Skip to content

fix: preserve shared upstream gradients in RoPE backward - #12528

Merged
mahiatlinux merged 3 commits into
unslothai:mainfrom
taking-lying-flat:fix/rope-shared-grad-buffers
Oct 5, 2026
Merged

mahiatlinux merged 3 commits into
unslothai:mainfrom
taking-lying-flat:fix/rope-shared-grad-buffers

Conversation

@taking-lying-flat

Copy link
Copy Markdown
Contributor

RoPE backward can silently corrupt gradients when multiple outputs receive the same contiguous upstream gradient, for example (q + k).backward(g). contiguous() returns the original tensor in this case, and the QK path also reuses contiguous gradients directly. The in-place rotation then changes both the caller's gradient and the gradient seen by another branch.

Give the three backward implementations private buffers before their in-place updates. The fast paths use contiguous clones, including for expanded or strided inputs. The slow path clones before the existing multiply/addcmul operations, preserving their dtype and rounding behavior when half-precision gradients use FP32 cos/sin. Forward's in-place behavior and the Triton arithmetic are unchanged.

This extends the stride-zero fix in #4233 to shared dense gradients. The existing dense-gradient test supplies separate g.clone() tensors to the two outputs, which avoids this case. PyTorch's custom autograd guidance requires backward implementations to leave incoming gradients unmodified.

Reproduction

With a CUDA-enabled Unsloth environment, this assertion fails on main and passes with this change:

import torch
from unsloth.kernels.rope_embedding import fast_rope_embedding

torch.manual_seed(0)
b, h, s, d = 2, 4, 16, 64
inv = 1.0 / (10000 ** (torch.arange(0, d, 2, device="cuda").float() / d))
freqs = torch.outer(torch.arange(s, device="cuda").float(), inv)
emb = torch.cat((freqs, freqs), dim=-1)
indices = torch.arange(s, device="cuda").expand(b, s).contiguous()
x = torch.randn(b, h, s, d, device="cuda", requires_grad=True)
z = torch.randn_like(x, requires_grad=True)
q, k = fast_rope_embedding(x.clone(), z.clone(), emb.cos(), emb.sin(), indices)
g = torch.randn_like(q)
g_before = g.clone()
(q + k).backward(g)
assert torch.equal(g, g_before)

Validation

RTX A1000 Laptop GPU, PyTorch 2.12.1+cu130, Triton 3.7.1. Real autograd and CUDA kernels were loaded through an isolated harness that bypasses package-level model initialization.

FP32 shared-gradient case Main max gradient error vs PyTorch Fixed
Fast single-tensor backward 7.17 4.77e-7
Fast QK backward 5.83 4.77e-7
Slow backward 7.17 2.38e-7
  • 55 local cases passed across FP32/FP16/BF16, expanded and non-contiguous gradients, both public fast paths, and FP32 cos/sin with half-precision gradients. Input gradients remain unmodified.
  • In 25 comparisons, fixed shared-gradient results are bit-identical to the original implementation given separate gradient buffers. The small errors in the table are against the PyTorch reference.
  • All six existing test_rope_backward_matches_reference parameter combinations passed through the isolated harness.
  • Repository pre-commit hooks and git diff --check passed. No test files are included in this PR.

Already-contiguous gradients now incur a copy. Full-model training throughput, peak memory and multi-GPU execution were not measured.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

Resolve the conflict with unslothai#12171 in Fast_RoPE_Embedding.backward: keep
main's _rope_rows launch and give it the private contiguous clone of dY.
@Etherll

Etherll commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

RoPE backward no longer modifies the incoming gradient, so a gradient shared between outputs (for example (q + k).backward(g)) gives correct gradients for q, k and any other branch that uses it.

What changed

  • When one contiguous upstream gradient reached more than one output, all three RoPE backward paths rotated it in place, which corrupted the caller's gradient and any sibling branch. Each backward now rotates a private contiguous copy. Forward and the Triton math are unchanged.
  • The branch conflicted with Make RMSNorm, RoPE and the input-embedding hook traceable by torch.compile #12171. Main is merged in, and the private copy now feeds main's refactored kernel launch.

On a B200 (torch 2.11 + cu128, Triton 3.6), a shared-gradient probe fails on main and passes on c061b8f for the QK, single-tensor and slow paths. With separate gradient buffers, results are bit-identical to main across fp32/fp16/bf16, GQA, transposed and expanded gradients, and so are the loss and gradients of a LoRA step on a tiny Llama. tests/test_rope_zero_stride_grad.py and tests/test_rms_rope_compile.py pass, and compiled and eager gradients still match exactly.

The cost is one extra transient gradient copy per layer in eager backward. On the same machine it was not measurable: a RoPE forward+backward benchmark over seven model shapes moved by a median of +0.1% with no change in peak memory, and LoRA training on Qwen2.5-0.5B, Llama-3.2-1B, Qwen3-0.6B, Gemma-2-2B and Mistral-7B matched main in peak memory and throughput, with losses bit-identical where training is deterministic and otherwise within run-to-run noise. Multi-GPU training and ROCm/XPU were not tested. A regression test for the shared-gradient case would be a good follow-up.

Fork CI (Etherll#114) passed 20 checks. The red checks come from two failures that also happen on main: test_studio_evaluated_unions_do_not_grow, which flags a studio file this PR does not touch, and nine unsloth_zoo mlx tests. The first one stops the Core jobs early, so Core was rerun with that check unblocked. Core (HF=4.57.6 + TRL<1) passed every step; the other Core variants were still running at the time of this update.

@danielhanchen

Copy link
Copy Markdown
Member

The Repo tests (CPU, rest) failure (test_python39_compatibility.py::test_studio_evaluated_unions_do_not_grow, naming studio/backend/requirements/engines/engine_compat.py) is red on main since #11491, not from this PR. #12556 fixes it; a re-run or push after it lands should clear the check.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator

AMD confirmation at c061b8f, RX 6500 XT, Windows 11, torch 2.11 ROCm 7.14. (q + k).backward(g) at base is up to 5.83 off the PyTorch reference and rewrites g on the indexed QK path and the slow path. at head every path matches to rounding and g is untouched. no cost at a training shape (fp16, 1x32x4096x128: 3.04 vs 2.84 ms backward, peak +64 MiB both). one extra data point: under torch.compile the indexed call was already correct at base, so this is an eager-mode bug. LeoBorcherding#95 (comment)

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the backward paths in rope_embedding.py rotate a contiguous upstream gradient in place, so a gradient shared between outputs comes back corrupted, and the private copy fixes it. Will get this reviewed, and a regression test for the shared-gradient case would be welcome.

@mahiatlinux

Copy link
Copy Markdown
Contributor

Independent review and CUDA evidence

Reviewed current upstream 312d126b015eb4e3738e8a360540b832eceb97d8 and final source head aa78f549d2be0a1cbf9c7c8c83bae15a4d3b60c8 through the current-main prospective merge at review PR #91. The final source head and converged mirror head have identical blobs for both changed files.

On Linux x86_64 with an NVIDIA GeForce RTX 5060 Ti, Python 3.12.13, PyTorch 2.12.1+cu130, and Triton 3.7.1:

  • Current main mutated the caller-owned FP32 gradient in the single-tensor, indexed Q/K, and slow backward implementations, with maximum gradient error of 5.68 to 6.29 versus the PyTorch reference.
  • The repaired implementation preserved the caller gradient and matched the reference in 36 CUDA cases across FP32/FP16/BF16 and dense/expanded/transposed upstream layouts.
  • Base and head remained bit-identical in 24 independent-buffer compatibility comparisons, including GQA and mixed FP32 cos/sin with half-precision gradients.
  • The added regression test failed all three targeted implementations on the base code and passed on the repaired implementation. The focused test file passed all 9 cases on real CUDA.
  • The repository formatter with pinned Ruff 0.6.9, focused Ruff check, and git diff --check passed.

Full command-level evidence is recorded in the mirror evidence comment. Review convergence completed on the tested mirror head with no findings.

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants