Models and Optimizers¶
Defining Models with #[module]¶
Apply #[module] to any Rust struct. Jacobi derives Clone and teaches jit, grad, jvp, vmap, optimizers, and checkpointing how to walk your struct's tensors.
Plain config fields (usize, f64, bool, String, arrays, tuples, Option<T>, Vec<T>) pass through automatically with no skip attributes needed.
#[module]
struct TransformerBlock {
norm: RmsNorm,
attn: MultiheadAttention,
proj: Linear,
heads: usize,
head_dim: usize,
}
Every #[module] gains helper methods out of the box.
model.num_params()returns total scalar parameter count.model.save("model.safetensors")?andmodel.load("model.safetensors")?save and reload PyTorch-compatible checkpoints.model.export(&sample_x, |m, x| m.forward(&x), "model.mlir")?exports standalone StableHLO MLIR with weights baked in.model.export_onnx(&sample_x, |m, x| m.forward(&x), "model.onnx")?exports a standalone ONNX model (IR v9, Opset 18) with named weights.model.to_bf16(),model.to_f16(),model.to_f32(), andmodel.to_dtype(dtype)cast all floating-point parameters.model.to_device(idx)?(orto_device(&model, idx)?) moves every tensor leaf of a module to targetdevice_idx.ravel_module(&model)packs all leaves into a single flat 1DTensoralongside anUnravel<M>handle for L-BFGS, Hessian analysis, or evolutionary algorithms.
Sequential Pipelines (Sequential and Layer)¶
For fast prototyping without boilerplate structs, compose any built-in or custom Layer and stateless closures in Sequential. It implements Module and Layer directly with no nested generic tuple types, so it works with jit, grad, AdamW, .save(), and .load().
let net = Sequential::new()
.add(Linear::new(784, 256))
.add_fn(|x| x.gelu())
.add(LayerNorm::new(256))
.add_residual(
Sequential::new()
.add(Linear::new(256, 256))
.add_fn(|x| x.silu())
.add(Linear::new(256, 256)),
)
.add(Linear::new(256, 10));
let y = net.forward(&x);
Built-in Layers (jacobi::nn)¶
| Layer or function | Usage |
|---|---|
Linear |
Linear::new(in_features, out_features) |
LoraLinear |
LoraLinear::from_linear(linear, rank, alpha) with frozen base weights and .merge() |
Sequential |
Sequential::new().add(layer).add_fn(\|x\| x.gelu()).add_residual(block) |
Conv1d / Conv2d / Conv3d |
Conv2d::new(in_ch, out_ch, k).stride(2), Conv2d::grouped(...), Conv2d::depthwise(ch, k) |
ConvTranspose1d / ConvTranspose2d |
ConvTranspose2d::new(in_ch, out_ch, k).stride(2).padding(1).output_padding(1) |
BatchNorm2d |
BatchNorm2d::new(channels) with functional forward_train, apply_stats, and forward_eval |
GroupNorm |
GroupNorm::new(num_groups, num_channels).eps(1e-5) (channels-last [B, ..., C]) |
LayerNorm / RmsNorm |
LayerNorm::new(dim) / RmsNorm::new(dim) (functional nn::layer_norm, nn::rms_norm) |
Embedding |
Embedding::new(vocab_size, embed_dim) |
RoPE |
RoPE::new(head_dim, max_seq_len) or RoPE::with_base(...) with .apply and .apply_dynamic |
MultiheadAttention |
MultiheadAttention::new(dim, heads) or MultiheadAttention::gqa(dim, heads, kv_heads) |
KvCache |
KvCache::new(batch, kv_heads, max_seq, head_dim) with .append(&k, &v) and .reset() |
Dropout / nn::dropout |
nn::dropout(&x, 0.1) |
| Activations and Norms | relu, leaky_relu, elu, softplus, mish, swiglu, softcap, gelu, silu, sigmoid, log_sigmoid, softmax, log_softmax, rms_norm, layer_norm |
| Attention and Sampling | nn::flash_attention, nn::flash_attention_varlen, nn::scaled_dot_product_attention, nn::causal_mask, nn::kv_cache_mask, nn::sample, nn::sample_top_k, nn::sample_top_p |
| MoE and Large Vocab | nn::moe_swiglu_dispatch, nn::moe_swiglu_dispatch_local, nn::moe_swiglu_dispatch_all_to_all, MoeDispatchConfig, nn::chunked_lm_head_loss, nn::chunked_cross_entropy, nn::chunked_cross_entropy_indexed, nn::chunked_cross_entropy_indexed_tn, nn::batch_fused_apply |
| Losses | mse_loss, l1_loss, smooth_l1_loss, huber_loss, bce_with_logits, kl_div, cosine_similarity, cross_entropy, cross_entropy_with_options, chunked_cross_entropy, chunked_lm_head_loss |
Large-Scale LLM Primitives (FlashAttention, Sparse MoE, and Chunked LM Head)¶
For 4K+ context and large-vocabulary LLMs, Jacobi provides native differentiable primitives that absorb HBM and routing complexity directly inside nn.
nn::flash_attention(&q, &k, &v, causal, scale)automatically dispatches to cuDNN FlashAttention-2/3 on CUDA (BF16/F16,16 <= D <= 256) and causal lower-triangular block-tiled FlashAttention for larger head dims or other backends.nn::moe_swiglu_dispatch_all_to_allandnn::moe_swiglu_dispatchimplement O(SK) capacity-bounded sparse SwiGLU MoE routing for both[S, H]and[B, T, H]inputs, with automatic backend FP8 Tensor Core detection viaMoeDispatchConfig::default().nn::chunked_cross_entropy(&hidden, &lm_head_w, &targets, chunk_tokens)andnn::chunked_lm_head_loss(&hidden, &lm_head_w, chunk_tokens, loss_fn)stream large vocabularies (128k to 262k+) through a checkpointedfor_loopwithout materializing[B * T, V]logits in HBM (handling non-divisible token counts automatically).
// Constant-HBM cross-entropy over a 262k vocabulary at 4K context
let loss = nn::chunked_cross_entropy(&hidden, &lm_head_w, &targets, 2048);
Transformers, RoPE, and KV Caching¶
MultiheadAttention supports standard MHA, grouped-query attention (GQA), and multi-query attention (MQA), with built-in rotary embeddings (RoPE) and fixed-shape device-side KvCache updates via dynamic_update_slice.
let rope = RoPE::new(64, 2048);
let attn = MultiheadAttention::gqa(512, 8, 2);
let mut cache = KvCache::new(1, 2, 2048, 64);
// Prefill or decode without recompiling XLA shapes
let out = attn.forward_with_cache(&x, Some(&rope), &mut cache, None);
Optimizers, EMA, and Schedules (jacobi::optim)¶
Optimizers own only their internal state (like Adam moments) and update your model in place with opt.step(&mut model, &grads). Your model always stays a plain M.
let mut model = MyNet::new();
let mut opt = AdamW::new(&model, 1e-3).weight_decay(1e-2);
let mut ema = Ema::new(&model, 0.999);
let train_step = jit(move |(mut m, mut o): (MyNet, AdamW<MyNet>)| {
let (loss, mut grads) = value_and_grad(|p| p.loss(&x, &y), &m);
optim::clip_grad_norm(&mut grads, 1.0);
o.step(&mut m, &grads);
(m, o, loss)
});
for step in 0..100 {
opt.set_lr(optim::warmup_cosine(1e-3, step, 10, 100)); // no recompile
let loss;
(model, opt, loss) = train_step.call((model, opt))?;
ema.step(&model);
}
Available optimizers are Sgd (with optional momentum and weight decay), Adam, AdamW, EfficientAdamW (low-rank subspace AdamW cutting optimizer HBM by 96% to 98.7% with layer-streamed projections and updates, periodic basis refresh via .update_proj_gap(k), and distributed low-rank gradient sync via .value_and_grad_dp / .value_and_grad_hybrid), RMSprop, and Muon (Newton-Schulz orthogonalized momentum for 2D matrix weights). Use .no_decay_1d(&model) or .weight_decay_filter(&model, |name, t| ...) on Adam and AdamW to skip weight decay on biases and normalization scales, and Adam::spec_for / AdamW::spec_for / EfficientAdamW::spec_for for zero-HBM AOT compilation. Ema tracks exponential moving averages of any #[module].
// Low-rank memory-efficient AdamW (rank 32)
let mut opt = EfficientAdamW::new(&model, 1e-3, 32)
.weight_decay(1e-2)
.update_proj_gap(10);
let (loss, eff_grads) = opt.value_and_grad(|p| p.loss(&x, &y), &model);
opt.step(&mut model, &eff_grads);
Gradient utilities include optim::clip_grad_norm, optim::clip_grad_value, and optim::global_norm. Built-in schedules are optim::linear_warmup, optim::step_decay, optim::one_cycle, optim::cosine_decay, optim::warmup_cosine, and optim::wsd_schedule.
Data Loading (Dataset, DataLoader, and Prefetcher)¶
Implement Dataset (len and get) and pass it to DataLoader for deterministic per-epoch shuffling, lazy batch indexing (no epoch-wide index vector copies), multi-worker parallel collation (.num_workers(n)), distributed sharding (.shard(rank, world_size)), mid-epoch checkpoint resumption (.start_batch(step) / .iter_epoch_from(epoch, step)), and background prefetching over Prefetcher. For zero-allocation host pipelines that reuse large batch buffers across steps, use Prefetcher::pooled(buffers, fill) and return each consumed buffer with prefetcher.recycle(buf). For multi-worker CPU preprocessing pipelines with explicit step indices or multi-stage curricula, use Prefetcher::parallel(start_step, end_step, num_workers, depth, make_batch) or Prefetcher::staged(stages, begin, end, num_workers, depth).
use std::sync::Arc;
let loader = DataLoader::new(Arc::new(my_dataset), 64, collate_fn)
.shuffle(true)
.drop_last(true)
.num_workers(4)
.shard(process_index(), num_processes())
.prefetch(2)
.seed(42);
for batch in loader.iter_epoch_from(epoch, resume_batch) {
// Runs across 4 background workers in strict order while the accelerator runs the previous batch
}