#5779·burn

cuda: graph-captured optimizers replay stale host scalars (learning rate)

Author: swfsqlCreated Sep 22, 2026Updated Sep 29, 2026
Labelsenhancement

(Analysis and reproduction prepared by Claude)

Feature request

Graph-capture support for training: a whole step (forward, backward, optimizer) recorded once by burn::tensor::capture and replayed. Small models on CUDA are host-bound, and a replay turns hundreds of launches into one dispatch. On a two-layer MLP, fwd+bwd and the full step replay ×6–10 faster than eager on an RTX 2060.

Most of this already works. Autodiff's forward and backward replay bit-exactly, and so does the whole step with plain SGD at a constant learning rate. With any other optimizer setup, the capture still succeeds (is_hardware() == true), but the replays train on wrong values, and nothing reports it. There are two causes, both in the optimizers.

  1. Host scalars are frozen into the graph. On sm_70+ cubecl passes a kernel's scalars as grid constants in its parameter block (server.rs#L866, enabled at runtime.rs#L223), and a graph captures them by value. (Below sm_70 they would go through the info buffer instead; not tested here.) Two optimizer scalars change per step:

    • the learning rate, in every optimizer's grad.mul_scalar(lr) (adam.rs#L82), so any schedule stops at its value at capture time;
    • Adam(W)'s bias correction, a host f32 computed from the host step count time (adam.rs#L194), so every replay applies the correction for the recorded step.
  2. Where an update lands is left to chance. A replay reads the buffers the recording read and writes the buffers it wrote. So state advances across replays only if the update landed in the same buffer it read. Optimizer::step is functional: it returns new tensors. burn-cubecl's binary ops reuse an operand's buffer when no other tensor holds it (can_mut, lhs first), so whether a result reuses the state's buffer depends on reference counts and operand order.

    • Plain SGD's tensor - delta (sgd.rs#L94) and Adam's moment_1.mul_scalar(β₁).add(…) (adam.rs#L156) have the state as an unshared lhs, so both land in place.
    • Momentum computes grad.clone().mul_scalar(1 − d).add(velocity · m) (momentum.rs#L64). The lhs is a gradient temporary, so the new velocity lands in a fresh buffer each step. Replays keep reading the velocity from before the capture. The same ops with the velocity written back into its own buffer (the learning rate still a host scalar) replay bit-exactly.
    • AdamW computes tensor.clone().mul_scalar(1 − lr·λ) (adamw.rs#L97). The clone makes the parameter shared, so the updated parameter moves to a fresh buffer every step. Every replay then recomputes the same step from the parameters as they were at capture: the loss below never moves.

    User code cannot repair this from outside. The per-parameter state lives in ModuleOptimizer::param_context, which is private (module_optimizer.rs#L61), and its only accessor, to_record, reads to the host, which is illegal inside a capture.

Both are fixable within burn's public Optimizer trait. An AdamW that (a) keeps the learning rate and the step count as [1] device tensors, and (b) writes the parameter and every state tensor back into its own buffer (slice_assign), replays bit-exactly, including under a decaying learning rate (sketch under Additional context). PyTorch's answer to the same problem is capturable=True on Adam/AdamW: the step count stays on the device and the learning rate may be a tensor.

To Reproduce

Cargo.toml (burn 9147c11a, main 2026-09-22; the output below is identical on burn 8f08fdad / cubecl fc902af1):

toml
[package]
name = "capture-train"
version = "0.1.0"
edition = "2024"

[dependencies.burn]
git = "https://github.com/tracel-ai/burn.git"
rev = "9147c11a19a5e2d46694c54d441eee0e006e096c"
default-features = false
features = ["cuda", "std", "autodiff", "optim"]

src/main.rs:

rust
use burn::nn::{Linear, LinearConfig};
use burn::optim::{
    AdamConfig, AdamWConfig, GradientsParams, ModuleOptimizer, SgdConfig,
    momentum::MomentumConfig,
};
use burn::prelude::*;
use burn::tensor::{Distribution, activation::relu};
use std::cell::{Cell, RefCell};

#[derive(Module, Debug)]
struct Mlp {
    l1: Linear,
    l2: Linear,
}

struct Trainer {
    model: Option<Mlp>,
    optim: ModuleOptimizer,
    lr: f64,
    x: Tensor<2>,
    y: Tensor<2>,
}

impl Trainer {
    fn new(opt: &str) -> Self {
        let device = Device::default();
        device.seed(0);
        let ad = device.clone().autodiff();
        let model = Mlp {
            l1: LinearConfig::new(32, 128).init(&ad),
            l2: LinearConfig::new(128, 8).init(&ad),
        };
        let x = Tensor::random([64, 32], Distribution::Normal(0.0, 1.0), &device);
        let y = Tensor::random([64, 8], Distribution::Normal(0.0, 1.0), &device);
        let optim = match opt {
            "sgd" => SgdConfig::new().init(),
            "sgd-mom" => SgdConfig::new().with_momentum(Some(MomentumConfig::new())).init(),
            "adam" => AdamConfig::new().init(),
            "adamw" => AdamWConfig::new().init(),
            other => panic!("OPT: {other}"),
        };
        Self { model: Some(model), optim, lr: 1e-2, x, y }
    }

    /// One training step on the fixed batch; the loss before the update.
    fn step(&mut self) -> Tensor<1> {
        let model = self.model.take().unwrap();
        let pred = model.l2.forward(relu(model.l1.forward(self.x.clone().autodiff())));
        let loss = (pred - self.y.clone().autodiff()).square().mean();
        let grads = GradientsParams::from_grads(loss.backward(), &model);
        self.model = Some(self.optim.step(self.lr, model, grads));
        loss.inner()
    }
}

fn main() {
    let opt = std::env::var("OPT").unwrap_or_else(|_| "sgd".into());
    let decay = std::env::var("DECAY").is_ok_and(|v| v == "1");
    let lr = |i: usize| if decay { 1e-2 * 0.9f64.powi(i as i32) } else { 1e-2 };
    let device = Device::default();
    let n = 6;

    // Graph: 2 eager steps (so the optimizer state exists), capture, replay.
    let trainer = RefCell::new(Trainer::new(&opt));
    for _ in 0..2 {
        trainer.borrow_mut().step();
    }
    let runs = Cell::new(0);
    let step = || {
        runs.set(runs.get() + 1);
        trainer.borrow_mut().step()
    };
    // One eager run first: a cold capture fails otherwise (#5772).
    drop(step());
    let mut graph = burn::tensor::capture(&device, step);
    assert!(graph.is_hardware(), "no hardware graph");
    // Every closure run but the recording was a real step.
    let executed = runs.get() - 1;
    let mut replayed = Vec::new();
    for i in 0..n {
        trainer.borrow_mut().lr = lr(i);
        let loss = unsafe { graph.replay() };
        replayed.push(loss.clone().into_scalar::<f32>());
    }

    // Eager: the same steps.
    let mut trainer = Trainer::new(&opt);
    for _ in 0..2 + executed {
        trainer.step();
    }
    println!("OPT={opt} DECAY={}\nstep  replayed   eager", decay as u8);
    for (i, replayed) in replayed.iter().enumerate() {
        trainer.lr = lr(i);
        let eager = trainer.step().into_scalar::<f32>();
        let mark = if *replayed == eager { "" } else { "  <- differs" };
        println!("{i:>4}  {replayed:.6}  {eager:.6}{mark}");
    }
}

Output (each loss is taken before its step's update, so the first wrong update shows one row later):

$ OPT=sgd cargo run --release
OPT=sgd DECAY=0
step  replayed   eager
   0  0.918741  0.918741
   1  0.916615  0.916615
   2  0.914526  0.914526
   3  0.912472  0.912472
   4  0.910453  0.910453
   5  0.908466  0.908466

$ OPT=sgd DECAY=1 cargo run --release
OPT=sgd DECAY=1
step  replayed   eager
   0  0.918741  0.918741
   1  0.916615  0.916615
   2  0.914526  0.914734  <- differs
   3  0.912472  0.913067  <- differs
   4  0.910453  0.911585  <- differs
   5  0.908466  0.910268  <- differs

$ OPT=sgd-mom cargo run --release
OPT=sgd-mom DECAY=0
step  replayed   eager
   0  0.896907  0.896907
   1  0.888069  0.888069
   2  0.880348  0.879023  <- differs
   3  0.873564  0.869911  <- differs
   4  0.867571  0.860839  <- differs
   5  0.862251  0.851879  <- differs

$ OPT=adam cargo run --release
OPT=adam DECAY=0
step  replayed   eager
   0  0.351527  0.351527
   1  0.301291  0.301291
   2  0.256269  0.257056  <- differs
   3  0.216355  0.218006  <- differs
   4  0.181890  0.184175  <- differs
   5  0.152281  0.154924  <- differs

$ OPT=adamw cargo run --release
OPT=adamw DECAY=0
step  replayed   eager
   0  0.351529  0.351529
   1  0.351529  0.301293  <- differs
   2  0.351529  0.257057  <- differs
   3  0.351529  0.218007  <- differs
   4  0.351529  0.184177  <- differs
   5  0.351529  0.154925  <- differs

The Adam drift is the frozen bias correction alone: after 3000 eager steps, when the correction barely changes from one step to the next, the same capture stays within 3e-5 of eager over 20 steps.

Expected behavior

A captured training step replays as the eager steps would, for burn's optimizers and learning-rate schedules. At minimum, a capture that cannot replay correctly should not look like one that can.

Additional context

Measured (a fuller harness: every input in a stable buffer, refreshed by a host write before each replay, and 20 replayed steps compared with the same closure run eagerly; MLP 32→128→8, batch 64, RTX 2060, burn 9147c11a; the pin gives the same outcomes):

captured closure replay ≡ eager eager ms/step replay ms/step
forward + backward bit-exact 0.95 0.16 ×6.1
full step, SGD bit-exact 1.32 0.17 ×7.8
full step, SGD + momentum differs from step 2 1.66 0.20 ×8.5
full step, the same momentum, velocity written back in place bit-exact 1.70 0.21 ×8.1
full step, Adam differs from step 2 2.41 0.25 ×9.7
full step, AdamW differs from step 2 (parameter buffer moves each step) 2.14 0.27 ×8.0
full step, AdamW with device lr/step + write-back (below) bit-exact 3.88 0.37 ×10.6
same, learning rate ×0.9 per step bit-exact 3.39 0.37 ×9.2

What a capturable optimizer needs — the AdamW above, through the public Optimizer trait (lr is a [1] tensor the host rewrites before each step; state persistence omitted):

rust
#[derive(Clone)]
struct GraphAdamW { lr: Tensor<1>, beta_1: f32, beta_2: f32, epsilon: f32, weight_decay: f32 }

#[derive(Clone)]
struct GraphAdamWState<const D: usize> { time: Tensor<1>, moment_1: Tensor<D>, moment_2: Tensor<D> }

/// `new` written into `old`'s buffer — in place once every op reading `old` consumed its clone.
fn assign<const D: usize>(old: Tensor<D>, new: Tensor<D>) -> Tensor<D> {
    let whole = old.dims().map(|d| 0..d);
    old.slice_assign(whole, new)
}

impl Optimizer for GraphAdamW {
    type State<const D: usize> = GraphAdamWState<D>;

    fn step<const D: usize>(
        &self, _lr: f64, tensor: Tensor<D>, grad: Tensor<D>, state: Option<Self::State<D>>,
    ) -> (Tensor<D>, Option<Self::State<D>>) {
        let state = state.unwrap_or_else(|| GraphAdamWState {
            time: Tensor::zeros([1], &grad.device()),
            moment_1: grad.zeros_like(),
            moment_2: grad.zeros_like(),
        });
        let bcast = |t: Tensor<1>| t.unsqueeze::<D>();
        let time = state.time.clone().add_scalar(1.0);
        let moment_1 = (state.moment_1.clone().mul_scalar(self.beta_1))
            .add(grad.clone().mul_scalar(1.0 - self.beta_1));
        let moment_2 = (state.moment_2.clone().mul_scalar(self.beta_2))
            .add(grad.square().mul_scalar(1.0 - self.beta_2));
        // 1 − βᵗ, on the device.
        let correction =
            |beta: f32| bcast(time.clone().mul_scalar(beta.ln()).exp().neg().add_scalar(1.0));
        let m1_hat = moment_1.clone().div(correction(self.beta_1));
        let m2_hat = moment_2.clone().div(correction(self.beta_2));
        let delta = m1_hat.div(m2_hat.sqrt().add_scalar(self.epsilon));
        let lr = bcast(self.lr.clone());
        let decay = lr.clone().mul_scalar(-self.weight_decay).add_scalar(1.0);
        let updated = tensor.clone().mul(decay) - delta.mul(lr);
        let state = GraphAdamWState {
            time: assign(state.time, time),
            moment_1: assign(state.moment_1, moment_1),
            moment_2: assign(state.moment_2, moment_2),
        };
        (assign(tensor, updated), Some(state))
    }

    fn to_device<const D: usize>(state: Self::State<D>, _device: &Device) -> Self::State<D> {
        state
    }
}

Which suggests, for burn-optim:

  • a device-side learning rate and step count: a learning rate that may be a device tensor, refreshed by the host between steps, and Adam(W)'s time kept on the device;
  • an in-place contract: step leaves the parameter and every state tensor in the buffer it read (a write-back like assign above, or ops with an explicit output), at least behind an opt-in flag like PyTorch's capturable;
  • or, failing those, device access to the optimizer state, so a caller can copy it back in place itself.

A capture could also check, cheaply, that the buffers the recording read are the ones it wrote, and warn otherwise. That is how the parameter case above was found: comparing buffer ids around the recording.

Two more pitfalls met on the way:

  • A forward on an autodiff device without a backward cannot be captured. Each run keeps its tape alive (in-use memory grows ~66 KB per step on the MLP above), so the recording must allocate. The capture is rejected (capture recorded 2 memory node(s): an allocation inside the capture window makes the graph un-relaunchable), and burn falls back to eager without saying so. For a no-grad pass, use the inner device.
  • Memory: on a 2048×1024→4096→1024 MLP (8.4 M parameters), a live graph of the SGD step holds 608 MiB in use against 48 MiB of live state, on both revs. That is likely the warm-up multiplication described in #5772's "Related" section (not decomposed here), and it weighs most on training, whose pass is the largest. Replays gain nothing at that size anyway, since the step is device-bound.

Environment

  • burn 9147c11a (main, 2026-09-22; cubecl 0.11.0-pre.4) and burn 8f08fdad / cubecl fc902af1, identical outcomes
  • RTX 2060 (6 GB, sm_75), CUDA 12.2, Ubuntu container
  • rustc 1.97.1, release build