nbml
A minimal machine learning library built on ndarray for low-level ML algorithm development in Rust.
Unlike high-level frameworks, nbml provides bare primitives and a lightweight optimizer API for building custom neural networks from scratch. If you want comfortable abstractions, see Burn. If you want to understand what's happening under the hood and have full control, nbml gives you the building blocks.
Features
- Core primitives: Transformers, Attention, LSTM, Conv2D, Feedforward layers, etc
- Activation functions: ReLU, Sigmoid, Tanh, etc
- Layers: Softmax, LayerNorm, Sequence Pooling
- Optimizers: AdamW, SGD
- Utilities: Variable Sequence Batching, Gradient Clipping, Gumbel Softmax, Plots, etc
- Minimal abstractions: Direct ndarray integration for custom algorithms
Quick Start
use ;
use FFN;
use ;
// Build a simple feedforward network
let mut model = FFNnew;
// Create optimizer
let mut optimizer = default.with;
// Training loop, where x is (batch_size, 784) and y is (batch_size, 1)
for in training_data
Losses in nbml::f all return (loss, d_loss) — the scalar you log and the gradient you feed
straight back into backward(). See f::mse_loss, f::bce_loss, f::cross_entropy_loss, etc, and
their batch_* counterparts for 3D (batched sequence) inputs.
Architecture
NN Layers (nbml::nn)
Layer: Single nonlinear projection layerFFN: Feedforward network with configurable layersPositionwiseFFN: Two-layer position-wise feedforward block (used by the transformers)RNN: Vanilla recurrent neural networkLSTM: Long Short-Term Memory NetworkGRU: Gated Recurrent UnitESN: Echo-state network, fixed recurrence + readoutLSM: Liquid state machineRNNReservoir: RNN reservoir (used by ESN)SNNReservoir: Spiking neural network reservoir (used by LSM)Conv2D: Explicit Im2Col Conv2D layer (CPU efficient, memory hungry)PatchwiseConv2D: Patchwise Conv2D layer (CPU hungry, memory efficient)LinearSSM: Discrete Linear SSMAttention: Core softmax attention primitiveSelfAttention: Multi-head self attentionCrossAttention: Multi-head cross attentionGATv2: Sparse v2 graph attention (Brody et al., 2022)GATv2Transformer: Transformer block using sparse v2 graph attention.LinearAttention: Linear self attention with recurrent matrix-valued state. Subquadratic alternative to softmax attention (Katharopoulos et al., 2020)GatedLinearAttention: Gated linear attention with matrix-valued state and outer-product gating (Yang et al., 2024)DeltaNet: Linear attention with delta rule for error-corrected state updates (Yang et al., 2024)GatedDeltaNet: Gated delta network combining data-dependent gating with delta rule updates (Yang et al., 2025)Transformer: Transformer encoder/decoder blockLinearTransformerBase<A>: Transformer block generic over anyLinearAttentionLikemixer, with these aliases:LinearTransformer:LinearTransformerBase<LinearAttention>GlaTransformer:LinearTransformerBase<GatedLinearAttention>DeltaNetTransformer:LinearTransformerBase<DeltaNet>GdnTransformer:LinearTransformerBase<GatedDeltaNet>
nbml::nn::experimental holds work-in-progress modules (SelectiveSSM, DenseSelectiveSSM,
LinearCrossAttention). It is not re-exported from nbml::nn, so import it by full path. Expect
its API to change.
Layers (nbml::layers)
Layers that are only useful as components of other modules:
Dropout: Stateful dropout layerEmbedding: Learnable token embeddingsL2Norm: L2 normalizationLinear: Affine transformationSoftmax: Row-wise softmaxLayerNorm: Layer normalizationSequencePooling: Sequence mean-poolingLastTokenPooling: Last-token pooling, selects last token output only. For causal tasks.
Modeling (nbml::modeling)
Thin wrappers that assemble primitives into a full model.
CausalLM<M>: Embedding → sequence model → LM head, withtrain_step()wiring up cross entropy.Mis any type you implementCausalSequenceModelfor (see the example below).
nbml also re-exports ndarray, ndarray_rand, and ndarray_stats, so you don't have to pin
matching versions yourself: use nbml::ndarray::Array3;
Optimizers (nbml::optim)
ToParams
ToParams connects your model's weights and gradients to the optimizer. Implement params() to return a list of Param entries, each pairing a weight array with its gradient. The optimizer reads these pointers on each step to update weights in-place — no ownership transfer, no framework magic.
Param::new and with_grad accept any ndarray dimension (Array1, Array2, Array3, etc.), so you don't need separate methods per shape:
Params compose — bubble them up from sub-modules to build arbitrary architectures:
ToParams also provides zero_grads() to reset all gradient arrays after an optimizer step:
let mut aa = new;
aa.forward // <- implement this yourself
aa.backward // <- implement this yourself
optimizer.step;
aa.zero_grads;
Because params() already enumerates every weight in the tree, ToParams gets serialization for
free — dump()/load() move weights through Vec<TensorData>, and persist()/restore() do the
same via a bincode file:
let mut lstm = LSTMnew;
lstm.persist?;
let mut restored = LSTMnew;
restored.restore?; // same architecture, weights copied in place
Available optimizers:
AdamW: Adaptive moment estimation with weight decaySGD: Stochastic gradient descent
Use .with(&mut impl ToParams) to initialize a stateful optimizer (like AdamW) for your network:
let mut model = new;
let mut optim = default.with; // creates momentum/variance state for all parameters
optim.learning_rate = 1e-3;
ToIntermediates
ToIntermediates lets you snapshot and restore a module's cached activations (the values stored during forward() that backward() needs for gradient computation). This enables training loops that aren't possible in standard frameworks:
- Recursive / weight-tied depth: Forward the same module N times, stashing intermediates between each call. During backward, restore each stash in reverse to compute correct weight gradients for every application.
- Online learning with rollback: Checkpoint recurrent state mid-sequence, run an optimizer step, then restore and continue from the checkpoint.
Implement intermediates() to return mutable references to your cached values:
Then stash_intermediates() and apply_intermediates() work automatically:
let mut model = new;
// Forward pass A
model.forward;
let stash_a = model.stash_intermediates;
// Forward pass B (overwrites cache)
model.forward;
model.backward; // correct grads for B
// Restore A's cache, compute A's grads
model.apply_intermediates;
model.backward; // correct grads for A
Intermediates are returned from stash_intermediates as Vec<ArrayD<f32>> - aliased as IntermediateCache.
Activation Functions (nbml::f)
use f;
use array;
let x = array!; // activations operate on 2D arrays
let activated = relu;
Includes derivatives for backpropagation: d_relu, d_tanh, d_sigmoid, etc.
f::Activation is the enum form used by Layer/FFN. Each variant carries its forward fn,
derivative, and weight initializer: Relu, LeakyRelu, SoftmaxCrossEntropy, Identity, Exp,
Sigmoid, Tanh, Softplus.
Design Philosophy
nbml is designed for:
- Experimentation / Research: Prototyping of novel architectures, through full control of forward and backward passes
- Nonstandard Architectures: A lot more freedom without autograd running the show
- Transparency: No hidden magic, every operation is explicit
- Compute-Constrained Deployment: Lightweight + no C deps. Very quick for small models
nbml is not designed for:
- Large Scale Production deployment (use PyTorch, TensorFlow, or Burn)
- Automatic differentiation (you wire up the backward pass for custom modules)
- GPU acceleration (CPU-only via ndarray)
The included nn primitives are technically plug and play, but when composing them you will have to wire backward() yourself.
use Activation;
use SequencePooling;
use ;
use ;
use ;
Examples
Custom LSTM Training
use f;
use LSTM;
use ;
let mut lstm = LSTMnew;
let mut optimizer = default.with;
// where batch.dim() is (batch_size, seq_len, features)
// and features == lstm.d_model == (128 in this case)
for in data
Multi-Head Attention
use SelfAttention;
let mut attention = new;
// where input.dim() is (batch_size, seq_len, features)
// features == d_in == (512 in this case)
// and mask == (batch_size, seq_len, seq_len)
// with each element as 1. or 0. depending on whether or not the token
// is attendable
let output = attention.forward;
Transformer Decoder
use Transformer;
use Array3;
use ToParams;
let mut transformer = new_decoder;
// Transformer takes a 2D pad mask, not a full attention mask. It broadcasts the
// pad mask to (batch_size, seq_len, seq_len) internally, and for decoders it
// intersects that with a causal mask for you. `pad_mask()` and `causal_mask()`
// are public if you want the expanded masks yourself.
let y_pred = transformer.forward;
// some bs.
let d_y_pred = ones;
transformer.backward;
transformer.zero_grads;
KV Cached Decoding
Transformer::forward_cached (decoders only) appends to caller-owned K/V caches so incremental
decoding doesn't re-attend over the whole prefix. It runs with grad = false throughout — it's for
inference, not training.
use Transformer;
use ;
let = ;
let mut model = new_decoder;
// x is (batch_size, seq_len, d_model)
// caches are (batch_size * n_head, cached_seq_len, d_head), starting empty
let mut k_cache = zeros;
let mut v_cache = zeros;
let mut y = zeros;
for t in 0..seq_len
SelfAttention::forward_cached and Attention::forward_cached expose the same mechanism one level
down, if you're assembling your own decoder.
Causal Language Model
CausalLM<M> bolts an Embedding and an LM head onto any sequence model that implements
CausalSequenceModel. Because of the orphan rule you implement that trait on your own type:
use ;
use ;
use Transformer;
use ;
let mut lm = new; // vocab_size, d_model
let mut optim = default.with;
// tokens / targets are (batch_size, seq_len) token ids, pad_mask is (batch_size, seq_len)
let loss = lm.train_step; // forward + cross entropy + backward
optim.step;
lm.zero_grads;
Variable Length Batching
use batch_with_mask;
// sequences: Vec<Array2<f32>>, each (seq_len_i, features)
let = batch_with_mask;
// x -> (batch_size, max_seq_len, features), zero padded
// pad_mask -> (batch_size, max_seq_len), 1. for real steps and 0. for padding
Runnable Examples
examples/ has end-to-end programs you can run directly:
cargo run --example xor
Features / Build Flags
blas— routes ndarray's matmuls through BLAS. On macOS the Accelerate framework is wired up by default viablas-src.