Repository navigation
Fast decode: rotate Q and K in one launch, and fuse Qwen3 q/k norm with RoPE - #14599
Conversation
…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.
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 |
There was a problem hiding this comment.
💡 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".
| with torch_gpu_device(Q.device): | ||
| _rope_qk(Q, K, Q, K, cos2, sin2, rope_ptr, True, False, _eager_kernel) | ||
| return True |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Fixed in 357931d: decode_qk_norm_rope calls _sync_if_split(Q) after _launch_forward, matching fast_qk_norm_rope.
| or Wq.device != Q.device | ||
| or cos2.device != Q.device |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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]
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
…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.
…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.
…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.
In Unsloth's fast decode path (
LlamaAttention_fast_forward_inferenceand the Qwen3 decode attention), each layer rotates Q and K for the single new token in eager ops. The path:rotate_halfcopies;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_qkTriton 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 fusedfast_qk_norm_ropekernel.torch.compileis tracing;UNSLOTH_DECODE_FUSED_ROPE=0restores the previous path.Validation
In-process A/B with the kill switch toggled per rep, arms interleaved, 6 reps:
generatewall time, 128 new tokens.End to end, a full GRPO job on B200, torch 2.14:
jobs/compare.py: NO_REGRESSION. The loss values differ step to step because GRPO loss is sampling dependent.Numerics, Qwen3-0.6B 4-bit, greedy decode logits against a full no-cache forward of the same sequence:
Tests:
tests/test_decode_fused_rope.py: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.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):test_rms_rope_compiletiny Llama fullgraph cases fail. They fail the same way on main.tests/: 935 passed and 3 failed on both main and this PR, with identical IDs. unsloth_zoo RL tests: 974 passed.Not covered:
fast_inference=True(it does not use this path);