Nemotron 3 Ultra: replaying a rounded state

Robert Joseph George · TorchLean Verified Examples

After Moonshot AI's Kimi K3 in the last example, I wanted to look at an open-source model from a US team too. NVIDIA's Nemotron 3 Ultra combines recurrent Mamba layers, attention, and routed experts in a model with 550 billion parameters (55 billion of them active for each token) that supports a million-token context. And NVIDIA released base, post-trained, and quantized checkpoints, along with training datasets and recipes. Nemotron 3 Ultra release ↗

I want to work through one idea: keep an older checkpoint, and when we need the current state, replay the recent inputs from it. Why bother replaying? NVIDIA explores it to cut the rounding error once the state is stored in fewer bits, and that error matters because a recurrent layer keeps overwriting its state, so rounding those numbers can affect later calculations. Let's first check when replay gives us the same state, then use FloatLib to ask what changes when we round the checkpoint.

NVIDIA's account of quantizing Ultra makes the practical choices clear. A quantized model mixes several formats (the routed experts use NVFP4, while the recurrent state cache uses FP16 with stochastic rounding), so saving memory comes down to choosing what to round, where to round it, and how to keep the rounding error small. Since we have the report and the implementation, I can follow those choices into the equations and state the assumptions my proofs need.

A language model carries information forward as it reads. Attention does this by storing keys and values for individual past tokens, while Mamba's state-space model (SSM) keeps a tensor called the state and updates its entries with each new input. Nemotron uses both. Its recurrent tensor keeps the same shape for the whole conversation, even though the numbers in it change at every step.

A recurrent layer updates its state once per token The initial state flows through three updates. Each update receives a new token and produces the state used by the next update. Initial stateUpdateUpdateUpdate Token 1Token 2Token 3 State after token 1State after token 2Current state
Each update reads the previous state and the new input, and every arrow carries a tensor of the same shape (not a growing list of all the earlier tokens).

In Nemotron 3 Ultra, those tensors span 48 Mamba blocks. Keeping them in FP32 takes 384 MiB per main-model sequence before any other allocations, and although each request’s state has a fixed shape, that cost grows with the number of requests being served together. So the report's §4.5 saves that memory by storing the state in fewer bits, and to reduce the rounding error this adds, it also explores keeping an older checkpoint and replaying the inputs since it was saved. NVIDIA tested it in emulation on Nemotron 3 Super (the Ultra release doesn't use it yet). I start with the memory calculation, then check when replay returns the same state and how rounding a checkpoint affects later updates. In the example below you can change the storage schedule and see why a smaller error budget need not mean a smaller actual error.

Counting the state and attention cache

Ultra's released BF16 configuration lists 108 residual blocks: 48 Mamba blocks, 48 MoE blocks, and 12 attention blocks. Mamba blocks hold recurrent state and attention blocks hold keys and values. I transcribed their order as releasedSchedule (each entry names one residual block), and Lean checks the counts. Mamba is a state-space layer: it updates a fixed-size state using coefficients chosen from the current input. A mixture-of-experts (MoE) block selects a few learned feed-forward transformations for each token. Attention instead keeps keys, which future queries compare against, and values, which their attention weights combine, so these three kinds of block have different storage needs.

Let's count the entries. Each Mamba-2 block has a state tensor of shape [256, 64, 128]: 256 heads, 64 value channels per head, and 128 state coordinates. One head stores \(64\times128=8{,}192\) entries, so all the heads give 2,097,152 entries in a block, and at four bytes per FP32 entry that's 8 MiB (here MiB means \(2^{20}\) bytes). Multiplying by 48 gives 384 MiB. The BF16 label on the model describes its weight representation, so don't read it as the precision of every working state. On the attention side, each block has two KV heads of width 128, so the 12 blocks add 6144 bytes of FP8 keys and values for each token.

Recurrent-state payload stays fixed while the attention cache grows For one main-model sequence, FP32 recurrent states occupy 384 MiB and FP16 states occupy 192 MiB. The FP8 key and value cache grows by 6144 bytes per token, reaching those sizes at 65536 and 32768 tokens respectively. These are payload counts, not measured allocator use. Cache payload · MiB 0256 512768 032,768 65,536131,072 tokens FP32 recurrent state · 384 MiB FP16 recurrent state · 192 MiB FP8 attention cache
Memory for one sequence. Recurrent state has a fixed number of entries, while the attention cache adds keys and values for every token, and the circles mark where the two payloads are equal. These counts leave out the serving system's other allocations.

The KV payload stays below the recurrent payload until 65,536 tokens, where the two meet (released_fp32_fp8_crossover checks the exact boundary). If you store the SSM state in FP16 instead, that boundary halves to 32,768 tokens. These counts cover the payload for one main-model sequence. Convolution history, scale metadata, allocator padding, MTP, and retained snapshots add to the serving system’s memory use.

Batch size matters here as much as sequence length: sixty-four active requests with separate FP32 states already require \(64\times384\,\mathrm{MiB}=24\,\mathrm{GiB}\) for this payload alone. Reducing the state to FP16 halves that arithmetic count, but it also changes what happens every time an updated value is saved, which is why the rounding policy belongs in the calculation below.

Dimensions.lean

These formulas count tensor entries from the block schedule and dimensions, then multiply by bytes per scalar. The same module checks the Mamba projection partition. It also checks that using latent width 2048 rather than 8192 divides the routed-expert matrix parameter count by four (the router, shared expert, and additional projections are outside that ratio).

/-- Block counts: 48 Mamba, 12 attention, and 48 MoE. -/
theorem releasedSchedule_counts :
    releasedSchedule.count .mamba = 48 ∧
    releasedSchedule.count .attention = 12 ∧
    releasedSchedule.count .moe = 48 := by decide +kernel
Full source
/-- FP8 KV payload stays at or below the FP32 recurrent payload up to 64 Ki tokens, where the
two are equal. -/
theorem released_fp32_fp8_crossover (tokens : Nat) :
    kvBytes releasedSchedule tokens 2 128 1 ≤ ssmBytes releasedSchedule 256 64 128 4 ↔
      tokens ≤ 65536 := by
  rw [(released_cache_payloads tokens).1, (released_cache_payloads tokens).2]
  omega
Full source

Recovering the state by replay

Before replaying several tokens, let's run one prepared SSM update in Lean. We retain [10, 0], write [2, 0], and read the first coordinate. The output is 12. If you hover over the tensors and step, you can see how their dimensions appear in the types.

import Nemotron.SSM
import TorchLean.Tensor.Literal

open TorchLean

-- A rank-one write updates a two-coordinate state, then reads its first coordinate.
def ssmMemory : Nemotron.SSM.State Float32 1 2 := [[10, 0]]
def ssmToken : Nemotron.SSM.Input Float32 1 2 :=
  { retention := 1
    value := [2]
    write := [1, 0]
    read := [1, 0] }

#eval (Nemotron.SSM.step ssmMemory ssmToken).2.getScalar ⟨0, by decide⟩
#check Nemotron.SSM.step
Lean output
12.000000

Nemotron.SSM.step {α : Type} [Storage α] [Add α] [Mul α] [Zero α] {valueDim stateDim : ℕ}
  (state : Nemotron.SSM.State α valueDim stateDim) (input : Nemotron.SSM.Input α valueDim stateDim) :
  Nemotron.SSM.State α valueDim stateDim × Tensor α [valueDim]

So how do we get the current state without writing it after every token? We save it at an earlier point and keep the inputs needed for the updates since then, and to recover the current state we start from that checkpoint and run those updates again in order. Here \(s\) is the saved state and \(u_1,\ldots,u_k\) are the prepared inputs (the values and coefficients consumed by the recurrent update, after the earlier processing of each token). They aren't raw token IDs. Replay a token ID through a changed projection or convolution and you won't necessarily get back the prepared values used the first time.

In §4.5, the authors describe how they catch up from the older state:

we cache the input activations and apply activation replay to forward the state on-the-fly.

Let's make that replay step precise. We have to retain the values the update consumed, not resample them or regenerate them from a different state, and once those values are fixed I can prove the replay identity for a general transition before looking at rounding. (I'll use “scan” for applying that transition in order, carrying each updated state into the next step.)

Stored checkpoint sPending inputs u₁ … uₖ Same causal scan Current state + outputs
current = scan(step, checkpoint, pending).state
push(u): pending ← pending ++ [u]
flush(Q): checkpoint ← Q(current); pending ← []

Replaying the old buffer and one new input gives the same result as recovering the current state and then taking one more step. That's observe_push in Lean, and run_from_replay extends the identity to a whole suffix, including every emitted output. Both reuse the causal scan from the Kimi K3 example, so I didn't write a second one.

Replay.lean

This replay identity holds for any deterministic transition and input list, as long as the replay uses the same prepared inputs and arithmetic. Saving the state exactly preserves it (observe_flush_id_state), while a lossy write replaces it with the quantizer’s result (observe_flush_state), and a flush also clears the buffer’s earlier output history.

If a step uses randomness, replay has to keep its random choices too, and once those choices are fixed, the same deterministic identity applies. If you draw again on each replay, the question becomes one about distributions, which needs a separate theorem that I haven't written.

Here's a small example you can check in your head: let the transition be \(s'=s+u\), the stored checkpoint be 10, and the pending inputs be 2 and −3. Observing the buffer gives state 9. If we append input 4 and replay from 10 we get 13, exactly as if we'd started from the observed state 9 and applied that one new update. But the identity depends on the order and contents of the buffer, so it doesn't let us discard the −3 or replay a newly sampled substitute for it.

/-- Scanning the pending inputs and a suffix from the checkpoint equals replaying, then
continuing from the reconstructed state. Every output agrees, not just the final state. -/
theorem run_from_replay (step : State → Input → State × Output)
    (cache : Replay State Input) (suffix : List Input) :
    CausalScan.run step cache.checkpoint (cache.pending ++ suffix) =
      let prior := cache.observe step
      let next := CausalScan.run step prior.1 suffix
      (next.1, prior.2 ++ next.2) :=
  CausalScan.run_append step cache.checkpoint cache.pending suffix
Full source

An error budget for checkpoint writes

A rounded checkpoint can differ from the reference state in every entry. How do we keep track of that difference? Suppose one update bounds each coordinate error by \(L\) times the previous allowance (with the prepared input held fixed), and each storage write adds at most \(\delta\) to that allowance. Then running \(n\) updates before writing multiplies it by \(L^n\) and adds one \(\delta\).

Writing \(E_j\) for the budget after the \(j\)th checkpoint gives the recurrence:

Eⱼ₊₁ = L^(nⱼ₊₁) Eⱼ + δ

Here \(E_0\) is the error in the initial state and \(n_{j+1}\) is the number of tokens in the next chunk. If each update shrinks or preserves a difference between states, then \(0\le L\le1\), and after \(m\) writes we get:

Eₘ ≤ E₀ + mδ, for 0 ≤ L ≤ 1.

So for \(E_0\ge0\), \(\delta\ge0\), and \(0\le L\le1\), you pay at most one \(\delta\) per write. If updates can amplify a difference, the weighted recurrence still applies, but this linear bound can fail. And even under the linear bound, moving the writes changes where their errors enter the computation.

The factor \(L^n\) can make the weighted budget (a worst-case calculation, not a measurement of an actual rounding error) much smaller than the count-only bound. With no initial error, \(L=1/2\), a write allowance \(\delta=0.1\), and two chunks of two tokens, the first budget is 0.1 and the second is \(\frac14\times0.1+0.1=0.125\), because the older allowance has shrunk through two updates before the new write contributes its own.

Error.lean

quantizedChunks_within_of_writes works with arbitrary tensor shapes, sequence lengths, and chunk partitions, and checkpointBudget_le_count bounds its budget by the number of writes under the nonnegativity and retention assumptions above.

The WritesWithin premise asks for an error allowance at the states the rounded execution actually writes, because floating-grid spacing grows with magnitude and no single absolute cap can cover every unbounded real input. Fixed-grid quantizers can use the stronger uniform premise in quantizedChunks_within.

Both executions receive the same prepared inputs, so if a perturbed state changes the next sampled token, we'd need to control that change before using this comparison.

The checkpoint error theorem
/-- Storage bounds at the written states give an error bound for any checkpoint partition.
Sensitivity is paid per token and `δ` once per checkpoint. -/
theorem quantizedChunks_within_of_writes {shape : Shape} {Input Output : Type}
    (step : Tensor ℝ shape → Input → Tensor ℝ shape × Output)
    (quantize : Tensor ℝ shape → Tensor ℝ shape) (L δ : ℝ)
    (hstep : ∀ input e x y, Within e x y → Within (L * e) (step x input).1 (step y input).1)
    (chunks : List (List Input)) (x y : Tensor ℝ shape) (e : ℝ) (hxy : Within e x y)
    (hwrites : WritesWithin step quantize δ x chunks) :
    Within (checkpointBudget L δ e chunks)
      (quantizedChunks step quantize x chunks) (CausalScan.run step y chunks.flatten).1 
Read the proof
by
  induction chunks generalizing x y e with
  | nil => simpa [quantizedChunks, checkpointBudget, CausalScan.run] using hxy
  | cons chunk rest ih =>
      simp only [WritesWithin] at hwrites
      -- First propagate the old error through the chunk, then pay for its one storage write.
      have hscan := scan_state_within step L hstep chunk x y e hxy
      have hwrite := within_triangle hwrites.1 hscan
      have hwrite' : Within (L ^ chunk.length * e + δ)
          (quantize (CausalScan.run step x chunk).1) (CausalScan.run step y chunk).1 := by
        simpa [add_comm] using hwrite
      -- Both executions resume from their own resulting state with the same remaining inputs.
      have hrest := ih (quantize (CausalScan.run step x chunk).1)
        (CausalScan.run step y chunk).1 (L ^ chunk.length * e + δ) hwrite' hwrites.2
      simpa only [quantizedChunks, checkpointBudget, List.flatten_cons,
        CausalScan.run_append] using hrest
/-- With `0 ≤ L ≤ 1` the budget grows at most linearly in the number of writes. This is a
worst-case bound and does not compare the actual errors of two schedules. -/
theorem checkpointBudget_le_count {Input : Type} (L δ e : ℝ)
    (hL : 0 ≤ L) (hLone : L ≤ 1) (hδ : 0 ≤ δ) (he : 0 ≤ e)
    (chunks : List (List Input)) :
    checkpointBudget L δ e chunks ≤ e + chunks.length * δ 
Read the proof
by
  induction chunks generalizing e with
  | nil => simp [checkpointBudget]
  | cons chunk rest ih =>
      have hpower : 0 ≤ L ^ chunk.length := pow_nonneg hL _
      have hpowerOne : L ^ chunk.length ≤ 1 := pow_le_one₀ hL hLone
      have hnext : 0 ≤ L ^ chunk.length * e + δ :=
        add_nonneg (mul_nonneg hpower he) hδ
      have hbound := ih (L ^ chunk.length * e + δ) hnext
      simp only [checkpointBudget, List.length_cons, Nat.cast_add, Nat.cast_one]
      nlinarith [mul_le_mul_of_nonneg_right hpowerOne he]
Full source

Fewer writes can leave a larger error

Table 16 reports emulated checkpointing experiments on Nemotron 3 Super, while the released Ultra cache uses FP16 with stochastic rounding (described on page 46). For my example, I use an integer grid so you can follow every rounding decision and isolate the effect of the storage schedule (I'd need the report’s model and FP16 encoder to reproduce its measurements).

I'd read the table one rounding policy at a time. With FP16 round-to-nearest, its reported mean accuracy drop changes from 1.07% without checkpointing to 0.03% with period eight, but with FP16 stochastic rounding the corresponding values are −0.26% and 0.19%. So checkpointing helps several rows, though the table doesn't show it improving every policy. Our example asks the related mathematical question: does reducing the number of writes force a smaller terminal error for every input sequence?

No, and the example below shows why. It uses \(s'=as+u\) with nearest-even rounding to the integer grid, so every write has absolute error at most ½. If you select the cancellation example, you'll see why fewer writes need not decrease the actual terminal error, even when \(a=1\).

Reference Write each token Checkpoint + replay
State trajectories under reference and quantized checkpoint schedules

ScheduleWritesFinal state Actual errorWeighted budget
Dots on the blue curve mark storage writes. Between writes the pending inputs are replayed, and the final partial chunk gets written too. Your browser draws this with JavaScript arithmetic, while the two named rational counterexamples are proved in Lean with FloatLib's executable rounder.

My favourite example here is the cancellation sequence −0.9, −0.9, −0.5, −0.1, with exact sum −2.4. Writing each token finishes at −2 (error 0.4), while writing every two tokens finishes at −3 (error 0.6). Half the writes, and a bigger error! Both runs satisfy their error budgets. It's the signs of the rounding errors that explain the difference: some cancel, and changing the schedule changes that cancellation, so fewer writes need not reduce the actual final error. The report’s measurements are compatible with this example.

Rounding.lean

These are exact rational calculations using FloatLib’s nearest-even integer quantizer. fewer_writes_can_increase_error checks the strict error inequality above, and repeated_ties_lose_updates checks the other example, where two half-unit additions rounded separately leave zero but rounding their sum once gives one.

/-- Four nearest-even writes can end closer to the exact sum than two, through cancellation.
So "fewer sequential quantization steps" does not always mean less error. This is a fixed-grid
example, not a counterexample to the report's measured results. -/
theorem fewer_writes_can_increase_error :
    |quantizedChunks addStep quantize 0
        [[-9 / 10], [-9 / 10], [-1 / 2], [-1 / 10]] - (-12 / 5)| <
      |quantizedChunks addStep quantize 0
        [[-9 / 10, -9 / 10], [-1 / 2, -1 / 10]] - (-12 / 5)| := by
  decide +kernel
Full source

The Mamba state update

Inside one recurrent head, the state is a matrix with one row per value channel and one column per state coordinate (the tensor type records this as [valueDim, stateDim]). For each token, the prepared input tells the head how much old state to retain (\(a\)), what values to write (\(x\) and \(B\)), and how to read an output (\(C\)).

S′ = aS + xBᵀ; y = S′C.

So the scalar \(a\) determines how much of the old state we retain, the outer product \(xB^{\mathsf T}\) writes new information into the state, and multiplying by \(C\) reads an output vector.

So what sensitivity factor does a Mamba update have? Start with two different states, \(S\) and \(T\), and apply the same prepared input to both. When we subtract, their new input writes cancel:

update(S,u) − update(T,u) = a(S − T).

Each coordinate difference is multiplied by \(a\), so \(|a|\le L\) gives the sensitivity condition used in the error budget. BoundedInput pairs a prepared input with evidence of that inequality, and the dimensions stay parameters throughout.

SSM.lean

update_sub_apply checks the cancellation, update_within bounds the remaining difference, and checkpoint_error uses those results in the checkpoint theorem. The public SSM.Sequence.run takes packed input tensors and returns a final state and one output row per token, and run_unstack identifies each row with its scan output.

The model source gives us a reason for the retention bound. Its rate is \(A=-\exp(\mathrm{logA})\) and a mathematical softplus gives a positive timestep \(\Delta\), so \(a=\exp(\Delta A)\) lies between zero and one. I like this part: because the parameterization gives this bound for every real log-rate, we can check it without looking at a single learned value.

Mamba2.lean

prepareHead shares each B/C group across its contiguous heads and scales B by Δ before passing it to the SSM core. prepareHead_bounded checks the retention bound and updateHeads_within lifts it to the tensor of all heads. As in the model source, the step adds the D skip and reads the updated state before casting it for cache storage.

I use the pinned model implementation for these equations because the report’s cache section doesn't give the complete selective SSM update. My adapter begins after projection and convolution, so connecting it to the full decoder still needs proofs that I haven't written yet for gating, grouped normalization, and output projection, among other operations. Its mathematical softplus also needs a refinement argument for PyTorch’s finite-precision threshold branch.

From state error to output error

Does a small state error give a small output error? Not necessarily, if the read coefficients are large. Say each state coordinate differs by at most \(e\) and both runs use the same read vector \(C\). Then every output channel satisfies:

|yᵢ − ŷᵢ| ≤ e ∑ⱼ |Cⱼ|.

You can't drop the absolute values. Suppose two read coefficients are 10 and −10. Their sum is zero, but coordinate errors of +0.01 and −0.01 produce an output difference of \(10\times0.01+(-10)\times(-0.01)=0.2\), because the two products have the same sign and their errors add. With absolute values the bound is \(0.01\times(|10|+|-10|)=0.2\), which covers that case.

SSM.read_within follows from the tensor library's matrix-vector coordinate theorem and mathlib’s absolute-sum inequality, and step_output_within also accounts for retention in the next update. Both hold at arbitrary dimensions, even with an empty state axis. To turn this formula into a small numerical bound, we'd need a bound on the sum of absolute read coefficients. I haven't established one for learned weights. A logit bound would also need to follow the error through gating, normalization, skip connections, and later blocks.

Retention and the grouped state update
/-- For a nonnegative time step the decay lies in `(0, 1]`, whatever the learned log-rate, so
discretization never expands the prior state. -/
theorem retention_bounds (delta logA : ℝ) (hdelta : 0 ≤ delta) :
    0 < retention delta logA ∧ retention delta logA ≤ 1 := by
  constructor
  · exact Real.exp_pos _
  · apply Real.exp_le_one_iff.mpr
    exact neg_nonpos.mpr (mul_nonneg hdelta (Real.exp_nonneg _))
/-- Coordinatewise, the update is the source's scalar Mamba-2 equation
`state * dA + x * (B * dt)`. -/
theorem updateHead_apply {groups headsPerGroup headDim stateDim : Nat}
    (hHeadsPerGroup : 0 < headsPerGroup)
    (parameters : Parameters (groups * headsPerGroup))
    (input : Token groups headsPerGroup headDim stateDim)
    (head : Fin (groups * headsPerGroup)) (state : SSM.State ℝ headDim stateDim)
    (valueIndex : Fin headDim) (stateIndex : Fin stateDim) :
    SSM.update state (prepareHead hHeadsPerGroup parameters input head)
        (valueIndex, stateIndex, PUnit.unit) =
      let delta := timeStep parameters.timeStepMin (input.rawDt.getScalar head)
        (parameters.dtBias.getScalar head)
      state (valueIndex, stateIndex, PUnit.unit) * retention delta (parameters.logA.getScalar head) +
        (Tensor.unstack input.value head).getScalar valueIndex *
          ((Tensor.unstack input.B (groupIndex hHeadsPerGroup head)).getScalar stateIndex * delta) := by
  simp [SSM.update, prepareHead, Tensor.scale, Tensor.matrix, Tensor.getScalar_eq_apply]
/-- One update over all heads does not increase a coordinate error in the prior state, since
every prepared retention is at most `1`. Both sides use the same token and parameters. -/
theorem updateHeads_within {groups headsPerGroup headDim stateDim : Nat}
    (hHeadsPerGroup : 0 < headsPerGroup)
    (parameters : Parameters (groups * headsPerGroup))
    (input : Token groups headsPerGroup headDim stateDim)
    (x y : Tensor ℝ [groups * headsPerGroup, headDim, stateDim])
    (e : ℝ) (hxy : Cache.Within e x y) :
    Cache.Within e (updateHeads hHeadsPerGroup parameters input x)
      (updateHeads hHeadsPerGroup parameters input y) 
Read the proof
by
  intro coordinate
  have hhead : Cache.Within e (Tensor.unstack x coordinate.1)
      (Tensor.unstack y coordinate.1) := by
    intro inner
    simpa [Tensor.unstack] using hxy (coordinate.1, inner)
  have hnext := SSM.update_within (Tensor.unstack x coordinate.1)
    (Tensor.unstack y coordinate.1)
    (prepareHead hHeadsPerGroup parameters input coordinate.1) 1 e (by norm_num)
    (prepareHead_bounded hHeadsPerGroup parameters input coordinate.1) hhead
  simpa [updateHeads, Tensor.dim, Tensor.dim] using hnext coordinate.2
Full source
State sensitivity and readout bounds
/-- Applying the same prepared input to two states cancels the rank-one write. -/
theorem update_sub_apply {valueDim stateDim : Nat}
    (x y : State ℝ valueDim stateDim) (input : Input ℝ valueDim stateDim)
    (coordinate : Shape.Coord [valueDim, stateDim]) :
    update x input coordinate - update y input coordinate =
      input.retention * (x coordinate - y coordinate) := by
  simp [update, Tensor.scale]
  ring
/-- A fixed read vector turns a coordinatewise state error into an output error, scaled by the
read vector's absolute sum. So a stable state alone does not give a small readout error. -/
theorem read_within {valueDim stateDim : Nat}
    (x y : State ℝ valueDim stateDim) (read : Tensor ℝ [stateDim])
    (e : ℝ) (hxy : Cache.Within e x y) :
    Cache.Within (e * ∑ j : Fin stateDim, |read.getScalar j|)
      (Tensor.matvec x read) (Tensor.matvec y read) 
Read the proof
by
  rintro ⟨i, rest⟩
  cases rest
  change |(Tensor.matvec x read).getScalar i -
    (Tensor.matvec y read).getScalar i| ≤ _
  rw [Tensor.matvec, Tensor.matvec, Tensor.getScalar_contract_matVec_eq_sum,
    Tensor.getScalar_contract_matVec_eq_sum, ← Finset.sum_sub_distrib,
    Finset.mul_sum]
  calc
    |∑ j : Fin stateDim, (Tensor.get2 x i j * read.getScalar j - Tensor.get2 y i j * read.getScalar j)|
        ≤ ∑ j : Fin stateDim,
            |Tensor.get2 x i j * read.getScalar j - Tensor.get2 y i j * read.getScalar j| :=
      Finset.abs_sum_le_sum_abs _ _
    _ ≤ ∑ j : Fin stateDim, e * |read.getScalar j| := by
      apply Finset.sum_le_sum
      intro j _
      rw [← sub_mul, abs_mul]
      apply mul_le_mul_of_nonneg_right _ (abs_nonneg _)
      simpa only [Tensor.get2_eq_apply] using
        hxy ⟨i, j, ()⟩
Full source

Rounding theory and stored bits

For nearest-even rounding, FloatLib bounds the error by half a unit in the last place (ULP), and Cache.roundTensor_within applies that theorem to each tensor entry, so if we bound all those half-ULPs by \(\delta\), we get the storage allowance needed above. Near zero, the theorem uses an absolute error bound that includes gradual underflow.

FloatLib’s real-valued grid has no upper exponent limit, so to connect it to stored bits, its refinement theorems require finiteness premises (an overflowing result has no real value). And since the released cache uses stochastic rounding, I also examine the local random rounding choice and the assumptions needed to preserve its mean.

/-- If every coordinate's half-ULP is at most `δ`, rounding is `Within δ`. An absolute
bound covers subnormals and needs no relative error bound near zero. -/
theorem roundTensor_within {shape : Shape} (fmt : FloatFormat)
    (x : Tensor ℝ shape) (δ : ℝ)
    (hδ : ∀ coordinate, Model.ulpAt fmt (x coordinate) / 2 ≤ δ) :
    Within δ (roundTensor fmt x) x := by
  intro coordinate
  simpa only [roundTensor, Tensor.map_apply] using
    (Model.abs_roundAt_sub_le fmt (x coordinate)).trans (hδ coordinate)
Full source

Stochastic rounding and the mean state

Say you have a value 3.25 between grid points 3 and 4. Nearest rounding always chooses 3. Stochastic rounding chooses 4 one quarter of the time and 3 the rest of the time, so the mean is 3.25 even though each individual write changes the value. Since the state gets written again and again, we care about both the average and the error along an individual run.

FloatLib's roundQuot chooses the upper integer when the entropy residue is smaller than the discarded remainder. roundQuot_sum counts the choices made by this executable rounder, and averaging them over uniform residues recovers the original quotient.

P(upper) = remainder / denominator
Mean rounded value = original value
Absolute error of each write ≤ grid spacing
Stochastic.lean

roundTensor_mean lifts this mean law to tensor coordinates, each with its own sign and grid cell. It only asks that every coordinate sees uniform residues, so one shared entropy word and independent words both work. Stochastic.roundTensor_within bounds every outcome’s error by one grid spacing, and with shared entropy those errors can be correlated even though each coordinate has the right mean.

The entropy residues must be uniform, which isn't automatic: reducing a uniform fixed-width word modulo an arbitrary denominator can bias them. Our adapter describes a local signed grid cell for each coordinate, with an explicit quantum and denominator, so connecting it to the released FP16 encoder still means checking saturation, overflow, flush-to-zero, and entropy generation.

For example, a uniform three-bit word has eight possible values. Reducing it modulo three gives residue zero for 0, 3, and 6, so that residue occurs with probability 3/8, not 1/3, which would bias a rounding choice intended to occur one third of the time. This denominator of three is an illustration (I'm not claiming NVIDIA's binary-format encoder uses one), but it shows why the general theorem needs its uniform-residue premise.

Since the prepared SSM update multiplies the old state and adds a fixed write, updating a nonempty ensemble of states and then averaging gives the update of their mean. update_mean checks this identity, and scan_mean carries it through a sequence when the actual ensemble’s storage perturbations have mean zero at every step.

That mean-zero condition must hold at the states reached during execution. Conditionally unbiased rounding can establish it, but checking the encoder’s mean at one isolated input isn't enough. And the inputs stay fixed throughout this argument. Nonlinear decoder layers and changes in sampled tokens need their own analysis.

For the example 3.25, an unbiased write can leave an error of −0.25 or +0.75, and averaging those errors with probabilities three quarters and one quarter gives zero. But neither individual write is exact. To describe one run we still need its error bound, and to describe the spread across runs we need a variance bound. A zero mean error gives us neither, and it doesn't make the stored states identical either.

The stochastic-rounding theorems
/-- A finite family of entropy words with uniform residues modulo `den`: every residue below
`den` is hit by `samples / den` words. -/
def UniformResidues {samples : Nat} (den : Nat) (entropy : Fin samples → Nat) : Prop :=
  ∀ r < den, den * (Finset.univ.filter fun i => entropy i % den = r).card = samples
/-- Each coordinate is unbiased when its own entropy residues are uniform. Nothing is assumed
about how the words of different coordinates are related. One word shared by every coordinate
and independent words both satisfy the premise (`roundTensor_mean_shared`,
`roundTensor_mean_independent`), though shared words give correlated coordinate errors. -/
theorem roundTensor_mean {samples : Nat} {shape : Shape} (quantum : Tensor ℝ shape)
    (sign : Tensor Bool shape) (den numerators : Tensor Nat shape)
    (entropy : Fin samples → Tensor Nat shape) (hsamples : 0 < samples)
    (hden : ∀ coordinate, 0 < den coordinate)
    (huniform : ∀ coordinate,
      UniformResidues (den coordinate) fun i => entropy i coordinate) :
    mean (Tensor.dim fun i => roundTensor quantum sign den numerators (entropy i)) =
      unrounded quantum sign den numerators 
Read the proof
by
  apply TorchLean.Tensor.Rep.ext
  intro coordinate
  simpa [mean_apply, roundTensor, unrounded] using
    round_ensemble_mean (quantum coordinate) (sign coordinate) (numerators coordinate)
      (den coordinate) (hden coordinate) hsamples (fun i => entropy i coordinate)
      (huniform coordinate)
/-- If every coordinate's grid spacing is at most `δ`, a stochastic tensor write is `Within δ`
of the unrounded tensor, however the entropy words are correlated. -/
theorem roundTensor_within {shape : Shape} (quantum : Tensor ℝ shape)
    (sign : Tensor Bool shape) (den numerators entropy : Tensor Nat shape) (δ : ℝ)
    (hden : ∀ coordinate, 0 < den coordinate)
    (hδ : ∀ coordinate, |quantum coordinate| ≤ δ) :
    Within δ (roundTensor quantum sign den numerators entropy)
      (unrounded quantum sign den numerators) := by
  intro coordinate
  simpa [roundTensor, unrounded] using
    (round_error (quantum coordinate) (sign coordinate) (entropy coordinate)
      (numerators coordinate) (den coordinate) (hden coordinate)).trans (hδ coordinate)
/-- A fixed prepared SSM update is affine, so it commutes with the mean of a nonempty ensemble.
`scan_mean` uses this to compose conditionally unbiased state writes. Input-dependent token
selection, normalization, and nonlinear decoder layers fall outside the identity. -/
theorem update_mean {samples valueDim stateDim : Nat}
    (states : Tensor ℝ [samples, valueDim, stateDim])
    (input : SSM.Input ℝ valueDim stateDim) (hsamples : 0 < samples) :
    SSM.update (mean states) input =
      mean (Tensor.dim fun i => SSM.update (Tensor.unstack states i) input) 
Read the proof
by
  apply TorchLean.Tensor.Rep.ext
  intro coordinate
  have hn : (samples : ℝ) ≠ 0 := by exact_mod_cast Nat.ne_of_gt hsamples
  simp only [SSM.update, Tensor.add_apply, Tensor.scale, Tensor.map_apply,
    mean_apply, Tensor.unstack_dim]
  rw [Finset.sum_add_distrib, ← Finset.sum_mul]
  simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul]
  field_simp
/-- If each step updates every sample and then adds storage errors of mean zero, the ensemble
mean follows the exact scan from the initial mean. Conditionally unbiased writes can supply
`herrors` on finite histories. Neither independence nor zero error on a single history is
assumed. -/
theorem scan_mean {samples valueDim stateDim : Nat}
    (inputs : List (Input ℝ valueDim stateDim))
    (states errors : Nat → Tensor ℝ [samples, valueDim, stateDim]) (hsamples : 0 < samples)
    (hstep : ∀ i : Fin inputs.length, states (i.val + 1) =
      (Tensor.dim fun sample =>
        update (Tensor.unstack (states i.val) sample) inputs[i.val]) + errors i.val)
    (herrors : ∀ i : Fin inputs.length,
      mean (errors i.val) = Tensor.full [valueDim, stateDim] 0) :
    mean (states inputs.length) = (CausalScan.run step (mean (states 0)) inputs).1 
Read the proof
by
  apply scan_mean_of_step inputs states
  intro i
  rw [hstep i, Cache.Stochastic.mean_add, herrors i]
  rw [← update_mean (states i.val) inputs[i.val] hsamples]
  apply TorchLean.Tensor.Rep.ext
  intro coordinate
  simp
Full source

Why the mean doesn't survive every nonlinear map

Let's carry the 3.25 example one step further and suppose a later calculation squares the stored value. Three quarters of the writes return three and one quarter return four, so the average stored value is 3.25, but the average square is

The mean of a square need not equal the square of the mean.

The difference is 3/16, the variance of this rounded value. I made this square up (it isn't one of Nemotron's decoder operations), but it shows that the mean-zero write error hasn't disappeared: a nonlinear calculation can turn its spread into a change in the mean output.

For the prepared SSM transition, fixed input coefficients make the update affine in the state, so we can carry the mean through it. We can't reuse that argument unchanged for nonlinear gates, normalization, or token selection, where we'd need to bound what the next operation does to the rounding error, much as squaring did in this example.

Losing small gradient contributions in BF16

The report's first training-divergence account describes a divergence after changing the output layer's local gradient accumulation from FP32 to BF16. Each multi-token prediction head's loss had a weight of 0.05, the small contributions to the shared output layer were lost, and returning to the FP32 recipe re-stabilized training. So let's look at how a representable contribution can disappear during accumulation.

Multi-token prediction asks additional heads to predict farther-ahead targets during training, and their losses contribute gradients to shared parameters, including the output layer. Multiplying each head's loss by 0.05 reduces its gradient contribution before accumulation, so the accumulator has to preserve small additions beside larger values. Choosing a precision only from the size of each contribution isn't enough.

Take a running sum of 256 and add 1. The next BF16 value above 256 is 258, so 257 falls halfway between them, and nearest-even rounding returns 256. So in BF16, 256 + 1 = 256, and the 1 is just gone! Binary32 represents 257 exactly, and I checked both equalities in Lean with FloatLib’s finite-format arithmetic.

BF16: 256 + 1 → 256
binary32: 256 + 1 → 257

The contribution 1 is itself representable in BF16, so the loss happens when it's added to the larger running sum (these numbers illustrate that mechanism and aren't gradients recorded from NVIDIA’s run). There's also a second training divergence in the report, but its cause remained undetermined, and I don't have an explanation for it either.

Accumulation.lean

For whole gradient tensors, accumulate_within reuses FloatLib’s reduction-tree error theorem: we specify the addition order and bound the rounding error at each addition, and the theorem then bounds the difference from the exact sum of the interpreted input tensors. A uniform allowance \(\delta\) gives \(\mathrm{nodeCount}\,\delta\).

The theorem accepts arbitrary tensor shapes and scalar carriers. Applying it to a backend requires evidence of that backend’s addition order, and errors already present in the input gradients must be accounted for separately.

The accumulation theorem and BF16 witness
/-- Accumulation error is at most FloatLib's sum of per-addition allowances, for any tensor shape
and scalar type. Errors in producing the leaves are not counted, since the reference adds the
interpreted leaves in exact real arithmetic.
-/
theorem accumulate_within {α : Type} [Storage α] {shape : Shape}
    (combine : α → α → α) (interpret : α → ℝ)
    (schedule : ReductionTree (Tensor α shape))
    (allowance : Tensor α shape → Tensor α shape → ℝ)
    (h : schedule.AllNodes (Tensor.zipWith combine) id (fun x y =>
      Cache.Within (allowance x y) (Tensor.map interpret (Tensor.zipWith combine x y))
        (Tensor.map interpret x + Tensor.map interpret y))) :
    Cache.Within (schedule.errorBudget (Tensor.zipWith combine) id allowance)
      (Tensor.map interpret (accumulate combine schedule))
      (accumulate (· + ·) (schedule.map (Tensor.map interpret))) 
Read the proof
by
  intro coordinate
  have hError := schedule.abs_eval_sub_exact_le_errorBudget (Tensor.zipWith combine) id
    (fun x => interpret (x coordinate)) allowance
    (by
      induction schedule with
      | leaf x => trivial
      | node left right hl hr =>
          -- Project each node's tensor bound to this coordinate.
          exact ⟨hl h.1, hr h.2.1, by
            simpa [Tensor.map_apply, Tensor.add_apply] using h.2.2 coordinate⟩)
  change |interpret (accumulate combine schedule coordinate) -
    schedule.eval (· + ·) (fun x => interpret (x coordinate))| ≤ _ at hError
  rw [accumulate_apply] at hError
  simpa [accumulate_apply, ReductionTree.eval_map, Function.comp_def, Tensor.map_apply] using hError
/-- In BF16, `256 + 1` is a tie and rounds back to the even neighbor `256`. These numbers
illustrate the mechanism and are not recorded gradients from NVIDIA's run. -/
theorem bf16_add_one_eq_self :
    Model.add (Model.roundRat .bfloat16 false 256 1) (Model.roundRat .bfloat16 false 1 1) =
      Model.roundRat .bfloat16 false 256 1 := by
  decide +kernel
/-- In binary32 the same addition is exact. -/
theorem binary32_add_one_eq_sum :
    Model.add (Model.roundRat .binary32 false 256 1) (Model.roundRat .binary32 false 1 1) =
      Model.roundRat .binary32 false 257 1 := by
  decide +kernel
Full source

Rolling back rejected draft tokens

Suppose a draft proposes three tokens but the main model accepts only the first. Then the next computation has to start from the state after that first token, because a state incorporating the two rejected tokens would describe the wrong prefix.

So how do you get back to that state? Attention can discard the keys and values belonging to a rejected suffix, but a Mamba update overwrites the fixed-size recurrent state, so discarding token records alone can't restore it. Instead, NVIDIA retains a snapshot at every draft step. I include the initial state in the snapshot sequence too, so rejecting the entire draft selects that state.

Initial stateSnapshot after draft 1 Snapshot after draft 2 Snapshot after draft 3
Speculation.lean

restore_eq_prefix identifies the selected snapshot with the state obtained by running the accepted prefix. In run_after_restore, continuing from that snapshot gives the same final state and committed outputs as running the accepted prefix followed by the continuation.

SSM.Sequence.snapshots exposes the states in a [tokens + 1, valueDim, stateDim] tensor. Row zero is the initial state, and snapshots_unstack identifies each bounded row with its corresponding prefix.

These rollback laws use the same causal scan and apply to any deterministic transition, while a random transition must retain its choices in the state or prepared inputs for exact replay. As for the speculative acceptance sampler, its probability law is a separate obligation, and I haven't proved it here.

The rollback theorems
/-- Restoring gives the state after running the accepted prefix. -/
theorem restore_eq_prefix (step : State → Input → State × Output)
    (initial : State) (draft : List Input) (accepted : Fin (draft.length + 1)) :
    restore step initial draft accepted =
      (CausalScan.run step initial (draft.take accepted.val)).1 
Read the proof
by
  induction draft generalizing initial with
  | nil =>
      simp [restore, snapshots, CausalScan.run]
  | cons input rest ih =>
      cases accepted using Fin.cases with
      | zero => simp [restore, snapshots, CausalScan.run]
      | succ accepted =>
          simpa [restore, snapshots, CausalScan.run] using ih (step initial input).1 accepted
/-- Continuing from the restored snapshot gives the same final state and committed outputs as
scanning the accepted prefix and the continuation. Rejected draft inputs leave no trace. -/
theorem run_after_restore (step : State → Input → State × Output)
    (initial : State) (draft : List Input) (accepted : Fin (draft.length + 1))
    (continuation : List Input) :
    CausalScan.run step initial (draft.take accepted.val ++ continuation) =
      let prior := CausalScan.run step initial (draft.take accepted.val)
      let next := CausalScan.run step (restore step initial draft accepted) continuation
      (next.1, prior.2 ++ next.2) := by
  rw [restore_eq_prefix]
  exact CausalScan.run_append step initial (draft.take accepted.val) continuation
/-- Row `accepted` is the state after that many tokens. -/
theorem snapshots_unstack {α : Type} [Storage α] [Add α] [Mul α] [Zero α]
    {tokens valueDim stateDim : Nat} (inputs : Sequence α tokens valueDim stateDim)
    (initial : State α valueDim stateDim) (accepted : Fin (tokens + 1)) :
    Tensor.unstack (inputs.snapshots initial) accepted =
      (CausalScan.run step initial (inputs.toList.take accepted.val)).1 := by
  simp only [snapshots, Tensor.unstack_dim, Cache.Speculation.restore_eq_prefix]
Full source

Conclusion

I'd love to extend this to the token scores of the released model. That means following the error from the actual storage writes through replay and the rest of the decoder, then comparing it with the gap between the winning token and its competitors. And I think the cancellation example is a good reason to measure the actual error as well as carry a worst-case bound, since reducing that bound doesn't guarantee a smaller error on every input.

The replay proof takes the transition and checkpoint schedule as parameters, so if you're trying a different recurrent model or storage format, we can reuse that argument and work on the numerical assumptions specific to your update. I'd be happy to compare examples, so send me yours :)

References

Cite this article

Robert Joseph George. Nemotron 3 Ultra: replaying a rounded state. TorchLean Verified Examples, 2026.

@misc{george2026nemotron,
  author = {Robert Joseph George},
  title = {{Nemotron 3 Ultra: replaying a rounded state}},
  year = {2026},
  howpublished = {TorchLean Verified Examples},
  url = {https://robertboy18.github.io/TorchLean-Verified-Examples/week-05-nemotron-specification/site/}
}
Download BibTeX