Repository navigation
Checkpoint-replay down_proj skip: add Gemma-1, make the skip call-scoped and hook-aware (also fixes the shipped Llama-family skip) - #18934
Conversation
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.
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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]
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
… 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.
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_forwardarms and disarms the skip aroundself.mlp(...)and carries the_unsloth_mlp_output_unreadtag, the same as the Llama layer forward.kernels/fast_lora.py:apply_lora_mlp_geglu_exactandapply_lora_mlp_geglu_approxtake the replay token, asapply_lora_mlp_swigludoes.block_skip_down_eligibleaccepts the GEGLU forwards, so the compiled block replay can skip too.post_feedforward_layernormreads the MLP output, and its layer forward never arms.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: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: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._mlp_output_unobserved(layer, mlp). It allows the skip only when all of these hold:forwardis 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'spost_forwardreceives the MLP output.forwarditself and take the one-shot token._BLOCK_SKIP_DOWNflag is gone. The block wrapper passes_unsloth_skip_down=Trueinto the one replay call it has checked. The tagged Llama and Gemma layer forwards hand it to the fused MLP, which hands it toLoRA_MLPas an argument. A compiled call on another thread therefore never sees it. Dynamo specialises on the constant, so the graph count is unchanged._IN_TRIALstate. It now passes a private keyword to its own recursive call._IN_TRIALis kept for the existing bookkeeping only.finallyblock, 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: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.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.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-2bandunsloth/Llama-3.2-1BQLoRA r16,use_gradient_checkpointing="unsloth", 2 x 2048 tokens, 30 steps, median of steps 9-30, fresh process per run, basef3df81dand 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.