Modules and Neural Networks
Reference for jacobi::module, the #[module] macro, and jacobi::nn.
#[module] and Module Trait (jacobi::module)
Annotate any Rust struct with #[module] to automatically derive Clone and implement Module. Non-tensor config fields (usize, i32, i64, f32, f64, bool, String, arrays, tuples, Option<T>, Vec<T>) pass through untouched.
| Method / Function |
Signature |
Description |
| Parameter count |
model.num_params() -> usize |
Total scalar element count across all tensor leaves |
| Checkpointing |
model.save(path) -> Result<()>, model.load(path) -> Result<Self> |
Memory-mapped PyTorch-compatible .safetensors serialization |
| Export |
model.export(&sample_x, \|m, x\| ..., path), model.export_onnx(&sample_x, \|m, x\| ..., path) |
Export standalone StableHLO .mlir or ONNX (IR v9, Opset 18) |
| Dtype casting |
model.to_bf16(), to_f16(), to_f32(), to_dtype(Dtype) |
Cast all floating-point tensor leaves |
| Device placement |
model.to_device(device_idx: usize) -> Result<Self>, to_device(&m, device_idx) |
Move all tensor leaves of a module to device_idx |
| Tree utilities |
leaves(&m), named_leaves(&m), unflatten(&template, &leaves), module_map(&m, f), module_zip_map(&a, &b, f) |
Functional pytree traversal and reconstruction |
| Flat parameter vector |
ravel_module(&m) -> (Tensor, Unravel<M>) |
Pack all parameters into one 1D Tensor with an inverse Unravel<M> handle |
Built-In Layers (jacobi::nn)
Core and Parameter-Efficient Layers
| Layer |
Constructors & Builders |
Forward & Helpers |
Linear |
Linear::new(in_f, out_f) |
.forward(&x) (fields w, b) |
LoraLinear |
LoraLinear::from_linear(linear, rank, alpha) |
.forward(&x), .merge() -> Linear (freezes base_w/base_b; exposes only a, b as Module leaves) |
Sequential |
Sequential::new().add(layer).add_fn(\|x\| ...).add_residual(block) |
Implements Module and Layer (.push, .push_fn, .push_residual, .forward(&x)) |
Embedding |
Embedding::new(num_embeddings, embed_dim) |
.forward(&token_ids) (field w) |
Dropout |
Dropout::new(p: f64) |
.forward(&x, training: bool) |
Normalization Layers
| Layer |
Constructors & Builders |
Forward & Notes |
LayerNorm |
LayerNorm::new(dim).eps(1e-5) |
.forward(&x) (auto f32 stats for low-precision inputs) |
RmsNorm |
RmsNorm::new(dim).eps(1e-5) |
.forward(&x) (auto f32 stats via nn::rms_norm) |
GroupNorm |
GroupNorm::new(num_groups, num_channels).eps(1e-5) |
.forward(&x) on channels-last [B, ..., C] |
BatchNorm2d |
BatchNorm2d::new(channels).momentum(0.1).eps(1e-5) |
Functional .forward_train(&x) -> (Tensor, BatchNormStats), .apply_stats(stats), .forward_eval(&x), .forward(&x, training), and .forward_mut(&mut self, &x, training) |
Convolutions (Channels-Last)
| Layer |
Constructors & Builders |
Layout |
Conv1d |
new(in_c, out_c, k), grouped(..., groups), depthwise(c, k), .stride(s), .padding(p) |
[B, L, C] |
Conv2d |
new(in_c, out_c, k), new_2d(in_c, out_c, [kh, kw]), grouped, depthwise, .stride, .stride_2d, .padding, .padding_2d |
[B, H, W, C] |
Conv3d |
new(in_c, out_c, k), grouped, depthwise, .stride, .stride_3d, .padding |
[B, D, H, W, C] |
ConvTranspose1d |
new(in_c, out_c, k), .stride, .padding, .output_padding |
[B, L, C] |
ConvTranspose2d |
new(in_c, out_c, k), new_2d, .stride, .padding, .output_padding |
[B, H, W, C] |
Attention, RoPE, and KV Caching
| Layer |
Constructors |
Methods |
RoPE |
RoPE::new(head_dim, max_seq_len), RoPE::with_base(head_dim, max_seq_len, base) |
.apply(&x, offset), .apply_dynamic(&x, &pos) (symbolic O(1) MLIR) |
KvCache |
KvCache::new(b, kv_heads, max_seq, head_dim), KvCache::with_dtype(..., dtype) |
.append(&k, &v), .update_dynamic(&k, &v, &pos), .reset() |
MultiheadAttention |
MultiheadAttention::new(dim, heads), MultiheadAttention::gqa(dim, heads, kv_heads) |
.forward(&x, mask), .forward_with_rope(&x, &rope, offset, mask), .forward_with_cache(&x, rope, &mut cache, mask), .forward_with_dynamic_cache(&x, rope, &mut cache, &pos, mask) |
Large-Scale LLM Primitives (jacobi::nn)
FlashAttention
pub fn flash_attention(
q: &Tensor,
k: &Tensor,
v: &Tensor,
causal: bool,
scale: Option<f64>,
) -> Tensor
- Expects 4D
[B, H_q, S_q, D] queries and [B, H_kv, S_kv, D] keys/values (H_q % H_kv == 0 for MHA, GQA, and MQA).
- On CUDA (
BF16/F16, 16 <= D <= 256 multiple of 8, S >= 64), automatically lowers to cuDNN FlashAttention-2/3 (__cudnn$fmhaSoftmax + __cudnn$fmhaSoftmaxBackward, or exact analytical lower-triangular tiled backward for 128 < D <= 256 on Blackwell). Disable with JACOBI_CUDNN_FMHA=0.
- On
D > 256 (such as D = 512), CPU, Metal, TPU, or F32, runs causal lower-triangular block-tiled FlashAttention (Q_TILE = 512 under remat) for S >= 1024.
- Related functions
nn::flash_attention_varlen(&q, &k, &v, &q_lens, &kv_lens, causal, scale), nn::cudnn_fmha_custom_call(&q, &k, &v, causal, scale), nn::scaled_dot_product_attention(&q, &k, &v, mask), nn::causal_mask(seq_len), and nn::kv_cache_mask(max_seq, step_len, &pos).
Sparse Capacity-Bounded MoE
let cfg = MoeDispatchConfig::default()
.capacity_factor(1.25)
.swiglu_clamp(10.0);
let y = nn::moe_swiglu_dispatch_all_to_all(
&x, &top_idx, &top_weights,
&w_gate, &w_up, &w_down,
n_experts_total, ep_size, Some("ep"), cfg,
);
MoeDispatchConfig builder methods .capacity_factor(f64) (default 1.25), .softcap(gate, up), .swiglu_clamp(limit), and .native_fp8_dot(bool) (auto-detects CUDA/TPU by default).
nn::moe_swiglu_dispatch_all_to_all token-sharded O(SK) argsort + prefix-sum slot packing with all_to_all_axis dispatch/combine across Expert-Parallel ranks. Accepts [S, H] or [B, T, H].
nn::moe_swiglu_dispatch and nn::moe_swiglu_dispatch_local replicated-token capacity-bounded MoE dispatch (with optional deferred psum_axis for fused TP+EP shared experts).
Chunked Large-Vocabulary LM Head and Multi-Stream Fusion
nn::chunked_lm_head_loss(&hidden, &lm_head_w, chunk_tokens, |logits| ...) and nn::chunked_lm_head_loss_tn stream chunk_tokens tokens at a time through [H, V] or [V, H] heads inside a checkpointed for_loop with mixed-dtype alignment, F32 logit accumulation, and exact token-weighted remainder handling.
nn::chunked_cross_entropy(&hidden, &lm_head_w, &targets, chunk_tokens), nn::chunked_cross_entropy_with_softcap, and nn::chunked_cross_entropy_tn exact drop-in replacements for dense cross-entropy at 16x to 150x lower peak HBM.
nn::chunked_cross_entropy_indexed(&hidden, &lm_head_w, &flat_indices, &targets, chunk_tokens, softcap) and nn::chunked_cross_entropy_indexed_tn gather only supervised flat_indices before projecting into vocabulary space for MLM, masked reconstruction, or assistant-only SFT.
nn::batch_fused_apply(&[&x1, &x2, ...], |merged| ...) concatenates multiple streams along batch axis 0, evaluates a shared encoder once for larger GEMMs and fewer kernel launches, and slices every output leaf matching sum(B_i) back into per-stream outputs.
Quantized Linear & Matmul Helpers
nn::quantized_matmul(&x, &w) and nn::quantized_linear(&x, &w_out_in) multiply against weights stored natively in F8E4M3FN, F8E5M2, F4E2M1FN, BF16, F16, or F32 (aligning mixed input/weight dtypes automatically), using CUDA/TPU native Tensor Core matmul_in with BF16 accumulation and falling back to BF16 on CPU/Metal.
nn::fp8_matmul(&x, &w) / nn::fp8_linear(&linear, &x) dynamically scaled FP8 (F8E4M3FN) with f32 accumulation and straight-through master weight gradients.
nn::fp4_matmul(&x, &w) / nn::fp4_linear(&linear, &x) dynamically scaled NVFP4 (F4E2M1FN) with f32 accumulation.
Functional Activations, Norms, Losses, and Sampling
- Activations and norms
nn::relu, nn::gelu, nn::gelu_exact, nn::silu, nn::sigmoid, nn::log_sigmoid, nn::leaky_relu(&x, slope), nn::elu(&x, alpha), nn::softplus, nn::mish, nn::swiglu(&gate, &up), nn::softcap(&x, cap), nn::softmax, nn::log_softmax, nn::log_softmax_axis(&x, axis), nn::layer_norm(&x, &gain, &bias, eps), nn::rms_norm(&x, &gain, eps), nn::dropout(&x, p).
- Losses
nn::mse / nn::mse_loss, nn::l1_loss, nn::smooth_l1_loss(&pred, &target, beta), nn::huber_loss(&pred, &target, delta), nn::bce_with_logits(&logits, &targets), nn::kl_div(&log_probs, &target_probs), nn::cosine_similarity(&a, &b, axis, eps), nn::cross_entropy(&logits, &targets), nn::cross_entropy_with_options(&logits, &targets, label_smoothing, ignore_index).
- Sampling
nn::sample(&logits), nn::sample_top_k(&logits, k, temp), nn::sample_top_p(&logits, p, temp).