Repository navigation
GRPO PrefixGrouper: cover transformers-native Qwen3-MoE attention (opt-in) - #18616
Conversation
…t-in) Qwen3-MoE loads through FastModel with transformers' own attention, which drops prefix_seg_info, so both GRPO gates excluded every MoE config. A per-class wrapper now points the attention interface at the shared-prefix flex kernel for the call that carries the segment table (HF still computes q / k / v), and raises if the kernel was not reached so the caller falls back. The MoE block routes each token on its own, so deduplicating the shared prompt leaves routing unchanged. Opt-in with UNSLOTH_GRPO_PREFIX_GROUPER_MOE=1 until a step-time A/B shows a win. Stays off with routing replay (rows are matched by position resets) and with router logits in the loss. The wrapped model is marked _unsloth_prefix_grouper_moe_ok, and only that lifts the MoE exclusion in the no-grad gate.
…Grouper table The int segment table recompiled a compiled block at every new GRPO length. Only Unsloth's own decoder layers were exempt; transformers-native layers now carry the table too (Qwen3-MoE via prefix_grouper_hf), and on L4 each new prompt length cost about 4.7 s. Also loosen the CUDA leak test to rounding noise (expert GEMM shapes follow the routed token counts).
|
@codex review |
Codex Review Summary: ✅ CompletedThis 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. Keep them coming! 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". |
[skip ci]
Run the flex kernel and the patched router eager on CPU (Inductor C++ builds dominated the file), and shrink the model to 2 layers and 4 experts. Assertions and tolerances are unchanged. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
…, opt-in small tiles (unslothai#18645) ## Summary On a T4 (sm75, 64 KB shared memory), the GRPO PrefixGrouper FlexAttention kernel cannot compile. The 16-bit 128 / 64 tile needs 98304 B at head_dim 128, and the one-stage retry needs the same amount. Today the compile check spends about 3 minutes failing, twice, at the first training step. It then switches PrefixGrouper off. This PR does two things, both inside the compile-options and compile-check code in `unsloth/utils/prefix_grouper_kernel.py`: 1. **Skip the failing compile.** The skip applies on NVIDIA GPUs below 96 KB of shared memory, for fp16 / bf16 at head_dim >= 128 when the user has not opted in. The check is skipped up front and PrefixGrouper reports itself off with a clear reason. The result is the same as today (the packed path), minus about 185 s of startup per run on T4. 2. **Opt-in small tiles.** `UNSLOTH_GRPO_PREFIX_GROUPER_SMALL_SMEM=1` pins forward and backward tiles that fit 64 KB. The tiles are chosen from the device's queried shared memory limit (Triton `max_shared_mem`, falling back to the torch device properties), never from the GPU name. The settings are forward 32 / 32 with 1 stage and 4 warps, and backward 32 / 32 / 32 / 32 with 1 stage and 8 warps. Every key is pass-prefixed (`fwd_*`, `bwd_*`), so nothing leaks between passes. That gives one compiled variant per call site, and the one-stage retry adds no second one. GPUs with 96 KB or more shared memory (sm80+, sm86 / sm89 / sm120, V100) keep exactly the same `kernel_options` as before. ROCm keeps today's behaviour; the opt-in tiles are available there for testing. ## Why the small tiles are not the default on T4 Triton 3.8 emits no tensor-core MMA on sm75. A plain `tl.dot` in fp16 compiles to 0 `mma.sync` and 256 `fma.rn.f32`, and the flex kernels compile the same way. Attention therefore runs on CUDA cores: - Isolated kernel test (Qwen3 attention shape, prompt 512 + 8 x 128): flex forward + backward takes about 46 ms, against 9-11 ms for the unshared SDPA rows. - The shared forward wins on larger models, but the flex backward loses that time again. | T4, fp16, GRPO, 768-token prompt, 8 x 128 completions | PG off (A/A, 3 runs) | opt-in small tiles (3 runs) | delta | |---|---|---|---| | Qwen3-0.6B step time (s), run 1 | 4.939 / 4.964 / 4.968 | 6.908 / 6.935 / 7.025 | +39.7% (slower) | | Qwen3-1.7B step time (s), run 1 | 10.214 / 10.279 / 10.290 | 9.982 / 9.992 / 10.022 | -2.8% | | Qwen3-1.7B step time (s), run 2 (other VM) | 11.136 / 11.190 / 11.294 | 10.734 / 10.738 / 10.805 | -4.0% | On 1.7B the logps phase drops from 1.30 to 0.87 s and the compute_loss forward from 1.50 to 0.96 s, with peak memory going from 4.56 to 4.43 GB. Most of that is lost again in the backward. Default path, Qwen3-0.6B, base vs head without the opt-in: - **Steady state:** 5.56 / 5.67 s for base and 5.56 / 5.60 / 5.61 s for head, against a PG-off A/A of 5.47 / 5.58 / 5.67 s. All of these are inside the A/A spread. - **Wall time per run:** 292 s for base and 107 s for head. ## Correctness on T4 (opt-in path) The check uses real Qwen3 FastLanguageModel with LoRA. It compares the PrefixGrouper stream against unshared per-row log-probs and LoRA grads, and the flex kernel was called 56 times. | | fp32 PG vs per-row | fp16 PG vs fp32 per-row | fp16 per-row vs fp32 per-row | |---|---|---|---| | 0.6B max abs dlogp | 3.2e-5 | 0.024 | 0.014 | | 0.6B total rel grad | 6.4e-6 | 5.2e-3 | 5.1e-3 | | 1.7B max abs dlogp | 2.5e-5 | 0.022 | 0.028 | | 1.7B total rel grad | 7.1e-6 | 5.0e-3 | 4.5e-3 | So the fp16 PrefixGrouper error is at the level of fp16 rounding of the unshared path. ## Interaction with unslothai#18614 / unslothai#18616 The branch is rebased on current main, which includes both PRs. The change touches only the tile selection, the small-smem skip and a shared failure helper, so it merges without conflicts. The AsyncGRPO tree mask (`TreeSegInfo`) and the Qwen3-MoE opt-in go through the same `_run_flex` and `_checked_first_call`. On T4 they therefore get the same up-front skip, and the same tiles under the opt-in. ## Tests `tests/test_prefix_grouper_small_smem.py` covers the following: - Options are unchanged for 96 KB and larger limits, with and without the opt-in. - The opt-in tiles are fully pass-prefixed and satisfy the template static asserts. - There is one variant only. - The skip fires only for NVIDIA, 16-bit, head_dim >= 128, with no opt-in. - The limit is queried once per device, with the torch-properties fallback. - `_run_flex` passes the device options. - On T4 the compile check runs no strict compile. On main, 25 of the 27 tests fail. The two that pass assert the unchanged default.
Summary
GRPO PrefixGrouper (shared-prompt dedup: one forward over
[prompt, c_0 .. c_{G-1}]instead of G full rows) never engaged on MoE models. Both GRPO gates excluded every config withnum_experts/moe_intermediate_size, because Qwen3-MoE loads through FastModel with transformers' own attention, which dropsprefix_seg_infoand would leak completions into each other (9.05 nats on a tiny Qwen3-MoE when forced on main).This PR adds an opt-in path for Qwen3-MoE:
unsloth/utils/prefix_grouper_hf.py(new): a per-class wrapper onQwen3MoeAttention.forward. On a call that carries a segment table, it points the attention-interface lookup at the existing shared-prefix flex kernel for that one call, so transformers still computes q / k / v (projections, q/k norm, RoPE). If the kernel was not reached, it raises and the caller falls back to the packed path. Calls without a table run the original forward unchanged, bit for bit.prefix_seg_info_applied(model): when no hand-written forward is marked, it asks the wrapper. Every decoder layer must qualify. A qualifying MoE model is marked_unsloth_prefix_grouper_moe_ok.No-grad gate (
unsloth/models/rl_replacements.py): the MoE exclusion is lifted only for models with that mark.unsloth-zoo (companion PR GRPO PrefixGrouper: pass the model to the grad-path gate, allow verified MoE unsloth-zoo#2631): the grad-path gate passes the model to
prefix_grouper_enabled(model), falling back to the old no-argument form on older unsloth. Its MoE exclusion is lifted the same way.unsloth/models/_block_compile.py: a compiled decoder block now keeps the stock forward for any layer carrying a PrefixGrouper table, not only Unsloth's own layers. The int segment table otherwise recompiled the block at every new prompt length, which cost about 4.7 s per step on L4 and made the first A/B 2x slower.The MoE block routes each token on its own, so sending the shared prompt through once leaves every token's routing unchanged. Each expert also receives the same set of distinct tokens as before, so no expert's grad changes from zero to None.
Opt-in with
UNSLOTH_GRPO_PREFIX_GROUPER_MOE=1. It stays off withUNSLOTH_GRPO_ROUTING_REPLAY=1, because replay matches rows byposition_idsresets and the shared stream has none per completion. It also stays off whenoutput_router_logitsputs the router aux loss into the loss.Correctness
CPU, fp32, tiny Qwen3-MoE (3 layers, 8 experts top-2, GQA),
tests/test_prefix_grouper_qwen3_moe.py, torch 2.15 / transformers 5.23 and torch 2.12 / transformers 4.57.6: 9 passed on both stacks.Flip, same tiny model with PrefixGrouper forced: main gives 9.05 nats, this PR 1.0e-5. New block-compile test fails on main and passes here.
Existing PrefixGrouper / DPO prefix-share suites: 94 passed, 2 skipped on both base and head. zoo PrefixGrouper / zero-advantage suites: 492 passed on both.
Colab L4, torch 2.14.1 / transformers 5.18 / TRL 1.15, real kernel:
Speed (Colab L4, GRPO)
Setup: random-weight Qwen3-MoE with Qwen3-30B-A3B layer dims (128 experts top-8, 6 layers, 4.4B params), bf16 LoRA r16, no vLLM, G=8, prompts of 512-529 tokens, 128-token completions forced to full length, 10 steps, median of steps 4-10. Fresh process per run, interleaved. Base = merge base (unsloth cf3eb59, zoo a515275).
UNSLOTH_GRPO_PREFIX_GROUPER_MOE=1Step time -25.6% (A/A spread 0.85%), peak memory -0.6 GB. The same setup on A100-40: base 1.322 s/step (A/A spread 0.5%), head 1.150 s/step (-13.0%), no-opt-in 1.322. On T4 the flex kernel does not compile at head_dim 128 (shared memory limit), so the existing compile check turns PrefixGrouper off and step time matches base (60.3 s). Per phase, base vs head: logprob forward 0.216 vs 0.064 s, loss forward+backward 0.266 vs 0.104 s, generation unchanged (2.47 s). Without the opt-in, head matches base.
Not covered