Skip to content

Checkpoint-replay down_proj skip: add Gemma-1, make the skip call-scoped and hook-aware (also fixes the shipped Llama-family skip) - #18934

Merged
danielhanchen merged 2 commits into
mainfrom
s7-dproj-skip-gemma
Nov 22, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
s7-dproj-skip-gemma

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Gradient checkpointing replays each decoder layer during backward only to rebuild the tensors the fused LoRA MLP saves (X, e, g). The down projection output feeds residual + mlp(x), which is the checkpoint's own output, and its nested backward never reads that value. Llama-style layers already skip the down GEMM in the replay. This PR extends the same skip to Gemma (GEGLU).

Changes

  • models/gemma.py: GemmaDecoderLayer_fast_forward arms and disarms the skip around self.mlp(...) and carries the _unsloth_mlp_output_unread tag, the same as the Llama layer forward.
  • kernels/fast_lora.py: apply_lora_mlp_geglu_exact and apply_lora_mlp_geglu_approx take the replay token, as apply_lora_mlp_swiglu does. block_skip_down_eligible accepts the GEGLU forwards, so the compiled block replay can skip too.
  • Gemma 2 stays off. Its post_feedforward_layernorm reads the MLP output, and its layer forward never arms.
  • Cohere, Granite and Falcon-H1 are left unchanged. Cohere and Granite currently load through FastModel, and Falcon-H1 keeps PEFT's MLP, so none of them runs the fused LoRA MLP the skip lives in.

Tests

New file tests/test_gc_skip_replay_mlp_down_gemma.py, run on CPU in fp32 with torch reference GEGLU kernels, covering both GEGLU forms:

  • The skipped output is filled with NaN. Every LoRA gradient and the input gradient are bitwise equal to the skip-off replay, and match the run without checkpointing.
  • The skip counter reads one per layer, and 0 on the current main.
  • LoRA dropout, forward hooks and calls outside a replay keep the down projection.
  • Under block compile (aot_eager) the replay skips with the same graph count, 0 graph breaks and 0 recompiles.

The two inventory tests now list Llama and Gemma as the arming forwards.

Results

Colab L4, unsloth/gemma-2b, QLoRA r16 on all projections, use_gradient_checkpointing="unsloth", 2 x 2048 tokens, torch 2.14.1, block compile on. Fresh process per arm, order base / head / head / base:

Base Head
Median step (s) 1.5622 / 1.6008 1.4171 / 1.4242
Down projections skipped 0 540 (18 layers x 30 steps)
Steady peak allocated 2.789 GiB 2.740 GiB
Graph breaks 0 0

The step is 10.2% faster against a 2.5% base-to-base spread. The first losses are identical across all arms.

Update: the skip now runs only when nothing outside the layer can see the MLP output

The replay skip is only safe when nothing outside the decoder layer can read or re-enter mlp(x). Six cases broke that. The Llama-style skip already on main shares the same code, so each fix below applies to Llama, Mistral, Qwen2 and Qwen3 as well as Gemma.

  • One observer check on every call. The eager arm and the compiled eligibility now share _mlp_output_unobserved(layer, mlp). It allows the skip only when all of these hold:
    • The MLP's own forward is a fused LoRA MLP bound to that MLP. An Accelerate hook (_hf_hook / _old_forward) or a tiled MLP around it turns the skip off, because Accelerate's post_forward receives the MLP output.
    • The MLP has no forward pre-hook or post-hook. A pre-hook can call the MLP's forward itself and take the one-shot token.
    • The decoder layer has no forward hook and no Accelerate wrapper.
    • No global forward hook or pre-hook is registered.
  • The compiled replay is call-scoped. The process-wide _BLOCK_SKIP_DOWN flag is gone. The block wrapper passes _unsloth_skip_down=True into the one replay call it has checked. The tagged Llama and Gemma layer forwards hand it to the fused MLP, which hands it to LoRA_MLP as an argument. A compiled call on another thread therefore never sees it. Dynamo specialises on the constant, so the graph count is unchanged.
  • The compile warm-up no longer authorises other calls. The grad-mode trial used to authorise the skip through the shared _IN_TRIAL state. It now passes a private keyword to its own recursive call. _IN_TRIAL is kept for the existing bookkeeping only.
  • The eager token is released in a finally block, so an exception inside the MLP cannot leave it set.

Tests

Added to tests/test_gc_skip_replay_mlp_down_gemma.py. Each test runs for Llama (SwiGLU) and for both Gemma GEGLU forms:

  • With an Accelerate hook that squares the output on one layer's MLP or on the layer itself, or with an MLP pre-hook that runs the MLP's forward, that layer keeps its down projection (skip count N-1). All gradients are finite and bitwise equal to the skip-off run. Compiled eligibility is off for those layers.
  • While a compiled replay skips, a compiled MLP call on another thread returns the real projection, not the placeholder.
  • During the compile warm-up of one layer, a grad-mode call of another layer on another thread keeps its projection.

On the previous head and on main, these tests fail for Llama and for Gemma: the skip count is 3 instead of 2, eligibility stays on, and the other thread's output is NaN. With this update they pass. The existing replay-skip, block compile, fused LoRA and FSDP decline suites still pass on CPU (573 passed; the skips are CUDA-only cells).

Re-check on L4

Same setup as above: Colab L4, unsloth/gemma-2b, QLoRA r16, 2 x 2048 tokens, torch 2.14.1, block compile on. Each arm ran in a fresh process, in the order base / head / head / base. Head is this update.

Base Head
Median step (s) 1.5927 / 1.7166 1.5115 / 1.5392
Down projections skipped 0 540 (18 layers x 30 steps)
Steady peak allocated 2.789 GiB 2.740 GiB
Graph breaks / dynamo frames 0 / 2 0 / 2

The skip still engages on every layer. The peak memory saving and the graph count are unchanged. The first two losses match in every arm. The timing on this VM was noisy: the two base runs differ by 7.8%, which is as large as the mean head-vs-base delta (-7.8%). This run therefore neither confirms nor contradicts the earlier -10.2%. The adjacent pairs give -5.1% and -10.3%. The change adds only a few per-call attribute checks and replaces a global flag with an argument, and the compiled graphs are the same.

Interleaved re-check on L4

Timing (one Colab L4, torch 2.14.1, transformers 5.17.0, unsloth/gemma-2b and unsloth/Llama-3.2-1B QLoRA r16, use_gradient_checkpointing="unsloth", 2 x 2048 tokens, 30 steps, median of steps 9-30, fresh process per run, base f3df81d and this PR interleaved B H B H B H). Gemma-2b: base 1.659 s/step (3 runs, spread 7.4%), this PR 1.478 s/step (spread 3.4%), so -10.9%. All three PR runs are faster than all three base runs. All 540 replay down projections (18 layers x 30 steps) are skipped, steady peak memory drops from 2.789 to 2.740 GiB, graph breaks stay at 0, and the first two losses are identical. Llama-3.2-1B, where the skip already ships: base 0.748 s/step (spread 0.9%), this PR 0.749 s/step (+0.1%, inside the noise). It skips 480 projections on both sides, and memory and losses are identical, so the new per-call observer check costs nothing measurable on the existing path.

The replay skip already covers Llama-style layers. Gemma's decoder layer also feeds the MLP output only
into residual + mlp(x), so its replays can skip the down projection too. Arm the skip in the Gemma layer
forward, let both GEGLU LoRA MLP forwards take the token, and let block compile accept the GEGLU kernels.
Gemma 2 stays off: its post-MLP norm reads the projection.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 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-22T20:06:15.653937Z f8a7357 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. Hooray!

Reviewed commit: dc64ab63fb

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

…ees the MLP output

The eager arm and the compiled eligibility now share one check, run on every call: the MLP forward is a
fused LoRA MLP bound directly to the MLP (no accelerate hook or tiled wrapper), the MLP has no forward pre
or post hook, the decoder layer has no forward hook or accelerate wrapper, and no global forward hook is set.

The compiled replay no longer reads a process-wide flag. The block wrapper passes _unsloth_skip_down=True
into the one replay call; the tagged Llama and Gemma layer forwards hand it to the fused MLP and on to
LoRA_MLP as an argument, so a call on another thread never sees it. The compile warm-up passes its own
keyword to the recursive trial call instead of authorising the skip through the shared _IN_TRIAL state.
The eager token is released in a finally block.

The Llama-style skip on main shares this code, so the same fixes apply to it, and the new tests run for
Llama as well as both Gemma GEGLU forms.

[skip ci]
@danielhanchen danielhanchen changed the title Skip the down projection in checkpoint replays of Gemma layers (-10% step on L4) Checkpoint-replay down_proj skip: add Gemma-1, make the skip call-scoped and hook-aware (also fixes the shipped Llama-family skip) Nov 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: f8a7357301

ℹ️ 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 77f216c into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the s7-dproj-skip-gemma branch November 22, 2026 23:25
ouyang-2019 pushed a commit to ouyang-2019/unsloth that referenced this pull request Nov 23, 2026
… replay skip eligibility (unslothai#18986)

### What

Follow-ups to unslothai#18811 and unslothai#18934 in block compile
(`unsloth/models/_block_compile.py`, `unsloth/kernels/fast_lora.py`):

1. The checkpoint shim that block compile puts back outside the block
(`_checkpointing`) now follows the transformers 5.24
`GradientCheckpointingLayer` wrapper. It checkpoints only while grad is
enabled, and it clears the renamed `cache=` keyword as well as
`past_key_values=` / `layer_past=`. `_has_cache` also treats `cache=` as
a cache call, so cached calls keep the stock forward as they did with
`past_key_values=`.
2. `patch_block_compile` rebinds accelerate-hooked layers of a model
whose layer class was already wrapped for an earlier model. The
installed forward keeps the forward it replaced
(`_unsloth_block_before`) for that rebind.
3. `block_skip_down_eligible` refuses MLPs whose gate / up / down
adapters have a dropout module or a `lora_B` bias.
`_mlp_output_unobserved` refuses an MLP class that overrides `__call__`.

### Why

1. transformers 5.24 renamed the layer cache keyword to `cache`. It also
stopped checkpointing a training-mode layer under `no_grad`, so
`generate()` on a model left in `train()` keeps its cache. The shim
still checkpointed under `no_grad`, never cleared `cache=`, and
`_has_cache` missed `cache=`. A cached call therefore ran the compiled
block and could write the cache twice. The repro was a two-layer random
Llama on transformers 5.24.0 behind accelerate dispatch hooks, CPU,
torch 2.14.1. The block was installed with `aot_eager`:
- `no_grad` prefill + decode in train mode: main raised `The size of
tensor a (6) must match the size of tensor b (3)` (6 cached keys against
a 3-position mask), after 17 graphs and 49 breaks. With this change the
cache lengths are 3 then 4 and the logits match stock transformers
exactly (max delta 0), with 0 graphs.
- Grad-enabled forward with an explicit cache: main raised the same
error. Here it runs, matching stock transformers.
2. unslothai#18811 rebinds accelerate's `_old_forward` only when it wraps the
class. A second model of the same layer class, dispatched before the
first was patched, kept the stale bound wrapper. On transformers 5.23+
that means no checkpointing and no compiled block. Same repro,
transformers 5.24: the second model's layer ran its projection once with
no regional graph on main (no checkpoint replay). With this change it
runs twice with one graph, the same as the first model.
3. LoRA dropout and a `lora_B` bias take `LoRA_MLP`'s branch that always
runs the down projection. The compiled block still passed the skip flag
(an extra replay graph) and counted a skip in `MLP_DOWN_SKIP_STATS`. On
Gemma GEGLU with `lora_dropout=0.1`, main counted 3 skips for 3 layers
whose replay outputs were all finite (none skipped). An MLP subclass
that overrides `__call__` can transform `mlp(x)` outside its forward.
With a `__call__` that squares the output, main still skipped that
layer's down projection in eager. The backward through the square then
read the placeholder: 29 of 43 gradient tensors differed from skip-off,
on both GEGLU forms and on Llama SwiGLU.

### Tests

Each new test fails on main (`632c437424`) and passes here (CPU, torch
2.14.1):

-
`tests/test_block_compile.py::test_block_checkpoint_shim_keeps_the_5_24_cache_contract`:
main checkpointed under `no_grad` (`[1] == []`).
-
`tests/test_block_compile.py::test_block_rebinds_hooked_layers_of_a_second_model`:
main ran the second model with no checkpoint (`[] == [1]`).
-
`tests/test_gc_skip_replay_mlp_down_gemma.py::test_mlp_call_override_keeps_down_projection[gemma_approx|gemma_exact|llama]`:
main counted 3 skips where 2 are allowed.
-
`tests/test_gc_skip_replay_mlp_down_gemma.py::test_compiled_replay_with_lora_dropout_counts_no_skip[gemma_approx|gemma_exact]`:
main reported a dropout MLP as skip-eligible.

Suites, run with unsloth-zoo main for
`gradient_checkpoint_replay_module`:

- `tests/test_block_compile.py`,
`tests/test_gc_skip_replay_mlp_down.py`,
`tests/test_gc_skip_replay_mlp_down_gemma.py` and
`tests/test_gc_skip_replay_mlp_down_block_compile.py` on transformers
4.57.6: 134 passed, 25 skipped (CUDA only).
- `tests/test_block_compile.py` on transformers 5.23.0 (torch 2.15.0)
and on 5.24.0: 81 passed, 9 skipped. The 2 failures in each venv also
fail on main: `vllm.sampling_params` is missing there.

### Not covered

- No GPU run. To confirm on a GPU, run training-mode `generate()` from a
QLoRA Llama on transformers 5.24 with block compile on, once on a single
GPU and once with `device_map` split across 2 GPUs. Also run a Gemma
LoRA with `lora_dropout > 0` under block compile and check the graph
count.
- Two findings are not changed here. An enclosing
`torch.compile(fullgraph=True)` around a hooked model still breaks on
the block's inline flags inside the checkpoint. The FP8-LoRA
per-instance `layer.forward` still shadows accelerate's hook (this
predates unslothai#18811).



## GPU check

Colab L4, transformers 5.24.0, QLoRA Llama-3.2-1B through FastModel with
block compile on, left in train(): a no-grad prefill then one cached
step raises `expanded size (12) must match (6)` on the merge base; with
this PR the cache goes 6 then 7. Gemma with lora_dropout=0.1: base marks
the layer skip-eligible and compiles 3 graphs, this PR refuses and
compiles 2. Unit tests: base 7 failed, head 129 passed.
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