Skip to content

Add recompute_checkpoint/2 to compute a result again at every use - #1913

Draft
blasphemetheus wants to merge 15 commits into
elixir-nx:mainfrom
blasphemetheus:feat/recompute-checkpoint
Draft

blasphemetheus wants to merge 15 commits into
elixir-nx:mainfrom
blasphemetheus:feat/recompute-checkpoint

Conversation

@blasphemetheus

@blasphemetheus blasphemetheus commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

What it does

defn twice(x) do
  y = recompute_checkpoint(x, fn x -> Nx.exp(x) end)
  first = Nx.sum(y)
  Nx.sum(y * first)
end

Without recompute_checkpoint, Nx.exp(x) runs once and y stays in memory until the last line. With it, Nx.exp(x) runs for Nx.sum(y), the result is dropped, and it runs again for y * first.

An input that is itself a recompute_checkpoint result is computed again too:

defn chain(x) do
  y = recompute_checkpoint(x, &Nx.exp/1)
  z = recompute_checkpoint(y, &Nx.tanh/1)
  first = Nx.sum(z)
  Nx.sum(z * first)
end

z is used twice, so Nx.tanh runs twice, and each of those runs needs y, so Nx.exp runs twice as well. In a chain of n blocks one use of the last result runs all n.

Under grad

The backward pass is the main place a result has a late second use: the forward pass uses an activation, and much later the gradient of the next layer uses it again.

defn pair(x, w1, w2), do: x |> Nx.dot(w1) |> Nx.max(0) |> Nx.dot(w2) |> Nx.max(0)

defn mlp(ws, x) do
  x = recompute_checkpoint([x, ws], fn x, ws -> pair(x, ws[0], ws[1]) end)
  x = recompute_checkpoint([x, ws], fn x, ws -> pair(x, ws[2], ws[3]) end)
  Nx.sum(x)
end

There is no gradient rule for it. grad differentiates the block like any other, and the saving comes from how the compiler lowers each use.

For the gradient of 16 such blocks (two dense layers each, width 1024, batch 32768), peak scratch memory on CUDA is 0.93 GB against 4.45 GB plain. grad_checkpoint/2 from #1865 needs 2.47 GB. The cost is that inputs are rebuilt at every use: the compiled gradient has 575 matrix products against 95 plain, and that count grows with the square of the depth.

On the host client the same gradient needs 6.57 GB against 8.46 GB plain, where grad_checkpoint/2 needs 2.42 GB. So this is the lower-memory option on a GPU only, and the slower one everywhere.

How it works

recompute_checkpoint/2 builds an Nx.block with an Nx.Block.RecomputeCheckpoint struct.

  • Nx.Defn.Evaluator stores a recipe for the block in place of its result and runs the recipe for every consumer.
  • EXLA does not cache the block by id, so every consumer lowers its own copy. Each copy reads its inputs through an optimization barrier shared with the consumer's other operands, which keeps XLA from merging the copies or running one early.

Limits

Two uses that do not depend on each other share one copy

y = recompute_checkpoint(x, &Nx.exp/1)
Nx.sum(y) + Nx.reduce_max(y)

Computing a result again saves memory when there is a gap between an early use and a late one, during which the result would otherwise be held. Here there is no gap. Neither use needs anything from the other, so the compiler may run them together and one copy serves both. EXLA compiles Nx.exp once for this function, and twice when the second use waits on the first (first = Nx.sum(y) then Nx.sum(y * first)).

Nx.Defn.Evaluator runs the function once per use in both cases. The values agree; the amount of work differs between the two compilers.

A while takes one copy and carries it

y = recompute_checkpoint(x, &Nx.exp/1)

{_i, acc} =
  while {i = 0, acc = y}, i < 3 do
    {i + 1, acc * 0.5}
  end

The variables of a loop are stored values. y is computed once when the loop starts, and from then on acc is an ordinary tensor the loop holds. To compute again on each iteration, call recompute_checkpoint inside the loop body.

One block per iteration saves nothing in the gradient of a while

grad does not store the state of each iteration of a while. It rebuilds each state from the initial one when the backward pass needs it, so the gradient of a loop holds the intermediates of one iteration at a time. Nothing is kept across iterations for a block to give back.

With one block of two dense layers per iteration, the gradient needs 472 MB of scratch memory on the host client with or without recompute_checkpoint, and the same with grad_checkpoint/2. When one iteration is a chain of four blocks, it drops from 1279 MB to 1080 MB, because there are activations inside the iteration that would otherwise be held. On CUDA that loop needs 809 MB either way, so inside a while the saving is on the host client only. In the gradient of a loop, the copies are tied only to values that exist when the iteration starts (the loop state and slices of the weights), so on CUDA they are computed at the start of the body and held.

A side effect in the function happens once per use

y = recompute_checkpoint(x, fn x -> io_call(Nx.exp(x), &IO.inspect/1) end)
first = Nx.sum(y)
Nx.sum(y * first)

The function runs for every use of its result, so this prints twice where the plain function prints once.

Tests

nx/test/nx/defn/recompute_checkpoint_test.exs (17 tests) counts runs of the function in the evaluator for two uses, a chain, a nested call, a tuple result, a vectorized result, cond and while, and checks gradients against the plain function for the same cases.

exla/test/exla/defn/recompute_checkpoint_test.exs (17 tests) counts instructions in the compiled program for the same consumers plus another block, and checks scratch memory forward and under grad.

🤖 Generated with Claude Code

blasphemetheus and others added 13 commits November 22, 2026 10:59
Ports the October per-use experiment (751d120) to current main.

checkpoint/2 builds an Nx.block with an Nx.Block.Checkpoint struct. The
result of that block is not kept:

  * The evaluator keeps the evaluated inputs and runs the body again for
    every consumer.
  * EXLA lowers the block again for every consumer. Each copy reads its
    inputs through an optimization barrier shared with the consumer's other
    operands, and the consumer reads those operands from the same barrier.
    Inputs that are checkpoint blocks are lowered again too, so a chain of
    checkpoints recomputes everything before each use.

Gradients use the existing block rule.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The plain function already fuses the matrix into both uses there.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The construct has its own name and block struct, Nx.Block.Recompute, so it
does not share a name with gradient checkpointing.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…luator

EXLA gave a tied copy only to consumers lowered through the generic
operator path. A while, another block, or an element of a tuple result got
one copy that XLA merged with the others. The copies are now made in
recur_operator for every kind of consumer, and the element of a tuple
result is no longer cached.

The evaluator kept the evaluated inputs of a recompute block, so an input
that was itself a recompute block ran once. It now keeps a recipe for such
inputs and runs it again on every use, as EXLA does.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…than a tuple

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Ports the cases written for checkpoint/2 that compare values and gradients
with the plain function: cond, while, custom_grad, stop_grad, containers,
vectorization, shared weights, nesting, higher-order gradients and random
keys.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Run counts for a vectorized result, a side effect in the function, and
scratch memory for a large result used inside cond and inside a while body.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The gradient of a while keeps no state per iteration, so one block per
iteration saves nothing and a chain of blocks inside one iteration does.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Nx.Block.Recompute becomes Nx.Block.RecomputeCheckpoint.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Drops the cases carried over from the gradient checkpointing tests that
only vary the body of the function. recompute_checkpoint/2 has no gradient
rule of its own, so they exercised the general block gradient. Keeps one
test per distinct path: uses, chains, nesting, tuple results, vectorized
inputs, cond, while, side effects and input validation.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
On CUDA the plain function already computes the exponential once per use
in the block consumer case, and the gradient of the loop needs the same
scratch memory with or without recompute_checkpoint.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@blasphemetheus

Copy link
Copy Markdown
Contributor Author

Right now in recompute_checkpoint there is no special gradient rule. One way you could change this if desired would be to scrap that conception and instead reuse the gradient rule from 1865, though this would muddy the difference between the two. I won't make that change unless it is wanted I think.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant