MLP and Fused Epochs¶
Full source in examples/mlp.rs. Run it with cargo run --release --example mlp.
What This Shows¶
- Defining a trainable model with
#[module]andLinear - Compiling an entire training epoch (shuffle, minibatch slicing,
grad, andSgdupdates) into a single XLA program withfor_loop - Saving and reloading
.safetensorscheckpoints
Model Definition¶
#[module]
struct Mlp {
l1: Linear,
l2: Linear,
}
impl Mlp {
fn new(hidden: usize) -> Self {
Self {
l1: Linear::new(1, hidden),
l2: Linear::new(hidden, 1),
}
}
fn forward(&self, x: &Tensor) -> Tensor {
self.l2.forward(&self.l1.forward(x).tanh())
}
fn loss(&self, x: &Tensor, targets: &Tensor) -> Tensor {
nn::mse_loss(&self.forward(x), targets)
}
}
Fused Epoch Loop¶
Instead of bouncing back to Rust for every minibatch, jit and for_loop compile all 64 minibatches into one device call.
let mut model = Mlp::new(128);
let mut opt = Sgd::new(&model, 0.03);
let train_epoch = jit(move |(mut model, mut opt): (Mlp, Sgd<Mlp>)| {
let perm = Tensor::randperm(n);
let xs = inputs.take(&perm);
let ts = targets.take(&perm);
(model, opt) = for_loop(batches, (model, opt), |step, (mut m, mut o)| {
let start = step * (batch_size as f64);
let x = xs.dynamic_slice(&start, batch_size);
let t = ts.dynamic_slice(&start, batch_size);
let grads = grad(|p| p.loss(&x, &t), &m);
o.step(&mut m, &grads);
(m, o)
});
let epoch_loss = model.loss(&inputs, &targets);
(model, opt, epoch_loss)
});
After 20 epochs, the script saves jacobi_mlp.safetensors, reloads the weights, and prints predictions. You can also export to ONNX (model.export_onnx(...)) or StableHLO (model.export(...)).