Skip to content

Skip the replayed LoRA MLP down projection under block compile - #18641

Merged
danielhanchen merged 2 commits into
mainfrom
nwa-block-compile-replay-skip
Nov 20, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
nwa-block-compile-replay-skip

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Follows up #18607 (and its zoo companion unslothai/unsloth-zoo#2630), both merged. #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 Skip the LoRA MLP down projection in gradient checkpoint replays #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 Skip the LoRA MLP down projection in gradient checkpoint replays #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 (#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 Skip the LoRA MLP down projection in gradient checkpoint replays #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.

On torch >= 2.11 block compile traces each decoder layer, so the eager
thread-local token never fires. The block wrapper now sets a guarded
global around a checkpoint replay of an eligible layer (the tagged
LlamaDecoderLayer_fast_forward with the fused SwiGLU LoRA MLP and no
forward hooks); the traced LoRA_MLP drops the down GEMM in that graph.
The no-grad forward call trials the same skip graph, so each layer kind
still compiles two graphs and later steps compile nothing.
@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-20T16:07:31.713801Z f3a8bff 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. 🚀

Reviewed commit: ec79f9bf63

ℹ️ 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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: f3a8bffe40

ℹ️ 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 ddac56b into main Nov 20, 2026
@danielhanchen
danielhanchen deleted the nwa-block-compile-replay-skip branch November 20, 2026 16:24
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