Repository navigation
Fused Qwen3 q_norm / k_norm RMSNorm + RoPE Triton kernel (opt-in) - #13890
Conversation
|
@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. 🚀 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 |
1 similar comment
|
pre-commit.ci run |
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
) 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.
…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.
#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>
Qwen3 applies RMSNorm to every query and key head before RoPE. Unsloth runs this as two
fast_rms_layernormcalls 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:torch.library.triton_opwith registered autograd, with no graph breaks.The kernel is used by
Qwen3Attention_fast_forwardonly whenUNSLOTH_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.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=0as the kill switch.