Skip to content

Fused Qwen3 q_norm / k_norm RMSNorm + RoPE Triton kernel (opt-in) - #13890

Merged
danielhanchen merged 8 commits into
mainfrom
dh/fused-qknorm-rope
Oct 16, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
dh/fused-qknorm-rope

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Qwen3 applies RMSNorm to every query and key head before RoPE. Unsloth runs this as two fast_rms_layernorm calls plus the Triton RoPE kernel. With the clones around the in-place RoPE, that is 4 forward and about 6 backward launches per layer, plus 3 to 4 autograd Functions. On small models, where LoRA training is dispatch bound, this region costs about 1 ms of host time per layer per forward and backward.

This PR adds unsloth/kernels/qk_norm_rope.py, which does the per-head RMSNorm and the rotation for Q and K together in one forward launch and one backward launch:

  • Same rounding steps as the current path: fp32 rstd, normed in the weight dtype, norm output in the activation dtype, rotation in the cos dtype. bf16 forward outputs are bit-identical to main on the tested shapes. Backward and fp16/fp32 forward match within rounding.
  • Saves the same tensors as today (X, weight, rstd, cos, sin, positions), so activation memory is unchanged.
  • Always writes fresh outputs and never modifies its inputs or the incoming gradient.
  • Supports plain and packed (restarting) position ids, GQA, and head_dim 16 to 1024 (powers of two).
  • Eager uses an autograd Function. Compiled graphs use torch.library.triton_op with registered autograd, with no graph breaks.
  • Trainable q_norm/k_norm weights (full fine-tuning) and any shape it does not cover fall back to the existing path.

The kernel is used by Qwen3Attention_fast_forward only when UNSLOTH_FUSED_QKNORM_ROPE=1. With the variable unset, the attention forward runs the same calls as before, and training is bit-identical to main.

Testing:

  • tests/test_qk_norm_rope.py: accuracy against the unfused path and an fp64 reference across dtypes, head dims 64/128/256, GQA, partial head blocks and packed positions; compile with fullgraph and the same bytes as eager; inputs and gradients untouched; trainable-weight fallback.
  • Kernel oracle against the Hugging Face Qwen3 norm and rotary code compiled by Inductor and an fp64 reference: 72 of 72 rows within tolerance. Errors are equal to or lower than the current path. A 2^-7 perturbation fails every row.
  • Deterministic QLoRA training, 20 steps: bit-identical to main with the variable unset. With it set, the loss difference is the size of the current path's own compiled-vs-eager rounding, and well below an eps-perturbed control.
  • B200, bf16 LoRA, same-process interleaved timing: about 7 to 10% faster per step on a 0.6B-shaped model and 3 to 4% on Qwen3-8B layer shapes. Kernel device time drops 2.9% and 0.7% respectively, with 11 fewer launches per layer per step.

It is opt-in for now because the timings come from a single busy host. Older torch / Triton versions, T4, and ROCm have not been tried. Once those are confirmed, it can become the default, with UNSLOTH_FUSED_QKNORM_ROPE=0 as the kill switch.

@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 ⚠️ Failed 2026-10-16T01:52:32.950499Z 1272767 New commits
🔒 Security Review ⚠️ Failed 2026-10-15T16:30:24.784163Z ffbb8cc 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. 🚀

Reviewed commit: ffbb8ccbbd

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

@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 8b3d6b85b8

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

@danielhanchen
danielhanchen merged commit 701a345 into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the dh/fused-qknorm-rope branch October 16, 2026 07:31
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.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 19, 2026
…e grad in the trainable norm fallback (unslothai#14200)

## Summary

Two follow-ups for the opt-in fused QKNorm + RoPE kernel
(`UNSLOTH_FUSED_QKNORM_ROPE=1`, unslothai#13890). The flag-off path is untouched:
`qwen3.py`, `rope_embedding.py` and `rms_layernorm.py` do not change.

1. **Mixed dtype tables.** With fp32 or fp16 activations and bf16 cos /
sin tables, the fused kernel cast the norm output down to bf16 before
the rotation. The indexed RoPE kernel it replaces (the usual Qwen3 case,
with position indices) multiplies with type promotion and never casts
the activation down. transformers' `apply_rotary_pos_emb` does the same:
the tables follow the activation dtype and the product uses normal torch
promotion. The fused kernel now casts to the table dtype only in the
no-indices mode, so each mode matches the unfused kernel it replaces.
When the dtypes already match, nothing changes: 72 output and gradient
tensors are byte-identical between the old and new kernel.
2. **Trainable norm fallback.** `_unfused` now passes `reuse_grad =
True` to both norms, as the flag-off Qwen3 path does. The norm output
only feeds the RoPE kernel there.

## Tests

`tests/test_qk_norm_rope.py` (GPU, tiny shapes):
- `test_mixed_dtype_tables_match_unfused`: fp32 and fp16 activations
against bf16 tables, with and without indices. The two indexed cases
fail on main; the no-indices cases pass on both.
- `test_trainable_norm_fallback_reuses_grad_buffer`: peak memory goes
from 24,450,048 to 20,255,744 bytes. Fails on main.

All 44 tests in the file pass here, including the existing fullgraph /
no graph break tests.

## Not covered here

- Only B200, torch 2.13, Triton 3.7.1; no end-to-end Qwen3 training run
with the flag on.
- In the no-indices mode the unfused RoPE kernel still rounds fp32
activations to bf16 tables, and the fused forward keeps matching it.
Changing that would alter the default RoPE kernel.
danielhanchen added a commit that referenced this pull request Oct 25, 2026
#13890 added a fused Triton kernel for Qwen3's q/k RMSNorm + RoPE in
training. It sits behind `UNSLOTH_FUSED_QKNORM_ROPE=1`, which is off by
default; the decode variant already ships on. That PR listed T4, older
torch and ROCm as its exit criteria. This PR covers the NVIDIA side and
turns the training kernel on by default there.

### Change
New `_qk_norm_rope_default()` in `unsloth/kernels/qk_norm_rope.py`, read
once at import into `QK_NORM_ROPE_ENABLED`:
- `UNSLOTH_FUSED_QKNORM_ROPE` = `0` / `false` / `no` / `off`: unfused
everywhere;
- `1` / `true` / `yes` / `on`: fused everywhere, including ROCm;
- unset: fused when `DEVICE_TYPE == "cuda"` (NVIDIA, Linux and Windows).

ROCm (`DEVICE_TYPE == "hip"`), XPU and CPU keep the unfused training
path. The fused backward has not been measured on ROCm.

### Results
**Timing.** Qwen3 LoRA SFT steps, torch 2.14 (T4 and A100 also on 2.10):
- every arm in one process per job, interleaved in rotated blocks, with
a fixed batch of about 4k tokens;
- median of block medians over 4-5 rounds;
- negative is faster than main; the A/A (main vs main) delta is in
brackets.

| GPU | torch | 1.7B 16-bit padded | 1.7B 4-bit packed | 0.6B 16-bit
packed | 0.6B 4-bit padded | 8B padded |
|---|---|---|---|---|---|---|
| T4 (fp16) | 2.14 | -0.44% (-0.03) | -0.63% (-0.23) | -1.79% (-0.20) |
-1.27% (-0.89) | 4-bit +0.27% (+0.83) |
| T4 (fp16) | 2.10 | -2.05% (-0.51) | | -2.34% (-1.01) | | 4-bit -0.14%
(+0.32) |
| A100 | 2.14 | -1.58% (-0.25) | -5.28% (+0.69) | -6.53% (-0.38) |
-3.74% (-1.82) | 16-bit -0.86% (-0.07) |
| A100 | 2.10 | -3.00% (+0.46) | | -4.04% (+0.55) | | 16-bit -0.75%
(-0.15) |
| L4 | 2.14 | -0.09% (+0.67) | -1.21% (0.00) | -0.67% (-0.06) | -0.10%
(+0.49) | 4-bit -0.27% (-0.01) |

No cell is slower beyond its A/A band. Peak memory is unchanged.

**Loss.** 50-step runs (20-30 for 8B) from the same LoRA init, seed and
data:
- max |loss difference| vs main is 0.6-1.6x the A/A difference (A/A is
0.002-0.0075 in bf16, 0.0003-0.0011 in fp16);
- final loss is within 0.003.

**Compile and engagement:**
- 0 graph breaks and 0 recompiles in both arms;
- the same unique graph counts in separate processes;
- per step, the fused forward runs 56 times and the fused backward 28
times; the unfused RoPE kernel runs 0 times and there are 0 eager
fallbacks.

### Tests
New cases in `tests/test_qk_norm_rope.py`:
- the env / device decision table (11 cases);
- a real tiny Qwen3 training step in a subprocess, checking that the
fused kernels run with the flag unset and do not run with `0`.

The file gives 57 passed on B200 with torch 2.14 and with 2.10. The
existing parity cases (bf16 forward bit-identical to unfused, gradients
vs an fp64 reference) pass on T4 fp16, A100 bf16 and B200.

### Not covered
- **GPUs:** no H100 (Colab refused it), sm120 or RTX 40xx timing.
- **ROCm:** keeps the unfused path by the gate.
- **Qwen3-MoE:** on transformers 5.x, Qwen3-MoE does not go through this
attention path, so it is unaffected.

---------

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.

1 participant