A dependency-free neural network library written from scratch. It started as a learning project (a single hidden-layer perceptron for the Seeds dataset) and is now a reusable library with many neuron types, mini-batch training and cache-blocked, SIMD-vectorised, multi-threaded CPU kernels.
Neuron types
| Family | Types |
|---|---|
Transfer functions (nn::Activation) |
Linear, Sigmoid, Tanh, ReLU, LeakyReLU, ELU, SELU, GELU, Swish/SiLU, Mish, Softplus, Softsign, HardSigmoid, HardTanh, HardSwish, ReLU6, Gaussian, Sine, Step (perceptron), Softmax |
| Feed-forward layers | Dense (fully connected), RBF (radial basis neurons), Dropout, LayerNorm |
| Recurrent cells | SimpleRNN (Elman), LSTM, GRU — stackable via return_sequences |
| Convolutional | Conv2D, MaxPool2D |
Spiking neurons (nn::spiking) |
Leaky integrate-and-fire, Izhikevich (7 presets), adaptive exponential IF (AdEx), Hodgkin-Huxley; exponential synapses, Poisson input, STDP plasticity |
Training: MSE, MAE, Huber, categorical / binary cross-entropy (fused with softmax / sigmoid outputs), SGD (+momentum, Nesterov), Adam/AdamW, RMSProp, Adagrad, gradient clipping, weight decay, learning-rate schedules (step, exponential, cosine, reduce-on-plateau for automatic learning rate), validation split, early stopping with best-weight restore.
Utilities: fast CSV loader, label encoding, one-hot, train/test split, min-max and standard scalers, binary model save/load.
- Contiguous matrices instead of neuron objects. Each layer stores its
weights as one aligned
[in x out]matrix; a whole mini-batch is propagated with a single GEMM instead of one dot product per neuron. - Cache-blocked, register-blocked GEMM (4x16 micro-kernel, L2-sized
panels) parallelised over output tiles with OpenMP. Optional CBLAS
(
-DNN_USE_BLAS=ON, e.g. OpenBLAS/MKL) for maximum throughput. - Vectorised transcendental functions (
nn/fastmath.hpp): branch-free exp/log/tanh/sigmoid that the compiler turns into AVX/NEON code without-ffast-math; inputs are clamped so no subnormal numbers occur. - Zero allocations in the training loop: matrices only ever grow, all workspaces are reused between batches.
- Recurrent layers compute the input projection of all timesteps in one
large GEMM; only
h_{t-1} W_his sequential. - Spiking simulation uses structure-of-arrays state (vectorised neuron updates) and CSR synapses, so propagation cost scales with the number of spikes, not synapses. Random connectivity is generated by geometric skipping (O(synapses), not O(n²)).
Measured on an Intel N97 (4 cores, AVX2), ./build/nn_bench:
| Benchmark | Result |
|---|---|
| GEMM 256³ / 1024³ | ~80 / ~50-65 GFLOP/s |
| MLP 784-512-256-10 training (batch 128) | ~17,000 samples/s |
| MLP inference | ~60,000 samples/s |
| LSTM (T=32, H=128) training | ~2,100 sequences/s |
| 10k Izhikevich neurons, 1M synapses | ~7x faster than real time |
Requirements: C++17 compiler (GCC ≥ 8, Clang ≥ 7, MSVC 2019), CMake ≥ 3.14. OpenMP is used when available.
Classic program (default). Without flags the build is the same as
before: the original single-hidden-layer network (src/main.cpp, Neuron /
Layer / Network) is built as bin/NN.
mkdir build && cd build
cmake ..
make
cd ../bin && ./NNLibrary. The new nn library, tests, examples and benchmarks are enabled
with NN_BUILD_LIBRARY:
cmake -S . -B build -DNN_BUILD_LIBRARY=ON # Release by default
cmake --build build -j
ctest --test-dir build # or ./build/nn_tests
./build/nn_benchCMake options:
| Option | Default | Meaning |
|---|---|---|
NN_BUILD_LIBRARY |
OFF (top level), ON (add_subdirectory) | build the nn library and its extras |
NN_BUILD_LEGACY |
ON (top level) | build the classic bin/NN program |
NN_USE_OPENMP |
ON | multi-threaded kernels |
NN_USE_BLAS |
OFF | delegate GEMM to an external CBLAS |
NN_NATIVE_ARCH |
ON (top level) | -march=native; turn off for portable binaries |
NN_BUILD_EXAMPLES / NN_BUILD_TESTS / NN_BUILD_BENCHMARKS |
ON (top level) | extras |
BUILD_SHARED_LIBS |
OFF | build libnn.so instead of libnn.a |
GPU backends are opt-in CMake flags on top of NN_BUILD_LIBRARY. Every
backend can be compiled in at the same time; the device is chosen at runtime.
| Flag | Backend | Hardware | SDK |
|---|---|---|---|
NN_USE_OPENCL |
OpenCL 1.2 | Intel, AMD, NVIDIA, ARM Mali, Apple | OpenCL headers + ICD loader |
NN_USE_VULKAN |
Vulkan compute | any Vulkan GPU (Linux, Windows, Android, macOS via MoltenVK) | Vulkan SDK / libvulkan-dev |
NN_USE_CUDA |
CUDA + cuBLAS | NVIDIA | CUDA Toolkit |
NN_USE_HIP |
HIP + hipBLAS | AMD (ROCm) | ROCm / hipcc, libhipblas-dev |
NN_USE_SYCL |
SYCL | Intel GPUs, others via oneAPI plugins / AdaptiveCpp | SYCL compiler (icpx -fsycl) |
NN_USE_GPU |
all of the above that are found |
cmake -S . -B build -DNN_BUILD_LIBRARY=ON -DNN_USE_GPU=ON
cmake --build build -j
NN_BACKEND=vulkan ./build/example_mnist_like # or: opencl, cuda, hip, sycl, cpu#include <nn/nn.hpp>
if (!nn::set_backend(nn::Backend::CUDA)) // false if not compiled in / no device
nn::set_backend(nn::Backend::OpenCL);
std::cout << nn::device_name() << "\n";
nn::set_offload_threshold(1 << 24); // smaller products stay on the CPUHow it works: the GPU computes the matrix multiplications, which make up
almost all of the work in Dense, LSTM/GRU/SimpleRNN, Conv2D and RBF layers.
Products smaller than the offload threshold (default 2^26 multiply-adds,
NN_OFFLOAD_THRESHOLD) stay on the CPU because transfer and launch overhead
would dominate. If a GPU call fails, the library prints a warning and falls
back to the CPU. The whole test suite passes with every product forced onto
the GPU (NN_BACKEND=opencl NN_OFFLOAD_THRESHOLD=0 ./build/nn_tests).
Measured on the Intel N97's integrated UHD Graphics (24 EUs), including transfers: GEMM 1024³ ~80 (OpenCL) / ~90 (Vulkan) GFLOP/s vs ~50-60 on the CPU; MLP 784-2048-1024-10 training ~1.4x faster than the 4 CPU cores, small networks about equal. Discrete GPUs gain far more. OpenCL and Vulkan are tested on real hardware; CUDA and HIP are compiled against their SDKs but untested without NVIDIA/AMD hardware; SYCL is untested.
Install and use find_package:
cmake -S . -B build -DNN_BUILD_LIBRARY=ON && cmake --build build -j
cmake --install build --prefix /opt/nnfind_package(nn 2 REQUIRED) # with CMAKE_PREFIX_PATH=/opt/nn
target_link_libraries(myapp PRIVATE nn::nn)or vendor it:
add_subdirectory(external/NeuralNetwork) # examples/tests are off automatically
target_link_libraries(myapp PRIVATE nn::nn)#include <nn/nn.hpp>
nn::Matrix raw = nn::data::load_csv("data/seeds_dataset.csv");
auto [x, labels] = nn::data::split_xy(raw); // last column = label
std::size_t k = nn::data::encode_labels(labels);
nn::Matrix y = nn::data::one_hot(labels, k);
nn::data::StandardScaler().fit_transform(x);
nn::Network net(x.cols());
net.add<nn::Dense>(32, nn::Activation::gelu());
net.add<nn::Dropout>(0.1f);
net.add<nn::Dense>(k, nn::Activation::softmax());
net.compile(nn::Loss::CategoricalCrossEntropy, std::make_unique<nn::Adam>(1e-2f));
nn::FitOptions opt;
opt.epochs = 100;
opt.batch_size = 16;
opt.validation_split = 0.2f;
opt.schedule = nn::LRSchedule::reduce_on_plateau();
net.fit(x, y, opt);
auto classes = net.predict_classes(x);
net.save("model.nnet");
nn::Network again = nn::Network::load("model.nnet");Every layer consumes and produces matrices of shape [batch x features].
Structured layers interpret a row as a flattened tensor, so no reshape layers
are needed:
- Sequences (RNN/LSTM/GRU): time-major,
[x_0 | x_1 | ... | x_{T-1}],features = input_dim / timesteps. - Images (Conv2D/MaxPool2D): channel-height-width (
CHW).
nn::Network seq(T * F);
seq.add<nn::LSTM>(64, T, /*return_sequences=*/true);
seq.add<nn::GRU>(32, T);
seq.add<nn::Dense>(1);
nn::Network cnn(28 * 28);
auto& c1 = cnn.add<nn::Conv2D>(nn::Shape3{1, 28, 28}, 16, 3, 1, 1, nn::Activation::relu());
auto& p1 = cnn.add<nn::MaxPool2D>(c1.output_shape(), 2);
cnn.add<nn::Dense>(10, nn::Activation::softmax());namespace sp = nn::spiking;
sp::Network net(/*dt ms*/ 0.5f);
auto exc = net.add_population(8000, sp::IzhikevichParams::regular_spiking());
auto inh = net.add_population(2000, sp::IzhikevichParams::fast_spiking());
net.connect(exc, exc, 0.01f, 0.5f);
net.connect(inh, exc, 0.01f, -1.0f);
net.add_poisson_input(exc, 2000, 1.5f);
net.enable_stdp(exc, exc, sp::STDPParams{});
net.run(2000); // 1 s
float hz = net.firing_rate(exc);| Program | Shows |
|---|---|
example_seeds |
successor of the original demo: load/train/evaluate/save on the Seeds dataset |
example_xor |
the same problem solved with 14 different neuron types and an RBF network |
example_sequence |
time-series forecasting with stacked SimpleRNN / GRU / LSTM |
example_mnist_like |
small CNN on synthetic 16x16 shape images |
example_spiking |
10k-neuron Izhikevich network plus LIF / AdEx / HH cells |
include/nn/ public headers (nn.hpp = umbrella)
layers/ Dense, Dropout, RBF, LayerNorm, recurrent, conv
src/ implementation (library) + classic program (main.cpp, Neuron/Layer/NeuralNetwork.cpp)
tests/ self-contained test suite (gradient checks for every layer and activation)
benchmarks/ nn_bench
examples/ example programs
data/ Seeds dataset
docs/ background on neural network families
Networkreuses internal buffers and is not thread-safe; use one instance per thread for concurrent inference (copy viasave/load). The kernels themselves are multi-threaded.nn::set_num_threads(n)limits the thread count (alsoOMP_NUM_THREADS).- Model files are little-endian binary (
.nnet, format version 2). Files written by the old text-based version 1 cannot be loaded.
See LICENSE.txt.