# Jacobi Complete Documentation (llms-full.txt) > Jacobi is a machine learning framework for Rust compiled via XLA and PJRT to CPUs, GPUs (CUDA, Metal, ROCm), and TPUs. Zero C++ build tools, `protoc`, or `libclang` required. Repository: https://github.com/HenryNdubuaku/jacobi Documentation: https://henryndubuaku.github.io/jacobi/ Concise index: https://henryndubuaku.github.io/jacobi/llms.txt License: Apache-2.0 Crate: `jacobi` v0.1.2 (Rust edition 2024, MSRV 1.85) --- ## 1. Quick Start and Core Conventions Install with `cargo add jacobi` (or `jacobi = { version = "0.1", default-features = false }` for a minimal build without Hugging Face `tokenizers` and `hf-hub`). Always import `use jacobi::prelude::*;`. Key rules to avoid PyTorch, Burn, or Candle hallucinations: 1. Annotate model structs with `#[module]`. It derives `Clone` and implements `Module`. Plain config fields (`usize`, `f64`, `bool`, `String`, arrays, tuples, `Option`, `Vec`) pass through automatically. 2. Never write `loss.backward()` or `opt.zero_grad()`. Use `let (loss, grads) = value_and_grad(|p| p.loss(&x, &y), &model); opt.step(&mut model, &grads);`. 3. `jit` takes a single argument implementing `Module` (group multiple items into a tuple `(model, opt)`) and executes via `.call(...)` or `.call_async(...)?.wait()?`. 4. Tensor operations never panic mid-expression. Errors propagate lazily and surface as `Result` on `.item()?`, `.to_vec_f32()?`, `.to_host()?`, `.check()?`, or `jit.call(...)?`. 5. Slicing uses `t.slice_axis(axis, start, end)` (never `.slice(...)`), `t.index(-1)`, `t.dynamic_slice(&start, size)`, `t.dynamic_update_slice_axis(&upd, axis, &start)`, `t.take(&ids)`, `t.take_axis(&ids, axis)`, `t.gather(axis, &idx)`, and `t.scatter_add(axis, &idx, &upd)`. Direct-to-device uploads use `Tensor::from_host_on`, `Tensor::from_*_on(..., dev)`, and `Module::to_device(dev)`. 6. Convolutions (`Conv1d`, `Conv2d`, `Conv3d`) use channels-last layout (`[B, L, C]`, `[B, H, W, C]`, `[B, D, H, W, C]`). 7. RNG is implicit on device (`manual_seed(42)`, `Tensor::randn`, `Tensor::randperm`, `nn::dropout`, `logits.sample()`). ### Minimal Compiled Training Loop ```rust use jacobi::prelude::*; #[module] struct Net { l1: Linear, ln: LayerNorm, l2: Linear, } impl Net { fn new(in_dim: usize, hidden: usize, out_dim: usize) -> Self { Self { l1: Linear::new(in_dim, hidden), ln: LayerNorm::new(hidden), l2: Linear::new(hidden, out_dim), } } fn forward(&self, x: &Tensor) -> Tensor { self.l2.forward(&self.ln.forward(&self.l1.forward(x)).gelu()) } } fn main() -> Result<()> { manual_seed(42); let x = Tensor::randn(&[32, 4]); let y = Tensor::randn(&[32, 2]); let mut model = Net::new(4, 32, 2); let mut opt = AdamW::new(&model, 1e-3).weight_decay(1e-2); let step = jit_autocast(Dtype::BF16, move |(mut m, mut o): (Net, AdamW)| { let (loss, mut grads) = value_and_grad(|p| nn::mse_loss(&p.forward(&x), &y), &m); optim::clip_grad_norm(&mut grads, 1.0); o.step(&mut m, &grads); (m, o, loss) }); for i in 0..50 { opt.set_lr(optim::warmup_cosine(1e-3, i, 5, 50)); let loss; (model, opt, loss) = step.call((model, opt))?; if i % 10 == 0 { println!("step {i:2} loss = {:.4}", loss.item()?); } } model.save("net.safetensors")?; let sample_x = Tensor::randn(&[1, 4]); model.export_onnx(&sample_x, |m, x| m.forward(&x), "net.onnx")?; Ok(()) } ``` --- ## 2. Large-Scale LLM and MoE Training Primitives Jacobi includes native, differentiable StableHLO primitives designed to absorb distributed and long-context LLM complexity: - **Automatic cuDNN FlashAttention-2/3 (`nn::flash_attention`)**: On CUDA GPUs (`BF16`/`F16`, `16 <= D <= 256` multiple of 8, `S >= 64`), `nn::flash_attention(&q, &k, &v, causal, scale)` automatically emits `__cudnn$fmhaSoftmax` forward and `__cudnn$fmhaSoftmaxBackward` backward via `custom_vjp` (using exact analytical lower-triangular tiled FlashAttention-2 backward for `128 < D <= 256` on Blackwell where cuDNN 9 restricts backward to `D <= 128`). For `D > 256` (such as `D = 512`), CPU, Metal, TPU, or `F32`, it automatically runs causal lower-triangular block-tiled FlashAttention (`Q_TILE = 512` with `remat`). Set `JACOBI_CUDNN_FMHA=0` to disable cuDNN dispatch. - **Token-Sharded All-to-All Sparse MoE (`nn::moe_swiglu_dispatch_all_to_all`)**: Uses O(S_local * K) `argsort` + prefix-sum slot packing (zero dense `[E, S]` one-hot matrices) and two `all_to_all_axis` collectives (dispatch + combine) so each EP GPU runs independent sequences through Attention, Norms, Embeddings, Shared Experts, and LM Head. Accepts `[S, H]` or `[B, T, H]`. `MoeDispatchConfig::default()` auto-detects CUDA/TPU FP8 Tensor Cores. - **Constant-HBM Chunked LM Head (`nn::chunked_cross_entropy`, `nn::chunked_lm_head_loss`)**: Streams `chunk_tokens` tokens at a time through `lm_head_w` inside a checkpointed `for_loop` (handling non-divisible token counts with exact token weighting), eliminating `[B * T, V]` logit HBM spikes on 128k to 262k+ vocabularies. - **Checkpointed `for_loop` with O(1) Scatter and `F8E5M2` Gradient Accumulation**: Stacked `[L, ...]` layer weights inside `for_loop(L, ...)` compile in O(1) graph size, accumulate gradients via O(1) in-place scatter-add per layer (avoiding full-stack additions), and automatically accumulate large FP8 outer weight gradients in scaled 1-byte `F8E5M2` (cutting FP8 loop gradient HBM in half; opt out with `JACOBI_FP8_GRAD_ACC=0`). - **Native FP8 Weight Storage and Hardware-Aware Backward (`nn::quantized_matmul`)**: Keeps weights natively in `Dtype::F8E4M3FN` (1 byte/param), runs native FP8 Tensor Core matmuls on CUDA/TPU with automatic BF16 fallback on CPU/Metal, and automatically enables dynamic per-tensor scaled FP8 backward GEMMs on Blackwell (`sm_100`) and TPU while keeping faster BF16 backward on Hopper (`sm_90`) (override with `JACOBI_FP8_BWD=0|1`). - **Low-Rank Subspace Optimizer (`EfficientAdamW`)**: Cuts optimizer state HBM by 96% to 98.7%, streams large stacked `[L, E, M, N]` low-rank projections and weight updates layer-by-layer, supports periodic subspace refresh (`.update_proj_gap(10)`), and synchronizes compressed low-rank gradients across data-parallel or hybrid DP/EP axes (`value_and_grad_dp`, `value_and_grad_hybrid`). ### Multi-Node Hybrid DP + EP Sparse MoE Pattern ```rust use jacobi::prelude::*; fn run_distributed_moe() -> Result<()> { if let (Ok(addr), Ok(np), Ok(pid)) = ( std::env::var("JACOBI_COORDINATOR_ADDR"), std::env::var("JACOBI_NUM_PROCESSES"), std::env::var("JACOBI_PROCESS_ID"), ) { init_distributed(addr, np.parse().unwrap(), pid.parse().unwrap())?; } let mesh = Mesh::hybrid_dp_ep()?; let ep_size = mesh.axis_size("ep")?; let _step = shard_map( mesh, vec![PartitionSpec::replicated()], vec![PartitionSpec::replicated()], move |(mut shard, mut opt, x, y): (MoeShard, EfficientAdamW, Tensor, Tensor)| { let (loss, grads) = opt.value_and_grad_hybrid( |p| p.loss(&x, &y, 64, ep_size), &shard, &["ep", "dp"], |name| { if name.starts_with("w_gate") || name.starts_with("w_up") || name.starts_with("w_down") { vec!["dp"] } else { vec!["ep", "dp"] } }, ); opt.step(&mut shard, &grads); (shard, opt, loss) }, ); Ok(()) } ``` --- ## 3. Transforms, Control Flow, and Autodiff - `jit(f)` / `jit_autocast(Dtype::BF16, f)` / `jit_on(&engine, f)`: traces once per `(engine, precision, autocast, shapes, dtypes)`, caches in LRU + disk (`~/.jacobi/cache`), donates uniquely owned buffers automatically (`.donate(false)` to disable), pre-compiles with zero HBM via `.compile_for(&spec)?`, and supports async overlap via `.call_async(x)?.wait()?`. - `eval(f)` compiles and executes a one-off closure; `eval_shape(&inp, f)` infers output `Vec` with zero allocation. - Reverse-mode autodiff: `grad(f, &p)`, `value_and_grad(f, &p)`, `jacobian(f, &x)`, `efficient_grad(f, &p, rank)`, `value_and_efficient_grad(f, &p, rank)`. - Forward-mode and higher-order autodiff: `jvp(f, &primals, &tangents)`, `jacfwd(f, &x)`, `hvp(f, &primals, &tangents)`, `hessian(f, &x)`. - Checkpointing and custom VJP: `checkpoint(f, &x)` (alias `remat(f, &x)`), `custom_vjp(&x, fwd, bwd)`. - Vectorization: `vmap(f, &inputs)` maps across axis 0 and composes with `grad` and `jit`. - Compiled control flow and chunking: `for_loop(steps, init, body)`, `for_loop_selective`, `for_loop_auto`, `scan(&xs, init, step)`, `scan_selective`, `scan_auto`, `auto_ckpt_steps`, `map_chunks(chunk_size, &inputs, |chunk| ...)` (rematerializes each chunk with `checkpoint` during `grad`), `while_loop(init, cond, body)`, `cond(&pred, &operand, on_true, on_false)`, `switch(&index, &operand, &[...])`. - Multi-stream fusion and sparse LM heads: `nn::batch_fused_apply(&[&x1, &x2], |merged| ...)`, `nn::chunked_cross_entropy_indexed` / `nn::chunked_cross_entropy_indexed_tn` (aligned mixed dtypes with `F32` logit accumulation). - Multi-device handles and ordered prefetching: `Sharded` (`replicate`, `from_fn`, `zip`, `zip3`, `unzip`, `unzip3`) with `PmapFn::call_sharded` / `ShardMapFn::call_sharded_handle`, `DataLoader` (`.num_workers`, `.shard`, `.start_batch`, `.iter_epoch_from`), `HostTensor` (`from_bf16`, `from_f16`), and `Prefetcher` (`new`, `parallel`, `staged`, `pooled` + `.recycle`) for multi-worker and zero-allocation host pipelines. --- ## 4. Hugging Face, LoRA, Export, Interop, and Serving ### Loading Pretrained Hugging Face Weights + LoRA + Export ```rust use jacobi::prelude::*; fn load_and_export() -> Result<()> { let tok = Tokenizer::from_pretrained("Qwen/Qwen2.5-0.5B")?; let ids = tok.encode_tensor("Explain XLA compilation.")?; // Lazy memory-mapped safetensors loader let loader = hub::weights("Qwen/Qwen2.5-0.5B")?.dtype(Dtype::BF16); let q_proj = loader.pp("model.layers.0.self_attn.q_proj").linear(896, 896)?; let lora = LoraLinear::from_linear(q_proj, 16, 32.0); let merged = lora.merge(); // Export back to Hugging Face / Candle / vLLM safetensors format HfExporter::new() .dtype(Dtype::BF16) .add_linear("model.layers.0.self_attn.q_proj", &merged) .save_safetensors("merged.safetensors")?; let _ = ids; Ok(()) } ``` ### DLPack, XLA FFI, ONNX, StableHLO, and Serving - **DLPack**: `let cap = t.to_dlpack()?; let t2 = Tensor::from_dlpack(cap)?;` (zero-copy when supported by PJRT). - **XLA FFI**: `register_ffi_handler("name", fn_ptr)?`, `ffi_call_one(...)`, `ffi_call_with_vjp(...)`. - **Export**: `model.save("m.safetensors")?`, `model.load("m.safetensors")?`, `model.export(&sample_x, |m, x| m.forward(&x), "m.mlir")?`, `model.export_onnx(&sample_x, |m, x| m.forward(&x), "m.onnx")?`. - **HTTP Serving**: `jacobi::io::serve::serve_mlir("m.mlir", 8080)?` (binds `127.0.0.1` by default). --- ## 5. Hardware Backends and Environment Variables Select backend with `use_backend(Backend::Cpu | Backend::Cuda | Backend::Metal | Backend::Tpu | Backend::Rocm | Backend::OneApi | Backend::Auto | Backend::PluginPath(p))?`. | Environment Variable | Effect | | --- | --- | | `JACOBI_BACKEND` | Force `cpu`, `cuda`, `metal`, `tpu`, `rocm`, or `oneapi` | | `PJRT_PLUGIN_PATH` | Load a specific PJRT `.so` or `.dylib` directly | | `JACOBI_GPU_MEMORY_FRACTION` | PJRT GPU allocator fraction (e.g. `0.95`) | | `JACOBI_CUDNN_FMHA=0` | Disable automatic cuDNN FlashAttention-2/3 on CUDA | | `JACOBI_CUDNN_FMHA_BWD_256=1` | Force cuDNN backward for `128 < D <= 256` (Hopper only) | | `JACOBI_FP8_BWD=0\|1` | Override dynamic FP8 backward GEMMs (auto ON on Blackwell/TPU, OFF on Hopper) | | `JACOBI_FP8_GRAD_ACC=0` | Disable scaled `F8E5M2` outer loop gradient accumulation | | `JACOBI_COORDINATOR_ADDR` | Multi-node coordinator `host:port` | | `JACOBI_COORDINATOR_TOKEN` | Required shared auth token for all distributed coordinator binds (unless `JACOBI_COORDINATOR_ALLOW_UNAUTHENTICATED=1`) | | `JACOBI_NUM_PROCESSES` | Multi-node process count | | `JACOBI_PROCESS_ID` | Zero-based multi-node process rank | | `JACOBI_DEBUG_NANS=1` | Error immediately on any `NaN` or `Inf` output | | `JACOBI_OFFLINE=1` | Disable automatic PJRT plugin downloads | | `HF_TOKEN` | Hugging Face authentication token | --- ## 6. Domain Primitives: RL Rollout, Diffusion, and Speech - **RL Rollout, GRPO, PPO, and DPO (`jacobi::nn::rl`)**: - `RolloutConfig::default()` and `RolloutKvCache::default_rollout(layers, batch, kv_heads, head_dim)` default to `group_size = 16`, SageAttention, `512`-token sliding-window ring buffers, and FP8 (`F8E4M3FN`, `F16` fallback on Metal) KV storage updated in place via single-op 5D `dynamic_update_slice`. - `nn::kv_cache_attention`, `nn::sage_attention(&q, &k, &v, mask, scale)`, and `nn::kv_cache_attention_with_options(..., sliding_window, use_sage, scale)` combine per-head K-smoothing, GQA/MQA collapse, and native FP8 `Q @ K^T` on CUDA/TPU. - `batched_rollout_loop`, `gather_token_log_probs`, `grpo_advantages`, `grpo_loss`, `gae_advantages`, `ppo_clipped_loss`, and `dpo_loss`. - **Diffusion & Rectified Flow Matching (`jacobi::nn::diffusion`)**: - `patchify_2d`, `unpatchify_2d`, `rope_2d`, `timestep_embedding`, `modulate`, `ada_ln_zero`, `logit_normal_timesteps`, `flow_matching_interpolate`, `flow_matching_loss`, and `NoiseSchedule::{linear, cosine}`. - **Speech & Audio (`jacobi::nn::audio`)**: - On-device `stft_power`, `log_mel_spectrogram`, `spec_augment`, `CausalConv1d`, channel-last `ConformerConvModule`, and log-space differentiable `ctc_loss`. - **FP8 Optimizer Modes (`jacobi::optim::Fp8UpdateMode`)**: - `MasterF32` (`+4 B/param`, default), `MasterBf16` (`+2 B/param`), and `StochasticRounding` (`0` extra bytes, unbiased) across `Sgd`, `RMSprop`, `Adam`, `AdamW`, `Muon`, and `EfficientAdamW`. --- ## 7. Architecture Benchmarks (4,096 Context, FP8, `PleIAs/SYNTH` Cross-Entropy & Rollout) Measured on random-weight architecture replicas with live `PleIAs/SYNTH` next-token cross-entropy and batched RL Rollout (`4,096`-token FlashAttention prefill + `1,024` rollout tokens, group-16, SageAttention + `window=512` FP8 KV cache). Cluster `Peak RAM` is `device-0 peak HBM x GPU count`. | Model | Hardware | Parallelism | Mode | Batch | Peak RAM (dev0 x N) | Throughput | 15-Step CE Loss | Cost / 1T | | --- | --- | --- | --- | --- | --- | --- | --- | --- | | Gemma-4-E4B (7.4B) | 1x B200 180GB | Single GPU | Forward | 16 | 21.59 GB | 154,127.0 tok/s | N/A | $9.0k | | Gemma-4-E4B (7.4B) | 1x B200 180GB | Single GPU | Train (Full AdamW) | 8 | 155.07 GB | 35,020.9 tok/s | 12.83 -> 8.85 | $39.7k | | Gemma-4-E4B (7.4B) | 1x B200 180GB | Single GPU | Rollout (Sage + SW-512, 4k->1k) | 512 | 20.17 GB | 30,998.7 tok/s | N/A | $44.8k | | Inkling-2-Mini (26B) | 8x H200 141GB | Expert Parallel | Forward | 192 | 210.00 GB | 356,043.9 tok/s | N/A | $21.8k | | Inkling-2-Mini (26B) | 8x H200 141GB | Expert Parallel | Train (Full AdamW) | 192 | 1,015.44 GB | 105,419.8 tok/s | 12.66 -> 8.32 | $73.8k | | Inkling-2-Mini (26B) | 8x H200 141GB | Expert Parallel | Rollout (Sage + SW-512, 4k->1k) | 2,048 | 149.76 GB | 63,084.2 tok/s | N/A | $123.3k | | DeepSeek-V4-Flash (283B) | 16x H200 141GB | Data + Expert Parallel | Forward | 64 | 743.84 GB | 217,233.5 tok/s | N/A | $71.6k | | DeepSeek-V4-Flash (283B) | 16x H200 141GB | Data + Expert Parallel | Train (Rank-32 EfficientAdamW) | 80 | 2,115.04 GB | 52,965.7 tok/s | 12.57 -> 10.62 | $293.7k | | DeepSeek-V4-Flash (283B) | 16x H200 141GB | Data + Expert Parallel | Train (AdamW) | 16 (min) | OOM (>2,256 GB) | OOM | N/A | N/A | | DeepSeek-V4-Flash (283B) | 16x H200 141GB | Data + Expert Parallel | Rollout (Sage + SW-512, 4k->1k) | 2,048 | 796.80 GB | 42,923.5 tok/s | N/A | $362.4k | Source examples: - https://github.com/HenryNdubuaku/jacobi/blob/main/examples/diffusion.rs - https://github.com/HenryNdubuaku/jacobi/blob/main/examples/speech_to_speech.rs - https://github.com/HenryNdubuaku/jacobi/blob/main/examples/grpo.rs - https://github.com/HenryNdubuaku/jacobi/blob/main/examples/ppo.rs - https://github.com/HenryNdubuaku/jacobi/blob/main/examples/rl_rollout.rs - https://github.com/HenryNdubuaku/jacobi/blob/main/examples/gemma4_e4b.rs - https://github.com/HenryNdubuaku/jacobi/blob/main/examples/inkling_mini_2_26b.rs - https://github.com/HenryNdubuaku/jacobi/blob/main/examples/deepseek_v4_flash.rs - https://github.com/HenryNdubuaku/jacobi/blob/main/examples/efficient_grad.rs - https://github.com/HenryNdubuaku/jacobi/blob/main/examples/qwen.rs - https://github.com/HenryNdubuaku/jacobi/blob/main/examples/gpt.rs - https://github.com/HenryNdubuaku/jacobi/blob/main/examples/vit.rs - https://github.com/HenryNdubuaku/jacobi/blob/main/examples/cnn.rs - https://github.com/HenryNdubuaku/jacobi/blob/main/examples/mlp.rs