Skip to content

Fast decode: rotate Q and K in one launch, and fuse Qwen3 q/k norm with RoPE - #14599

Merged
danielhanchen merged 5 commits into
mainfrom
grpo-decode-fused-rope
Oct 22, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
grpo-decode-fused-rope

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

In Unsloth's fast decode path (LlamaAttention_fast_forward_inference and the Qwen3 decode attention), each layer rotates Q and K for the single new token in eager ops. The path:

  • gathers cos / sin at the position;
  • builds rotate_half copies;
  • multiplies and adds.

Qwen3 also runs q_norm and k_norm as separate RMSNorm launches before that. This costs about 12 launches per layer per decoded token, and at small GRPO rollout sizes decode is launch-bound. HF generate rollouts (GRPO without vLLM) spend 95 to 97% of each step decoding, so this is where the step time goes.

Change

  • decode_rope_inplace (unsloth/kernels/rope_embedding.py): for single-token decode, one launch rotates Q and K in place at their positions. It reuses the existing _rope_qk Triton kernel.
  • decode_qk_norm_rope (unsloth/kernels/qk_norm_rope.py): for Qwen3, one launch runs q_norm + k_norm + RoPE, built on the existing fused fast_qk_norm_rope kernel.
  • Both helpers write nothing and return False / None where they do not apply. The caller then runs the old code unchanged. They do not apply:
    • when the sequence length is not 1;
    • on a non-CUDA device;
    • while torch.compile is tracing;
    • when Q, K, cos or sin have different dtypes;
    • on non-contiguous tables, odd head dims, or a position count that does not match the batch.
  • UNSLOTH_DECODE_FUSED_ROPE=0 restores the previous path.
  • Training and prefill code paths are unchanged.

Validation

In-process A/B with the kill switch toggled per rep, arms interleaved, 6 reps:

  • setup: batch 4, LoRA r = 32 with non-zero B attached (as GRPO's HF generate rollout runs it), greedy;
  • timing: median generate wall time, 128 new tokens.
GPU torch Qwen3-0.6B 16-bit Qwen3-0.6B 4-bit Llama-3.2-1B 16-bit
Colab T4 2.10.0 1.143x 1.138x 1.029x
Colab T4 2.14.1 1.182x 1.148x 1.037x
Colab L4 2.10.0 1.164x 1.146x 1.032x
Colab L4 2.14.1 1.183x 1.156x 1.040x
Kaggle T4 2.11.0 1.134x 1.129x 1.024x
Kaggle T4 2.12.1 1.150x 1.140x 1.035x
Kaggle T4 2.13.0 1.140x 1.119x 1.020x
  • Per-arm spread is 5% or less, so the Qwen3 gain is well outside noise.
  • The Llama gain (3 to 4%) is within the T4 spread (up to 4.3%) and is marginal.
  • CUDA kernels per decoded token, L4, torch 2.14:
    • Qwen3 16-bit: 1878 -> 1150;
    • Qwen3 4-bit: 1959 -> 1231;
    • Llama: 843 -> 683.
  • Engagement: on Qwen3 the fused q/k norm + RoPE runs 196 times in 8 tokens (28 layers x 7 decode steps) and the plain RoPE helper 0 times. On Llama the RoPE helper runs 112 times (16 x 7).

End to end, a full GRPO job on B200, torch 2.14:

  • setup: Qwen3-0.6B LoRA, HF generate rollouts, 256 completion tokens, 3 repeats per arm.
main this PR
steady step ms (3 repeats) 11654, 11717, 12185 8612, 9385, 9887
tokens/s 117 to 124 133 to 158
graph breaks / unique graphs 0 / 8 0 / 8
  • Median step time: -20%.
  • jobs/compare.py: NO_REGRESSION. The loss values differ step to step because GRPO loss is sampling dependent.
  • Peak memory is 1.77 / 1.73 GB.
  • The first repeat's first step includes the one-time Triton build of the two kernels. Later repeats with the compile cache kept are 49 / 42 s, against 49 to 56 s on main.

Numerics, Qwen3-0.6B 4-bit, greedy decode logits against a full no-cache forward of the same sequence:

main this PR
argmax agreement 0.977 0.992
mean abs logit diff 0.0593 0.0585
  • No non-finite logits on either side.
  • The fused rotation is within 2 ulp of the unfused one. Greedy token agreement between the two arms is sometimes well below 1 because of near-ties: one flip changes the rest of the sequence. Against the full forward, this PR agrees equally well or better in 10 of 12 Colab cells; in the other 2 (T4 Qwen3 4-bit, both torch versions) it is 0.998 vs 1.0.

Tests:

  • New tests/test_decode_fused_rope.py:
    • fused vs unfused Q and K over several shapes, bf16 / fp16, plain RoPE and Qwen3 q/k norm + RoPE;
      • within 2 ulp of the unfused path;
      • at least as close to an fp64 oracle;
    • fallbacks, each leaving the tensors untouched:
      • a float32 cos / sin table;
      • 3 tokens;
      • CPU tensors;
      • float32 norm weights;
    • the kill switch;
    • int32 positions sliced from a [bsz, seq] tensor (row stride kept): both kernels now get a contiguous copy. This case fails without it.
  • test_decode_fused_rope, test_rope_cache_current_device, test_qk_norm_rope, test_rope_kernel_layouts: 95 passed on torch 2.10 and 2.14.
  • Decode offset / compile RoPE tests (test_decode_offset_rope_model_loops, test_qwen3_decode_offset_rope, test_rms_rope_compile, test_rope_zero_stride_grad, test_longrope_short_long_boundary, test_rope_sync_single_device):
    • 75 passed on torch 2.10;
    • on torch 2.14 with transformers 4.57.6, 73 passed and the two test_rms_rope_compile tiny Llama fullgraph cases fail. They fail the same way on main.
  • The same five rope test files on Kaggle T4, torch 2.11.0 / 2.12.1 / 2.13.0: 62 passed, 12 skipped, 0 failed on each.
  • tests/: 935 passed and 3 failed on both main and this PR, with identical IDs. unsloth_zoo RL tests: 974 passed.

Not covered:

  • vLLM / fast_inference=True (it does not use this path);
  • Windows, macOS, ROCm, A100 / H100 (no GPU runners; the helpers return before any launch on non-CUDA tensors);
  • transformers 5.x decode;
  • the Cohere, Granite, Gemma2 and FalconH1 decode functions, which have their own RoPE code and are not changed here.

…th RoPE

Single-token decode in LlamaAttention_fast_forward_inference gathered cos / sin
per layer and rotated Q and K with rotate_half copies, neg, mul and addcmul,
about 12 launches per layer per token. Qwen3 added two eager per-head RMSNorms
(8 launches each). Decode with LoRA attached (GRPO rollouts without vLLM,
model.generate) is launch bound, so these dominate the host time per token.

Decode now calls the existing RoPE Triton kernel in place with the position
indices (llama path), or the existing fused q/k norm + RoPE forward kernel
(qwen3 path): one launch plus an index cast per layer. Kernels per decoded
token on Qwen3-0.6B + LoRA: 1934 -> 1206 (bf16), Llama-3.2-1B: 971 -> 811.
Falls back to the old code for anything the kernels do not cover (dtype
mismatch between Q, norm weight and the rope table, seq_len != 1, non-CUDA,
torch.compile tracing). UNSLOTH_DECODE_FUSED_ROPE=0 restores the old path.

Outputs agree with the unfused path to within 1 ulp, and the mean error
against an fp64 reference does not grow; decode logits stay as close or
closer to a full no-cache forward. Training code paths are unchanged.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 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 🔄 Running since 2026-10-22T04:29:49.495731Z 9a91ebd New commits
🔒 Security Review ⚠️ Failed 2026-10-22T03:34:16.725532Z
We couldn’t complete this review. Comment @codex security review to try again.
ce4b43a 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ce4b43ad43

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

Comment on lines +672 to +674
with torch_gpu_device(Q.device):
_rope_qk(Q, K, Q, K, cos2, sin2, rope_ptr, True, False, _eager_kernel)
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Synchronize fused RoPE before returning on split models

When inference uses a model dispatched across multiple GPUs, this returns immediately after the asynchronous Triton launch without calling _sync_if_split(Q). The other eager RoPE entry points explicitly drain the source-device stream before layer dispatch can move results to the next GPU; bypassing that safeguard can let split-model generation consume incompletely rotated Q/K tensors. Call _sync_if_split(Q) after the launch, while retaining the existing no-op behavior for single-device models.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 357931d: decode_rope_inplace now calls _sync_if_split(Q) after the launch, like the other eager entry points (a no-op on one device). test_decode_split_sync_and_mixed_devices checks the call.

Comment on lines +500 to +505
with torch_gpu_device(Q.device):
Qo, Ko, _, _ = _launch_forward(
Q, K, Wq.contiguous(), Wk.contiguous(), cos2, sin2, rope_indices,
float(_eps(q_norm)), float(_eps(k_norm)), True, _eager_kernel,
) # fmt: skip
return Qo.transpose(1, 2), Ko.transpose(1, 2)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Synchronize fused Q/K normalization on split models

For Qwen3 models split across GPUs, this new decode path omits the _sync_if_split(Q) call used by fast_qk_norm_rope after its eager Triton launch. The model-level decode loop subsequently transfers each layer's output to the next layer device, so the transfer can race the source-device normalization/RoPE work and produce corrupted generation. Synchronize after _launch_forward before returning the transposed outputs.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 357931d: decode_qk_norm_rope calls _sync_if_split(Q) after _launch_forward, matching fast_qk_norm_rope.

Comment thread unsloth/kernels/qk_norm_rope.py Outdated
Comment on lines +495 to +496
or Wq.device != Q.device
or cos2.device != Q.device

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject mixed-device inputs before launching the fused kernel

When Q is CUDA but K, Wk, or sin2 is on the CPU or another device, the current checks still accept the call because only Wq and cos2 are compared with Q.device. _launch_forward then runs under Q's CUDA device while passing foreign-device input and output pointers to Triton, raising a runtime pointer/device error instead of returning None as this guarded helper promises. Require K, both weights, and both tables to share Q's device before launching.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 357931d: Q, K, both norm weights and both tables must share a device (decode_rope_inplace now checks sin as well); otherwise the unfused path runs and nothing is written. Covered by test_decode_split_sync_and_mixed_devices, which fails before the change.

…ernel

The decoder passes the last column of [bsz, seq] positions. An int32 slice
keeps its row stride through reshape / to, and both kernels index positions
densely, so batch rows past the first were rotated at the wrong position.

[skip ci]
…ery operand on Q's device

Like the other eager RoPE entry points, both decode helpers now call
_sync_if_split(Q) after the Triton launch (a no-op on one device), so a
split model does not move a layer's output before the rotation finishes.
decode_qk_norm_rope now checks K, both norm weights and both tables
against Q's device, and decode_rope_inplace checks sin too; any mismatch
keeps the unfused path.

[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. You're on a roll.

Reviewed commit: 357931d106

ℹ️ 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 c5d885f into main Oct 22, 2026
@danielhanchen
danielhanchen deleted the grpo-decode-fused-rope branch October 22, 2026 05:01
Lyxot pushed a commit to NilayYadav/unsloth that referenced this pull request Oct 22, 2026
…lothai#14611)

unslothai#14599 (fused decode RoPE) calls `_sync_if_split(Q)` after its Triton
launch in `decode_rope_inplace` and `decode_qk_norm_rope`. On a model
split across GPUs (device_map), that blocks the host once per layer per
decoded token.

The drain is not needed there. Both helpers launch inside
`torch_gpu_device(Q.device)`, so the kernel runs on Q's device and its
current stream. The next layer's `.to(other_device)` is already ordered
after it: PyTorch's device-to-device copy synchronizes with the current
streams of both devices (`aten/src/ATen/native/cuda/Copy.cu`). The older
eager RoPE entry points keep their drains. Those were added in unslothai#3049 /
unslothai#3061 for launches made while another GPU was current, and this PR does
not touch them.

Measured on a random-weight 8-layer Llama (hidden 2048, fp16) split 4 +
4 over two B200s: batch 1, 32 new tokens, 4 interleaved repeats, median
generate time.

| decode RoPE path | median s | tokens/s |
|---|---|---|
| before unslothai#14599 | 0.442 | 72.4 |
| main (fused + drain) | 0.723 | 44.3 |
| fused, drain removed (this PR) | 0.444 | 72.0 |

All three arms produced the same tokens. With random weights that is
only a weak correctness check (the output is mostly one repeated token),
so this PR also adds a direct ordering test.

## Change
- Remove `_sync_if_split(Q)` from `decode_rope_inplace` and
`decode_qk_norm_rope`.
- Single-GPU behaviour is unchanged: the drain was a no-op there.

## Validation
- `test_decode_split_sync_and_mixed_devices` now asserts that the decode
helpers make no drain call.
- New `test_decode_rope_on_another_device_orders_with_the_copy`, which
needs two GPUs and skips on one:
  - rotates Q / K on GPU 1 while GPU 0 is current;
  - copies straight to GPU 0 with no host sync;
  - compares the result with the unfused rotation.
- `test_decode_fused_rope`, `test_qk_norm_rope`,
`test_rope_kernel_layouts`, `test_rope_sync_single_device`,
`test_qwen3_decode_offset_rope`, GPU-marked tests included: 414 passed,
1 skipped (the two-GPU test) on torch 2.14.1 and on torch 2.10.0.

Not covered: the two-GPU test was not run here (single-GPU leases). The
timing table comes from a two-GPU run of the same change outside this
PR's CI. ROCm split models were not tested.
danielhanchen added a commit that referenced this pull request Oct 22, 2026
…sed decode RoPE kernels (#14632)

`tests/utils/test_single_row_cached_attention.py` fails all 64 cases on
main, in the Core jobs' "generation correctness guards (HARD GATE)" step
(e.g. #14606, job 119685454271; reproduced on main `0ae76cc9f7`):

```
NameError: name 'decode_rope_inplace' is not defined
```

The test rebuilds `LlamaAttention_fast_forward_inference` and
`Qwen3Attention_fast_forward_inference` from source inside a
hand-written namespace. #14599 made them call the fused decode kernels
`decode_rope_inplace` (llama) and `decode_qk_norm_rope` (qwen3), which
that namespace did not have. The product is fine: both are imported in
the real modules.

## Change

- Both names are added with their CPU behaviour: the real functions
return `False` / `None` (nothing written) as soon as the tensors are not
on CUDA, and the unfused path runs. That is the path this test has
always exercised.
- The fixture now lists the decode function's free names and fails with
one clear message if any is not supplied, instead of a `NameError` in
every parametrized case the next time a dependency is added:

```
Qwen3Attention_fast_forward_inference now reads ['decode_qk_norm_rope']; give the harness a CPU stand-in for each
```

The test's rotary stub is the identity (cos 1, sin 0), so it checks
masking and the KV cache rather than RoPE. The fused kernels' own
correctness is covered by `tests/test_decode_fused_rope.py` on CUDA.

## Testing

- CPU torch 2.10: main 64 failed; this branch 64 passed.
- Removing the qwen3 stand-in fails the fixture with the message above.
danielhanchen added a commit that referenced this pull request Oct 25, 2026
…4714)

## What

The RoPE kernel loads `cos + rot_position * cos_row_stride` with an
int32 position. For a cos / sin table with more than 2**31 elements
(16.8M positions at head_dim 128, 4.2M at head_dim 512) the product
wraps negative and the load reads before the table. #14599 routes
single-token decode through this kernel, so decode at those positions
now hits it; the training path with explicit position ids already could.

This PR adds `cos` and `sin` to the tensors `long_indexing` checks and
widens the position to int64 when `LONG_INDEXING` is set.
`LONG_INDEXING` is a constexpr, so every table below 2**31 elements
compiles the exact same kernel as before.

## Evidence (B200, fp16, head_dim 128)

| position | offset | before | after |
|---|---|---|---|
| 1000 | 128000 | ok | ok |
| 16777214 | 2147483392 | ok | ok |
| 16777219 | 2147484032 | illegal memory access | matches the reference
|

No shipped model decodes that far today, so this is a bound fix, not a
hot path change.

## Tests

`tests/test_decode_fused_rope.py`: a meta-tensor check that a table past
int32 offsets takes 64-bit indexing, and a GPU test (marked `gpu`, skips
without about 9 GiB free) that decodes at position 2**31 / 128 + 3
against a reference. The GPU test crashes on main and passes here.
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