Skip to content

Fix RMSNorm and LayerNorm backward overwriting the incoming gradient - #13888

Merged
mahiatlinux merged 5 commits into
mainfrom
dh/rmsnorm-backward-grad-alias
Oct 16, 2026
Merged

mahiatlinux merged 5 commits into
mainfrom
dh/rmsnorm-backward-grad-alias

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

The non-Gemma Fast_RMS_Layernorm.backward and Fast_Layernorm.backward write 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:

  • Autograd hands the same tensor to both inputs of an add, so in norm(x) + x or norm1(a) + norm2(b) the other branch reads dX instead of dY.
  • y.backward(g) and torch.autograd.grad(y, x, g) overwrite the caller's g.

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:

  • The RMSNorm row and multirow kernels always store into their dX pointer.
  • The LayerNorm kernels gain a dX output pointer.
  • The compiled RMSNorm op no longer needs to copy dY first for non-Gemma.

Results:

  • Accuracy: in the shared-gradient graphs the gradient now matches fp64 as closely as eager PyTorch at the same dtype, and the incoming gradient is left unchanged. Graphs that were already correct give the same error as before.
  • Memory: on Llama-3.2-1B and Qwen2.5-1.5B shaped models (4-bit LoRA r=16, bf16, seq 4096, gradient checkpointing off and "unsloth"), peak allocated memory for a training step is identical to main, to the byte. Repeated runs of main show no spread. The extra buffer is one hidden-state-sized tensor that is freed before the step's peak.

Tests: tests/test_norm_backward_grad_alias.py checks 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 this dX = torch.empty_like(dY)), and a trial merge passes both test sets with UNSLOTH_RMSNORM_SAVE_OUTPUT at 0 and 1.

Not covered: speed timing, ROCm / XPU / T4 (memory measured on B200). Nothing in Unsloth calls Fast_Layernorm today, so that half is covered by the unit tests only.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-16T05:02:33.532550Z 98a15af Manual request
🔒 Security Review ⚠️ Failed 2026-10-15T16:27:42.685704Z e5f1cc4 PR opened
ℹ️ 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. Already looking forward to the next diff.

Reviewed commit: e5f1cc46f6

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

@mahiatlinux mahiatlinux self-assigned this Oct 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

…rad-alias

# Conflicts:
#	unsloth/kernels/layernorm.py

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 7b2af687c7

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

@mahiatlinux

Copy link
Copy Markdown
Contributor

Review and fix evidence

Reviewed and repaired current head 98a15af721e4531e4fafba515b6ab1e524c8f557.

What changed

  • Merged current main at b2ea078a520d117c393936d6d732465fc527dd62 and resolved the RMSNorm conflict by composing the recently added FROM_Y save-output path with this PR's fresh dX allocation.
  • Extended the regression matrix across RMSNorm save_output, Gemma mode, trainable/frozen weights, LayerNorm trainable/frozen weights, and fp32/fp16/bf16.
  • Applied the repository's comment-cleanup gate only within PR scope.

Negative and positive proof

  • Exact original base 061d5257738d13213dbe7e6ad18ea02e5da1cb44: 6 failed, 3 passed. Every non-Gemma RMSNorm and LayerNorm case failed because the incoming grad_outputs tensor was overwritten; all three Gemma control cases passed.
  • Exact original PR head 24a8927a6eec0417d52c2fb59f29390a1aacd0e1: 9 passed.
  • Repaired head, UNSLOTH_RMSNORM_SAVE_OUTPUT=0: 30 passed.
  • Repaired head, UNSLOTH_RMSNORM_SAVE_OUTPUT=1: 30 passed.

Regression coverage

  • Affected RMSNorm/LayerNorm GPU suite: 917 passed, 15 skipped, 1 deselected. The skips require two GPUs. The one deselected case, test_compiled_calls_never_use_fast_launch[rms-128-False], was run separately and reproduced unchanged on both the original PR head and repaired head, so it is pre-existing and outside this PR.
  • The affected suite covered launch routing, gradient layouts, trainable/frozen weights, multi-row behavior, empty inputs, save-output behavior, and eager/compiled parity. The tiny Llama compile tests ran from a locally cached public test checkpoint in network-isolated mode.
  • Pinned formatter, Ruff, diff checks, secret/debug scan, and the structural comment-only gate passed. The final worktree was clean.

Norm-level memory and timing probe

On an RTX 5060 Ti with shape (8, 1024, 4096), bf16, 20 timings:

Kernel Original base Repaired head
RMSNorm mutated dY; 67,141,632 B peak delta; 0.854016 ms median preserved dY; 134,250,496 B; 0.856048 ms
LayerNorm mutated dY; 67,174,400 B peak delta; 0.857616 ms median preserved dY; 134,283,264 B; 0.864240 ms

The correctness fix adds one 64 MiB dX buffer at this isolated norm level, with effectively unchanged median latency in this probe. I did not independently rerun the PR body's full-step peak-memory measurements.

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.

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 98a15af721

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

@mahiatlinux mahiatlinux left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Ready to merge, all manually checked.

@mahiatlinux
mahiatlinux merged commit 1b8737b into main Oct 16, 2026
@mahiatlinux
mahiatlinux deleted the dh/rmsnorm-backward-grad-alias branch October 16, 2026 05:13
danielhanchen added a commit that referenced this pull request Oct 16, 2026
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]
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 16, 2026
)

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.
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 19, 2026
…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>
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.

2 participants