Skip to content

Getting Started

Welcome! This page takes you from an empty Rust project to your first compiled neural network in a few minutes.

1. Install

Add jacobi to any Rust project.

cargo add jacobi

That is all you need. There is no C++ toolchain, protoc, or manual driver setup. On your first run, Jacobi detects your hardware (CPU, Apple Metal, NVIDIA CUDA, ROCm, or TPU) and caches the PJRT runtime in ~/.jacobi/.

Choosing a backend

Jacobi picks the best device automatically. To pin a specific backend, call use_backend(Backend::Cpu)? in code or set JACOBI_BACKEND=cpu in your shell.

2. Tensors and Math

Import jacobi::prelude::* and create tensors just like you would in PyTorch.

use jacobi::prelude::*;

fn main() -> Result<()> {
    manual_seed(42);

    let a = Tensor::randn(&[2, 3]);
    let b = Tensor::ones(&[3, 4]);
    let c = a.matmul(&b).relu();

    println!("shape {:?}", c.shape());
    println!("mean  {:.4}", c.mean().item()?);
    Ok(())
}

Shape mismatches and runtime errors never panic mid-expression. They propagate quietly and return Err(...) when you call .item()?, .to_vec_f32()?, or jit(...).call(...)?.

3. Gradients

Wrap any scalar-valued closure in grad or value_and_grad.

let w = Tensor::from_f32(&[2.0, -1.0], &[2]);
let (loss, dw) = value_and_grad(|p| (&p * &p).sum(), &w);

println!("loss = {}", loss.item()?);       // 5
println!("dw   = {:?}", dw.to_vec_f32()?); // [4.0, -2.0]

4. Your First Model

Mark any Rust struct with #[module]. That automatically makes it differentiable, serializable, and ready for jit and optimizers.

use jacobi::prelude::*;

#[module]
struct Net {
    l1: Linear,
    l2: Linear,
}

impl Net {
    fn new() -> Self {
        Self {
            l1: Linear::new(2, 16),
            l2: Linear::new(16, 1),
        }
    }

    fn forward(&self, x: &Tensor) -> Tensor {
        self.l2.forward(&self.l1.forward(x).tanh())
    }
}

fn main() -> Result<()> {
    manual_seed(7);

    // Classic XOR dataset
    let x = Tensor::from_f32(&[0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0], &[4, 2]);
    let y = Tensor::from_f32(&[0.0, 1.0, 1.0, 0.0], &[4, 1]);

    let mut model = Net::new();
    let mut opt = AdamW::new(&model, 0.05);

    // Compile one full training step into a single XLA executable
    let train_step = jit(move |(mut m, mut o): (Net, AdamW<Net>)| {
        let (loss, grads) = value_and_grad(|p| nn::mse_loss(&p.forward(&x), &y), &m);
        o.step(&mut m, &grads);
        (m, o, loss)
    });

    for step in 0..80 {
        let loss;
        (model, opt, loss) = train_step.call((model, opt))?;
        if step % 20 == 0 || step == 79 {
            println!("step {step:2} loss = {:.4}", loss.item()?);
        }
    }

    model.save("xor.safetensors")?;
    Ok(())
}

Ready to explore more? Read the User Guide or browse the Examples.