Skip to content

Skip the LoRA MLP down projection in gradient checkpoint replays - #18607

Merged
danielhanchen merged 2 commits into
mainfrom
cg2-skip-replay-mlp-down
Nov 20, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
cg2-skip-replay-mlp-down

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Under gradient checkpointing, the replay of a Llama-style decoder layer re-runs the whole fused LoRA MLP, including the down projection. LoRA_MLP.backward only reads X, e and g. The down output i feeds residual + i, which is the layer output and so the checkpoint output, and the checkpoint's nested backward never reads that value. This PR skips h = act(e) * g and the down GEMM (plus its 4-bit dequantize) during that replay. Gradients come out the same.

Needs the companion unsloth-zoo change (unslothai/unsloth-zoo#2630), which adds gradient_checkpoint_replay_module(). With an older unsloth_zoo nothing is skipped.

When it engages

All of these have to hold:

  • An Unsloth reentrant checkpoint (unsloth_gradient_checkpoint, the offloaded one, or UnslothCheckpointFunction) is replaying, and its checkpointed function is exactly this layer's call. The forms accepted are the module itself, its bound __call__ / forward, a functools.partial over those (transformers' GradientCheckpointingLayer and the block-compile partial(forward, self)), or the tagged custom_forward in LlamaModel_fast_forward. If one checkpoint wraps several layers, nothing is skipped.
  • The layer is LlamaDecoderLayer_fast_forward, which covers Llama, Qwen2, Qwen3 and Mistral. Gemma 2 / 3 (post-FFN norm), Cohere, Granite, MoE and hybrid layers keep their own forwards and never arm the skip.
  • Neither the layer nor the MLP has a forward hook, and there are no global forward hooks.
  • The MLP has no LoRA dropout and no LoRA bias.
  • Nothing is being traced. Blocks compiled by block compile (torch >= 2.11 by default) still run the down projection: the arm call folds away under tracing, and fullgraph=True still traces the layer.

UNSLOTH_GC_SKIP_MLP_DOWN=0 turns it off. fast_lora.MLP_DOWN_SKIP_STATS["skipped"] counts the skips.

Tests

  • tests/test_gc_skip_replay_mlp_down.py builds tiny Llama and Qwen3 models with PEFT LoRA and the real LlamaDecoderLayer_fast_forward and apply_lora_mlp_swiglu. It runs three checkpointers against three call forms. The skipped output is filled with NaN. Every LoRA gradient and the input gradient must be bitwise equal to the same run with the skip off, and the skip count must be exactly one per layer per backward. The file also covers: a two-layer checkpoint (0 skips), a forward hook (that layer is not skipped and its replay output stays real), LoRA dropout (0 skips), calls outside a replay (0 skips), a fullgraph=True compile of the layer, and a check that only the Llama layer arms the skip. The UnslothCheckpointFunction cases need CUDA; they passed on an L4.
  • The zoo side adds tests/test_gc_replay_module.py (which call forms resolve, set only during a replay, nested restore).
  • On base, the new unsloth test fails 17 of 17 cases.

Numbers

Colab L4, torch 2.10.0+cu128, unsloth/Qwen3-4B-unsloth-bnb-4bit, LoRA r=16 on all projections, use_gradient_checkpointing="unsloth", batch 1, synthetic tokens. 3 warmup steps, then the median of 8 timed steps. Base and head arms were interleaved, 3 runs each. Base is the merge base.

seq base median (3 runs, range) head median (3 runs, range) head with UNSLOTH_GC_SKIP_MLP_DOWN=0 change
2048 1.459 s (1.405 to 1.461) 1.365 s (1.363 to 1.385) 1.474 s -6.5%
4096 3.042 s (3.035 to 3.061) 2.852 s (2.848 to 2.879) 3.061 s -6.3%

In every run, the slowest head arm is faster than the fastest base arm. Peak allocated memory is unchanged (4.165 GB at 2048, 4.414 GB at 4096). The skip count is 396 per arm (36 layers x 11 steps), and 0 with the kill switch. Per-step losses match base to within the spread between base runs (step 1 is identical in every arm).

Llama-3.2-3B 4-bit on an A100 80GB (torch 2.10), seq 4096: base 0.5265 s (0.5259 to 0.5267), head 0.4952 s (0.4944 to 0.4953), -5.9%. At seq 2048 the difference (-1.5%) is inside the run-to-run spread. The skip count is 308 per arm (28 layers x 11 steps).

torch 2.14.1, where block compile is on by default (Qwen3-4B, A100 80GB, seq 2048): 0 skips, as intended, and no timing change outside the spread (base 0.3788 s, head 0.3803 s). Peak memory is identical.

While a reentrant checkpoint replays a Llama-style decoder layer (Llama, Qwen2,
Qwen3, Mistral), the fused LoRA MLP only has to rebuild X, e and g for its
backward. The down projection output feeds residual + i, the layer output, which
is the checkpoint output and is never read by its nested backward. The replay now
skips h = act(e) * g and the down GEMM (including its dequantize) for that layer.

Armed only when the replay's checkpointed function is exactly this layer (zoo
gradient_checkpoint_replay_module), the layer and MLP carry no forward hooks, the
MLP has no LoRA dropout or bias, and nothing is being traced. UNSLOTH_GC_SKIP_MLP_DOWN=0
turns it off; an older unsloth_zoo never skips.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T10:19:10.297313Z 1ff01c7 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 1ff01c7d6a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 984f9e1 into main Nov 20, 2026
@danielhanchen
danielhanchen deleted the cg2-skip-replay-mlp-down branch November 20, 2026 13:24
oobabooga pushed a commit to oobabooga/unsloth that referenced this pull request Nov 20, 2026
…thai#18641)

## Summary

Follows up unslothai#18607 (and its zoo companion unslothai/unsloth-zoo#2630),
both merged. unslothai#18607 skips the LoRA MLP down projection while a gradient
checkpoint replays a Llama-style decoder layer, but only on the eager
path. On torch >= 2.11, the default, block compile traces each decoder
layer, so the eager thread-local token never fires and the skip runs 0
times. This PR brings the skip to the compiled block.

## How

- `_block_compile._wrap.forward` (eager, outside the compiled region)
decides per call whether this is a checkpoint replay of exactly this
layer (`gradient_checkpoint_replay_module() is layer`) and whether the
layer is eligible:
- its forward is tagged `_unsloth_mlp_output_unread` (only
`LlamaDecoderLayer_fast_forward`, which Llama / Qwen2 / Qwen3 / Mistral
use; its MLP output only feeds `residual + mlp(x)`);
- the MLP's own `forward` is `apply_lora_mlp_swiglu`, with no accelerate
hook or tiled MLP around it;
  - there are no forward hooks on the layer or the MLP, and none global.
- If so, it sets the plain global `fast_lora._BLOCK_SKIP_DOWN` around
the compiled call. The traced `LoRA_MLP.forward` reads it, so dynamo
guards on it, and the replay graph returns an unfilled tensor instead of
running `act(e) * g` and the down GEMM (plus its NF4 dequantize).
- The block's grad-mode trial (run on the first no-grad call, which
under Unsloth checkpointing is the checkpointed forward) now trials the
skip graph, which is the graph the replay will use. So each layer kind
still compiles two graphs (no grad, grad), as before. Later steps
compile nothing, and there is no graph break.
- A grad-mode call that is not an eligible replay keeps the full graph,
through its own `checked` bit (2 = full, 4 = skip). For example,
training without checkpointing or with a hooked layer compiles that
graph on first use, through the usual strict compile and demotion path.
- LoRA dropout or a LoRA bias takes `LoRA_MLP`'s other branch, which
always runs the down projection.
- `UNSLOTH_GC_SKIP_MLP_DOWN=0` turns it off, as in unslothai#18607.

## Tests

`tests/test_gc_skip_replay_mlp_down_block_compile.py` (CPU, torch >=
2.11). It wraps the real `Qwen3DecoderLayer` with block compile's
`_wrap` (aot_eager backend), uses real PEFT LoRA,
`LlamaDecoderLayer_fast_forward` and Unsloth's reentrant checkpoint,
with the skipped output NaN-filled.
- Every replayed layer output is NaN and the skip count is exactly
N_LAYERS. Every LoRA gradient and the input gradient match the same
compiled run with the skip off (bitwise on Intel CPU and Colab CUDA; the
test allows a few ulps, rtol 1e-5, because Inductor CPU codegen on the
AMD CI runners with torch 2.11 rounds the two graphs a few ulps apart),
and are close to the uncompiled, uncheckpointed layers.
- The graph count is unchanged against the skip off. Two more steps add
0 graphs, 0 recompiles and 0 graph breaks.
- A forward hook, LoRA dropout, or a call outside a replay does not
skip.
- On unslothai#18607's head the same file fails (skip count 0 vs 3).

## Numbers

Colab, torch 2.14.1+cu130 (the default block compile path),
`unsloth/Qwen3-4B-unsloth-bnb-4bit`, LoRA r16 on all projections,
`use_gradient_checkpointing = "unsloth"`, bs1. Each arm takes 3 warmup
steps, then the median of 8 steps. Base (unslothai#18607 head, equal to main for
this code) and head are interleaved 3 times each; the spread is the
range over the 3 runs. Every arm compiles cold
(`TORCHINDUCTOR_FORCE_DISABLE_CACHES=1`).

| GPU | seq | base median (range) | this PR median (range) | kill switch
| change |
|---|---|---|---|---|---|
| L4 | 2048 | 1.352 s (1.333-1.355) | 1.255 s (1.251-1.258) | 1.354 s |
-7.1% |
| L4 | 4096 | 2.827 s (2.786-2.853) | 2.662 s (2.652-2.667) | 2.841 s |
-5.8% |
| A100 40GB | 2048 | 0.3845 s (0.3600-0.3859) | 0.3647 s (0.3639-0.3700)
| 0.3868 s | -5.1% |
| A100 40GB | 4096 | 0.6980 s (0.6978-0.6981) | 0.6595 s (0.6583-0.6598)
| 0.6986 s | -5.5% |
| A100 40GB, block CUDA graphs on | 2048 | 0.3587 s (0.3583-0.3594) |
0.3383 s (0.3382-0.3386) | 0.3583 s | -5.7% |
| A100 40GB, block CUDA graphs on | 4096 | 0.6914 s (0.6914-0.6915) |
0.6534 s (0.6534-0.6537) | 0.6908 s | -5.5% |

- In every row except A100 2048 with auto CUDA graphs, the slowest run
with this PR beats the fastest base run. The 0.3600 s base run in that
row is the one where block CUDA graphs auto mode turned graphs on (16
graphs, not 8). With graphs forced on in both arms, the gain is the same
as everywhere else.
- Skips are 396 per seq (36 layers x 11 steps) with this PR, and 0 on
base and with `UNSLOTH_GC_SKIP_MLP_DOWN=0`.
- Dynamo graph count is the same as base and stays flat from step 1 on
(8 per arm). There are 0 recompiles and 0 graph breaks.
- First step (cold compile) is not slower: on L4, base takes 47.1-47.9 s
and this PR 45.9-46.2 s.
- Peak memory is unchanged: +0.6 MB, 4.188 vs 4.189 GB.
- Step 1 loss is equal. Later losses differ only within the base-vs-base
spread.
- On a Colab L4 (CUDA), the new test file, the unslothai#18607 test file and
`tests/test_block_compile.py` give 115 passed, 2 skipped (both
pre-existing). The zoo `tests/test_gc_replay_module.py` gives 8 passed.

### AMD gfx1151 (Linux + Windows 11, torch 2.11 ROCm)

- The default SFT trainer path runs packed rows uncompiled on ROCm, so
there the existing eager skip engages equally on base and head (140 /
140 skips on Qwen3-0.6B), with bitwise equal losses.
- With the compiled block forced (manual loop, unpacked batch): skips 0
on base, 140 on head, 0 with `UNSLOTH_GC_SKIP_MLP_DOWN=0`; losses
bitwise equal; the same graph and graph-break counts on both arms, no
recompiles.
danielhanchen added a commit that referenced this pull request Nov 20, 2026
## Summary

`Repo tests (CPU, rest)` is red on `main` (seen on #18650, reproduced on
current `main`):

```
FAILED tests/test_autograd_inplace_outputs.py::test_no_inplace_mutation_of_returned_fresh_tensors
AssertionError: unsloth/kernels/fast_lora.py:686 LoRA_MLP: i.fill_(_SKIPPED_FILL)
```

## Cause

#18607 (skip the LoRA MLP down projection in gradient checkpoint
replays) builds the skipped output as `i = X.new_empty(X.shape)`. When
the test-only `_SKIPPED_FILL` sentinel is set, it then calls
`i.fill_(_SKIPPED_FILL)`. `i` is returned from `LoRA_MLP.forward`.

The guard exists because torch 2.11 compiles a wrong gradient for an
ATen in-place op on a fresh tensor a `torch.autograd.Function` forward
returns (#14712), and the block-compile path (#18641) traces this
forward. The guard is right, and the skip itself is right: only the
mutation needs to go.

## Change

- `unsloth/kernels/fast_lora.py`: allocate the skipped output already
filled, `X.new_full(X.shape, _SKIPPED_FILL)`, when the sentinel is set.
Otherwise it stays `X.new_empty(X.shape)`. The values are identical
(`new_empty` + `fill_` and `new_full` both give a tensor of that shape
full of that value), and production never sets the sentinel. There is no
in-place op left on the returned tensor.

## Testing

- `tests/test_autograd_inplace_outputs.py` fails on `main` with the line
above and passes with this change.
- `tests/test_gc_skip_replay_mlp_down.py` and
`tests/test_autograd_inplace_outputs.py` on CPU: 20 passed, 6 skipped.
The skipped six need CUDA.
- Not run here: those six CUDA tests, which fill the skipped output with
NaN to prove nothing reads it, and
`test_gc_skip_replay_mlp_down_block_compile.py` (torch >= 2.11 with
CUDA). This host has no local GPU for this session, and the remote
attempt failed in dependency setup before any test ran. CI's GPU jobs
will exercise them.
danielhanchen added a commit that referenced this pull request Nov 20, 2026
…rming layers (#18688)

## Summary

`Repo tests (CPU, rest)` fails intermittently on current `main`. It is
seen on #18650 and #18532, both based on recent `main`, and both runs
include #18607 and #18641:

```
FAILED tests/test_gc_skip_replay_mlp_down.py::test_only_the_post_norm_free_layer_arms
E   AssertionError: assert ['LlamaDecode...e_at_514_178'] == ['LlamaDecode...fast_forward']
E     Left contains one more item: '__resume_at_514_178'
```

## Cause

#18607 added this test. It collects every module-level function in
`unsloth.models.{llama, gemma, ...}` whose source calls
`arm_mlp_output_unread(` and expects exactly
`LlamaDecoderLayer_fast_forward`.

When an earlier test in the same xdist worker compiles that layer and
hits a graph break, Dynamo parks the continuation function
(`__resume_at_<offset>_<n>`) in the compiled function's module globals.
That puts it in `unsloth.models.llama`. Its code object points at
`LlamaDecoderLayer_fast_forward`'s lines, so `inspect.getsource` returns
the same source, and it counts as a second arming layer. The test passes
alone and fails only when such a compile ran first in the worker. The
product code is right; the test's view of the module namespace was not.

## Change

`tests/test_gc_skip_replay_mlp_down.py`: only count a function when its
code name matches the name it is bound under (`fn.__code__.co_name ==
fn_name`). Dynamo's resume functions are bound as `__resume_at_*` but
named `torch_dynamo_resume_in_*`, so they drop out. Every function
defined in the module with `def` still matches.

## Testing

- `tests/test_gc_skip_replay_mlp_down.py`: 18 passed, 6 skipped (the six
need CUDA).
- Reproduced the CI failure with a conftest that plants a resume
function exactly as Dynamo does: same code with `co_name =
"torch_dynamo_resume_in_LlamaDecoderLayer_fast_forward_at_514"`, bound
as `__resume_at_514_178` in `unsloth.models.llama`. The test from `main`
fails with `Left contains one more item: '__resume_at_514_178'`; this
version passes.
- The guard still does its job: planting a real second arming function
in `unsloth.models.gemma` still fails it (`Left contains one more item:
'GemmaDecoderLayer_arming'`).
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