Repository navigation
Fix RMSNorm and LayerNorm backward overwriting the incoming gradient - #13888
Conversation
…o the incoming grad
|
@codex review |
Codex Review SummaryThis 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. Already looking forward to the next diff. 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". |
|
pre-commit.ci run |
…rad-alias # Conflicts: # unsloth/kernels/layernorm.py [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
…3888-review # Conflicts: # unsloth/kernels/rms_layernorm.py
Review and fix evidenceReviewed and repaired current head What changed
Negative and positive proof
Regression coverage
Norm-level memory and timing probeOn an RTX 5060 Ti with shape
The correctness fix adds one 64 MiB Environment: Linux x86_64, Python 3.11.15, PyTorch 2.10.0+cu128, Triton 3.6.0, RTX 5060 Ti, driver 595.99.02. All local test execution was network-isolated. Fresh CI is queued on the repaired head. |
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 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". |
mahiatlinux
left a comment
There was a problem hiding this comment.
LGTM! Ready to merge, all manually checked.
UNSLOTH_RETURN_HIDDEN_STATES is set only by Unsloth's own GRPO, DPO and GKD trainers and zoo's GRPO loss, which feed the hidden states to a chunked lm_head loss whose backward returns a fresh grad. Allow final-norm reuse there regardless of slicing, so those runs match the pre-#13888 peak. Only a plain base-model call and output_hidden_states keep the norm's own buffer. [skip ci]
) unslothai#13888 made every non-Gemma `Fast_RMS_Layernorm.backward` write dX into a fresh buffer, so a shared or caller-owned incoming gradient is no longer overwritten. That buffer is one activation-sized tensor. When the norm backward runs at the step's peak, it raises peak memory. One example is a norm followed by a frozen projection. This adds `reuse_grad` (default False) to `Fast_RMS_Layernorm` and `fast_rms_layernorm`: - With `reuse_grad = True`, a non-Gemma backward writes dX over dY, as before unslothai#13888. Gemma and the compiled op are unchanged, since they already used a separate buffer. - These pre-norm decoder norms pass it: - Llama input, post-attention and final norms - Granite, Qwen3-MoE and GLM4-MoE decoder norms - Falcon-H1 input and pre-FF norms - the unfused Qwen3 q/k norms Their outputs only feed projections, RoPE or attention, whose backward returns a fresh gradient, so the default training path again makes the same kernel calls as before unslothai#13888. - Every other caller keeps the fresh buffer and the unslothai#13888 fix: patched `LlamaRMSNorm`, generic norm forwards, and direct `.apply`. - The `UNSLOTH_RMSNORM_SAVE_OUTPUT` path (unslothai#13868) composes with this. Backward reads the saved Y, never dY. The fused Qwen3 QK norm + RoPE path (unslothai#13890) is untouched. Peak memory for norm, frozen projection and backward (bf16, 4096 tokens, bytes above the pre-step allocation): | hidden | before unslothai#13888 | main | this PR | |---:|---:|---:|---:| | 2048 | 57,986,560 | 68,174,848 | 57,986,560 | | 4096 | 114,814,464 | 135,283,712 | 114,814,464 | | 8192 | 228,470,272 | 269,501,440 | 228,470,272 | The same numbers hold with `UNSLOTH_RMSNORM_SAVE_OUTPUT=1`. Gradients are bitwise identical across all arms. Tests: - New `test_rms_layernorm_reuse_grad_matches_and_saves_a_buffer` (fp32/fp16/bf16, Gemma and non-Gemma, save-output on and off). It checks that `reuse_grad` gives bitwise-identical dX and lowers the backward peak by exactly one activation for non-Gemma. - The existing norm, save-output and QK norm + RoPE tests pass. Not covered: speed timing, full-size models, T4 and ROCm.
…lf check, forced float32 skip (unslothai#14188) ## Summary Follow-ups for the head-dim 512 attention kernel (unslothai#13869) and one test gap from unslothai#13888. The default path is unchanged except where noted. 1. **Kill switch read under compile.** `_enabled()` was an `lru_cache`. Dynamo warns when it traces through that wrapper, and it re-reads the environment there, so compiled code could disagree with eager after the variable changed at runtime. It now reads the value once into a module-level holder that both paths share. `_enabled.cache_clear()` still resets it. 2. **4-bit-only GPU shards skipped the self check.** At load, the kernel self-checks every (device, dtype) holding fp16 / bf16 weights. A GPU that holds only bitsandbytes 4-bit weights (uint8 storage, for example with CPU-offloaded embeddings or a device-mapped shard) produced no target, so the kernel stayed off there. It now uses the 4-bit weights' compute dtype from `quant_state`. 3. **No wasted fp16 self check under forced float32.** Models stamped `_unsloth_forced_float32` (zoo's Gemma-4 float32 path) run attention in float32 on plain SDPA and never reach this router, so the patch now returns before the fp16 self check and autotune at load. 4. **Test only:** `test_rms_layernorm_backward_leaves_shared_grad_alone` now sets `_SAVE_OUTPUT` and asserts the backward-from-output path runs. Before, its `save_output = True` cases never exercised that path. ## Tests (GPU) - `tests/test_large_head_attention.py`: 3 new tests (compiled vs eager kill switch, 4-bit-only shard self check, forced float32 skip). They fail on main and pass here. - With `tests/test_norm_backward_grad_alias.py`: 52 passed. Not run here: a real Gemma-4 load for items 2 and 3, or any timing. The kernel itself is unchanged. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
The non-Gemma
Fast_RMS_Layernorm.backwardandFast_Layernorm.backwardwrite dX into the incoming gradient tensor. PyTorch requires backward never to modify its gradient arguments in place, and here it breaks results whenever another node or the caller still reads that tensor:norm(x) + xornorm1(a) + norm2(b)the other branch reads dX instead of dY.y.backward(g)andtorch.autograd.grad(y, x, g)overwrite the caller'sg.Against an fp64 reference, the input gradient error on main in these graphs is 1.2 to 2.6 for fp32, fp16 and bf16.
The decoder path never hit this, because there the norm output feeds a LoRA or linear backward that returns a fresh tensor.
The fix writes dX into a freshly allocated buffer, as the Gemma path already does:
Results:
Tests:
tests/test_norm_backward_grad_alias.pychecks fp32, fp16 and bf16 RMSNorm (Gemma and non-Gemma) and LayerNorm against fp64 on graphs with a shared or caller-owned gradient. The non-Gemma RMSNorm and LayerNorm cases fail on main and pass with this change.#13868 touches the same backward: the two compose (keep its
X = X.view(-1, dim)and thisdX = torch.empty_like(dY)), and a trial merge passes both test sets withUNSLOTH_RMSNORM_SAVE_OUTPUTat 0 and 1.Not covered: speed timing, ROCm / XPU / T4 (memory measured on B200). Nothing in Unsloth calls
Fast_Layernormtoday, so that half is covered by the unit tests only.