Repository navigation
RMSNorm: opt-in saving of the norm output instead of its input (UNSLOTH_RMSNORM_SAVE_OUTPUT) - #13868
Conversation
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". |
[skip ci]
|
pre-commit.ci run |
… not overwritten either [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b0197b4fee
ℹ️ 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".
| ) | ||
| dX = dX.view(*shape) | ||
| return dX, dW, None, None | ||
| return dX, dW, None, None, None |
There was a problem hiding this comment.
Preserve backward arity for four-argument calls
When Fast_RMS_Layernorm.apply is invoked using the pre-existing four-argument form, as it still is in tests/test_rmsnorm_gradient_layout.py:44 and multiple weight-gradient tests, autograd records four inputs, so this unconditional five-item return makes .backward() fail with an incorrect-number-of-gradients error. A defaulted save_output parameter does not count as a supplied input; update those callers to pass False or make the backward return match the number of arguments supplied.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
PyTorch accepts extra trailing None gradients from a custom Function's backward: when backward returns more values than forward inputs, the extras must all be None and are dropped (torch/csrc/autograd/python_function.cpp). The four-argument callers work: tests/test_rmsnorm_gradient_layout.py and tests/test_rmsnorm_weight_grad.py pass on GPU on this head, together with the save-output tests.
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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". |
# Conflicts: # unsloth/kernels/rms_layernorm.py
|
@codex review |
1 similar comment
|
@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". |
…13888) 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. --------- Co-authored-by: mahiatlinux <[email protected]>
…path free of opt-in checks (unslothai#13981) Follow-up to unslothai#13868. 1. With `UNSLOTH_RMSNORM_SAVE_OUTPUT=1`, a decoder forward over norm weights created inside `torch.inference_mode()` raised `RuntimeError: Inference tensors do not track version counter.` from `_save_output_ok`. Inference-tensor weights now fall back to saving X. The saved-Y path is also skipped when X needs no grad, since backward never runs and the weight check and its `.item()` would be wasted. 2. Default path (flag off): fused LoRA no longer calls the saved-norm marker check on every forward, and RMSNorm backward only reshapes the saved tensor when it is Y. Results with the flag off are unchanged. Tests: two new tests in `tests/test_rmsnorm_save_output.py` (both fail on main); RMSNorm and fused LoRA GPU tests pass (629 passed).
Unsloth only installed its fused LoRA kernels (QKV, O, and the SwiGLU / GeGLU MLP) when `lora_dropout == 0` and no adapter had `lora_bias = True`. Anything else dropped every layer back to PEFT's per-projection forward, which on a small 4-bit Llama with `lora_dropout = 0.05` costs about 28% more time per step (39.1 ms vs 30.5 ms median, exclusive B200, 3 repeats each) and slightly more memory. This PR runs both inside the fused autograd functions with PEFT's semantics: - Dropout applies only to the LoRA branch input; the base path sees the undropped input. Each projection draws its own mask, in PEFT's order (q, k, v; gate, up, down), with the same ATen call `nn.Dropout` makes (`native_dropout` on CUDA / XPU, `bernoulli_` noise on CPU). On 4-bit (bitsandbytes) bases under autocast, masks and the RNG state afterwards are therefore identical to PEFT's from the same seed. On 16-bit bases PEFT casts the input to the fp32 adapter dtype before dropout and so draws its masks on an fp32 copy; the fused path draws on the bf16 / fp16 activations, so the masks differ there while both are valid Bernoulli draws. Gradient checkpointing recompute replays the masks in both cases. Only the boolean masks are saved for backward; the dropped-out input is rebuilt from them. - `lora_bias`: the bias on `lora_B` is added as `(lora_B(x) + bias) * scaling`, PEFT's order, and its gradient is returned. - With neither feature active the kernels run exactly the previous code. - Kill switches: `UNSLOTH_FUSED_LORA_DROPOUT=0` and `UNSLOTH_FUSED_LORA_BIAS=0` restore the old fallback. DoRA still falls back to PEFT. Testing: - `tests/test_fused_lora_dropout_bias.py` (new): fused vs PEFT from the same seed on CPU and CUDA, fp32 / bf16 / fp16, each scored against an fp64 PEFT run on PEFT's own masks; masks and RNG state are bit-identical; checkpoint recompute is bit-identical; eval mode and the kill switches behave like PEFT. 49 of its cases fail on main (fused path not taken, or dropout ignored when the kernels are called directly). - Existing fused LoRA tests (multiple adapters, QAT, FP8, NVFP4, bnb compile, FSDP gate, patch summary) pass: 353 passed. - fp64 oracle on 1024 / 2816 shapes, all dtypes and configs: 0 failures, with negative controls (scaled output, masks dropped in backward, dX without mask) failing as expected. - torch.compile on torch 2.13: 0 graph breaks, compiled vs eager within the existing envelope. - 20-step QLoRA run on a tiny Llama: runs are bit-reproducible, the kill switch matches main bit for bit, and fused vs PEFT loss differences stay within the difference main already has between its fused kernels and PEFT. While doing this, Inductor on torch 2.13 produced wrong values for `add(..., alpha=float)` inside these autograd functions (eager and aot_eager were correct), so the new code multiplies explicitly. Without autocast (fp32 adapters in a hand-written loop) PEFT draws its masks on an fp32 copy, so the masks differ from the fused path there; both are valid dropout. Trainer runs on 4-bit bases under bf16 / fp16 autocast match PEFT's masks exactly. Composes with unslothai#13868 (both touch the `LoRA_MLP` / `LoRA_QKV` save_for_backward lines; a trivial merge keeps both, and the backward rebuilds the dropped-out input before dX is written into X's buffer). Not covered: DoRA (still falls back), torch 2.6 to 2.10, T4 / L4 / A100 / AMD / XPU, `lora_bias` timing.
) 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.
Each decoder RMSNorm saves its input X for backward, while the LoRA QKV / MLP kernel that consumes the norm output saves that output too. So every layer keeps two T x D tensors that only the norms need.
With
UNSLOTH_RMSNORM_SAVE_OUTPUT=1,Fast_RMS_Layernormsaves the returned output Y instead. That is the same tensor object LoRA already holds, so its storage is shared. The backward kernels rebuild the normalized row asY / W(Y / (1 + W)for Gemma) and keep using the saved rstd. LoRA_QKV / LoRA_MLP no longer write their dX into an input that a norm saved.The path is only taken when:
save_output=True. Only the Llama, Gemma and Gemma2 decoder norms that feed the attention / MLP projections do;Otherwise the previous code runs unchanged. torch.compile graphs keep the existing traced op.
Measured with QLoRA r=16, batch 1, no gradient checkpointing, A100:
Step time is unchanged within noise. Gradients differ by rounding only: against an fp64 reference the dX error stays within 1.07x of the current path (max error equal) for fp16 / bf16 / fp32 and hidden sizes 64 to 4097.
It is opt-in because the gradients are not bitwise identical. With Unsloth gradient checkpointing the gain is negligible, since only one layer's activations are live at a time.
Not covered: T4 / sm75 and ROCm, Gemma save-output on a real model (kernel oracle and unit tests only), and the transformers 4.57 / TRL floor corners. In fp16, Llama-3.2-1B norm weights as small as 1.3e-6 are too close to zero for
Y / W, so 9 of its 32 norms keep saving X (still -8.6% peak). Qwen3 q_norm / k_norm are left on the old path because the Triton RoPE kernel writes their output in place.