Skip to content

GRPO PrefixGrouper: cover transformers-native Qwen3-MoE attention (opt-in) - #18616

Merged
danielhanchen merged 4 commits into
mainfrom
cg5-prefix-grouper-moe
Nov 20, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
cg5-prefix-grouper-moe

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

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 with num_experts / moe_intermediate_size, because Qwen3-MoE loads through FastModel with transformers' own attention, which drops prefix_seg_info and 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 on Qwen3MoeAttention.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 with UNSLOTH_GRPO_ROUTING_REPLAY=1, because replay matches rows by position_ids resets and the shared stream has none per completion. It also stays off when output_router_logits puts 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.

    • Per-completion logps vs unshared rows: max 4.8e-6 nats (sdpa) and 7.6e-6 (eager).
    • Changing one completion moves no other completion by a single ulp.
    • Param grads, router and experts included: rel-L2 1.9e-6. On CPU, flex has no backward, so this test swaps the kernel for a dense-mask SDPA reference built only from the group specs.
  • 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:

    • Same pytest: 9 passed. fp32 logps 9.1e-6 nats, grads rel-L2 3.9e-6.
    • Unsloth FastModel + LoRA on a tiny Qwen3-MoE (head_dim 128, 16 experts top-4, gradient checkpointing), PrefixGrouper vs per-row: fp32 logps 1.9e-6, total LoRA grad rel-L2 7.1e-5 (48 grads, 16 on experts), kernel reached on every layer. bf16: 0.11 / 3.0e-2. The fp32 match shows the math is exact, so the bf16 gap is rounding.

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).

Arm runs (median s/step) median spread kernel calls peak alloc
base (A/A) 3.749 / 3.766 / 3.781 3.766 0.85% 0 9.86 GB
head, UNSLOTH_GRPO_PREFIX_GROUPER_MOE=1 2.801 / 2.798 / 2.814 2.801 0.6% 186 per run 9.26 GB
head, no opt-in 3.777 0 9.86 GB

Step 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

  • Real Qwen3-30B-A3B weights, 4-bit QLoRA, and AMD were not run. The feature stays opt-in until they are.
  • Qwen3-Next / Qwen3.5 (Gated DeltaNet): the recurrence and conv1d run across the flat stream, so each completion needs its own initial state from the prefix (tree recurrence). Not wrapped.
  • gpt-oss: its attention is replaced by Unsloth's own sink forward rather than the attention interface, and half its layers use a 128-token sliding window, which caps the PrefixGrouper span. A kernel LSE return would not unblock it on its own.

…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).
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T12:33:02.803693Z 2eef3d1 Manual request
ℹ️ 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. Keep them coming!

Reviewed commit: c7cc358884

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

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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 2eef3d126e

ℹ️ 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 ab2736d into main Nov 20, 2026
@danielhanchen
danielhanchen deleted the cg5-prefix-grouper-moe branch November 20, 2026 13:46
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Nov 20, 2026
…, 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.
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