Repository navigation
Add vLLM paged QSA attention and graph metadata - #6443
Open
liangel-02 wants to merge 1 commit into
Open
liangel-02 wants to merge 1 commit into
liangel-02 wants to merge 1 commit into
Conversation
liangel-02
requested review from
acisseJZhong,
fegin,
felipemello1,
shuhuayu,
tianyu-l and
wwwjn
as code owners
November 30, 2026 16:23
wwwjn
approved these changes
Nov 30, 2026
wwwjn
left a comment
Contributor
There was a problem hiding this comment.
Reopen because of #6201 (comment) wrongly merged base
This is the same PR as #6201
liangel-02
added a commit
that referenced
this pull request
Nov 30, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
this approach, and what you checked yourself. -->
## Why
`TokenChoiceTopKRouter` (`torchtitan/models/common/moe/moe.py`) is the stock MoE
router: a gate GEMM scores every expert for each token, then a softmax, top-k,
gather, optional renormalization and scale produce each token's experts and
weights, plus a routing map. It is the router of Qwen3 MoE, GPT-OSS,
Qwen3.5/3.6/3.8 and Flash-Next.
In generation, decode steps are tiny (about 16 tokens per rank), so everything
after the gate GEMM is launch- and latency-bound: PyTorch runs it as about 12
small kernels per MoE layer. On Qwen3.8-Flash-Next (512 experts, top-10, 48 MoE
layers) that chain takes about 21 us per layer, about 1 ms of every decode step,
for almost no arithmetic.
**Example.** One MoE layer, one decode step (16 tokens per rank, 512 experts,
top-10):
```
before: gate GEMM -> softmax -> topk -> gather -> sum -> add -> div -> mul
-> memset + scatter (routing map) ... ~12 kernels, ~21 us
after: gate GEMM -> _softmax_topk_kernel 1 kernel, ~4.3 us
(same scores, expert IDs in the same order and routing map, bitwise)
```
## What changed
- `FusedSoftmaxTopKRouter` (`torchtitan/rl/generator/moe_router.py`), a
`TokenChoiceTopKRouter` subclass: the gate GEMM is unchanged; one Triton
kernel computes the softmax, top-k, gather, renormalization, scale and routing
map. Its outputs equal the stock router's bitwise: it reproduces PyTorch's
CUDA softmax and sum reduction orders and `torch.topk(sorted=False)`'s output
order.
- `_replace_vllm_layer_configs` swaps it in, as it already does for the QSA,
GDN, KDA and PLE generation layers, only for routers that are exactly
`TokenChoiceTopKRouter` with a softmax score. Kept as is:
- router subclasses (DeepSeek V3/V4, round-robin, quantile-balanced) and
non-softmax (e.g. sigmoid) scores;
- batch-invariant mode, which overrides `aten::sum`, so the stock router there
computes different numbers than the default order this kernel reproduces;
- non-CUDA accelerators and ROCm, whose reduction orders differ
(`device_type == "cuda"` and `torch.version.hip is None`, checked in the
swap and again in `FusedSoftmaxTopKRouter.Config.__post_init__`).
- Training never uses `FusedSoftmaxTopKRouter`; trainer numerics are unchanged.
Batch invariance: each Triton program handles a tile of token rows, and every
reduction runs along one row's expert axis in an order fixed by E and K. A
token's routing depends only on its own gate logits, not on the batch size,
padding or the other rows.
Router consumers audited: `MoE.forward`, `KimiK3MoE.forward` and
`MuseSparkMoE.forward` pass the router outputs on unchanged. The local and
all-to-all token dispatchers read the routing map and still get it; DeepEP,
HybridEP and Dist-MoE ignore it.
## Alternatives considered
- A `local_compile` region over the same chain: 9.8 us per layer (vs 4.3 us),
and not bitwise (Inductor's softmax, 10-element sum and fp32 division round
differently), so it could pick different experts on near-ties than the
trainer.
- vLLM's fused `topk_softmax` op: not written to reproduce ATen's softmax
and top-k orders, so its outputs are not guaranteed to match the trainer's
router bitwise (not tested).
- Moving routing into Dist-MoE: out of scope there; Dist-MoE takes top-k
expert IDs and scores from the caller and keeps routers out of its API.
## User-facing changes
| Before | After |
| --- | --- |
| Generator MoE layers run the stock router's eager chain | Generator MoE layers with a softmax `TokenChoiceTopKRouter` run one fused kernel; outputs bitwise equal |
| Training | Unchanged |
No config fields or flags; the swap is automatic and limited to the cases above.
## Numerics
- Router outputs (scores, expert IDs in order, routing map) are bitwise equal to
the stock router on 5 (E, K) shapes x 4 input kinds (normal, ties, underflow,
NaN/inf) x 3 configs (route_norm on/off, route_scale, expert bias).
- Full Flash-Next model, seeded generation with FULL CUDA graphs: decode tokens
and logprobs are bitwise identical before and after on 88/88 requests, with
the shared-expert side-stream overlap both off and on.
## Performance
Qwen3.8-Flash-Next, 48 layers, real weights, DP4/EP4 on 4 GB300, 64 sequences at
~2.1k context, FULL CUDA graphs, with the Dist-MoE decode-routing stack:
| | Before | After |
| --- | --- | --- |
| Router per layer (microbench, T=16) | ~21.2 us | 4.3 us |
| Decode step | 16.43 ms | 15.06 ms (-8.3%) |
| Arrival steps (new prompts join) | 36.4-37.9 ms | 34.2-35.9 ms |
| Kernels per decode replay | 3732 | 3204 |
The full-model rows also include a separate change that fuses Dist-MoE's two
padding `masked_fill`s (about 0.14 ms per step, not in this PR); this PR alone
accounts for about 1.2 ms of the 1.37 ms. They were measured on the Flash-Next
generation stack this PR sits on (#6443, #6202, #6203, #6308) with the
Dist-MoE decode-routing stack.
## Testing
```bash
pytest -q tests/rl/unit_tests/gpu/test_moe_router.py # 20 passed, GB300
pytest -q tests/rl/unit_tests/cpu/test_vllm_wrapper.py
```
- `test_moe_router.py` (new): bitwise equality with the stock router across the
shapes, inputs and configs above. Catches a fused kernel whose outputs drift
from the stock router, including a PyTorch update that changes the ATen
softmax, sum or `torch.topk` orders the kernel reproduces.
- `test_vllm_wrapper.py` (extended): which routers the generator swaps. The
Qwen3 MoE debug flavor's softmax `TokenChoiceTopKRouter` is swapped; the
same model in batch-invariant mode, and with its routers converted to
`RoundRobinTokenChoiceTopKRouter` (a softmax subclass that selects experts
its own way), keeps the stock router. Catches the swap reaching routers whose
numerics it does not reproduce, e.g. a type check loosened to `isinstance`.
- Locally, `test_vllm_replacement_preserves_attention_sharding[kda]` in
`test_vllm_wrapper.py` fails to import `copy_replay_tails` from the installed
Attention Gym; that is an environment issue unrelated to this change.
## Known issues / follow-ups
- The kernel reproduces ATen's internal softmax, sum and top-k orders, which a
PyTorch update can change; `test_moe_router.py` fails if it does.
## Self-review
pr-review (branch mode) at f416c5763: needs discussion. Fixed after it: the
swap and `__post_init__` now also require `device_type == "cuda"` (XPU no
longer gets the kernel); the subclass test case uses a real softmax router
subclass (it used DeepSeek V3, rejected for its sigmoid score instead);
`_softmax_topk` is inlined into its only caller; the `_MAX_TOP_K` comment
states why the cap is 32. Not addressed:
- Whether torchtitan should host a hand-written Triton kernel that copies ATen
internals -- a maintainer question; it is generator-only, and the GPU test
fails if a PyTorch update changes the orders it depends on.
- Eligibility checks live in both the swap and `__post_init__`; a softmax
router beyond 2048 experts or top-32 would now raise at generator startup
instead of keeping the stock router (no in-repo flavor is close: max E=512,
K=10).
liangel-02
added a commit
that referenced
this pull request
Nov 30, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
this approach, and what you checked yourself. -->
## Why
`TokenChoiceTopKRouter` (`torchtitan/models/common/moe/moe.py`) is the stock MoE
router: a gate GEMM scores every expert for each token, then a softmax, top-k,
gather, optional renormalization and scale produce each token's experts and
weights, plus a routing map. It is the router of Qwen3 MoE, GPT-OSS,
Qwen3.5/3.6/3.8 and Flash-Next.
In generation, decode steps are tiny (about 16 tokens per rank), so everything
after the gate GEMM is launch- and latency-bound: PyTorch runs it as about 12
small kernels per MoE layer. On Qwen3.8-Flash-Next (512 experts, top-10, 48 MoE
layers) that chain takes about 19 us per layer, about 0.9 ms of every decode step,
for almost no arithmetic.
**Example.** One MoE layer, one decode step (16 tokens per rank, 512 experts,
top-10):
```
before: gate GEMM -> softmax -> topk -> gather -> sum -> add -> div -> mul
-> memset + scatter (routing map) ... ~12 kernels, ~19 us
after: gate GEMM -> _softmax_topk_kernel 1 kernel, ~4.7 us
(same scores, expert IDs in the same order and routing map, bitwise)
```
## What changed
- `FusedSoftmaxTopKRouter` (`torchtitan/rl/generator/moe_router.py`), a
`TokenChoiceTopKRouter` subclass: the gate GEMM is unchanged; one Triton
kernel computes the softmax, top-k, gather, renormalization, scale and routing
map. Its outputs equal the stock router's bitwise: it reproduces PyTorch's
CUDA softmax and sum reduction orders and `torch.topk(sorted=False)`'s output
order.
- `_replace_vllm_layer_configs` swaps it in, as it already does for the QSA,
GDN, KDA and PLE generation layers, only for routers that are exactly
`TokenChoiceTopKRouter` with a softmax score. Kept as is:
- router subclasses (DeepSeek V3/V4, round-robin, quantile-balanced) and
non-softmax (e.g. sigmoid) scores;
- batch-invariant mode, which overrides `aten::sum`, so the stock router there
computes different numbers than the default order this kernel reproduces;
- non-CUDA accelerators and ROCm, whose reduction orders differ
(`device_type == "cuda"` and `torch.version.hip is None`, checked in the
swap and again in `FusedSoftmaxTopKRouter.Config.__post_init__`).
- Training never uses `FusedSoftmaxTopKRouter`; trainer numerics are unchanged.
How the kernel works (one launch per router call; each program owns a tile of
1 token row, or 4 above 1024 tokens):
1. Softmax over the E expert logits with 32 lanes per row, in the order of
PyTorch's warp-per-row softmax (per-lane partial max/sum, then an XOR
butterfly), which ATen uses for rows of up to 2048 FP32 elements.
2. Top-k by K rounds of row argmax (ties to the lower expert ID), adding the
expert bias to the selection score only, as the stock router does.
3. The routing map is the set of experts picked in step 2.
4. The K picks are reordered into `torch.topk(sorted=False)`'s output order,
renormalized with a halving tree sum that matches Reduce.cuh's K-element
warp reduction, and scaled. The kernel compiles with
`enable_fp_fusion=False` so no multiply-add fusion changes rounding.
Batch invariance: each Triton program handles a tile of token rows, and every
reduction runs along one row's expert axis in an order fixed by E and K. A
token's routing depends only on its own gate logits, not on the batch size,
padding or the other rows.
Router consumers audited: `MoE.forward`, `KimiK3MoE.forward` and
`MuseSparkMoE.forward` pass the router outputs on unchanged. The local and
all-to-all token dispatchers read the routing map and still get it; DeepEP,
HybridEP and Dist-MoE ignore it.
## Alternatives considered
- A `local_compile` region over the same chain: 9.8 us per layer after the gate
(vs 4.3 us for this kernel, measured in the same earlier run),
and not bitwise (Inductor's softmax, 10-element sum and fp32 division round
differently), so it could pick different experts on near-ties than the
trainer.
- vLLM's fused `topk_softmax` op: not written to reproduce ATen's softmax
and top-k orders, so its outputs are not guaranteed to match the trainer's
router bitwise (not tested).
- Moving routing into Dist-MoE: out of scope there; Dist-MoE takes top-k
expert IDs and scores from the caller and keeps routers out of its API.
## User-facing changes
| Before | After |
| --- | --- |
| Generator MoE layers run the stock router's eager chain | Generator MoE layers with a softmax `TokenChoiceTopKRouter` run one fused kernel; outputs bitwise equal |
| Training | Unchanged |
No config fields or flags; the swap is automatic and limited to the cases above.
## Numerics
- Router outputs (scores, expert IDs in order, routing map) are bitwise equal to
the stock router on 5 (E, K) shapes x 4 input kinds (normal, ties, underflow,
NaN/inf) x 3 configs (route_norm on/off, route_scale, expert bias).
- Full Flash-Next model, seeded generation with FULL CUDA graphs: decode tokens
and logprobs are bitwise identical before and after on 88/88 requests, with
the shared-expert side-stream overlap both off and on.
## Performance
**Router microbenchmark.** Flash-Next's router config (hidden 2560, E=512,
K=10, route_norm, BF16 input), one GB300. Each number is the average per call
of 48 back-to-back router calls captured in one CUDA graph (one call per MoE
layer), 50 replays. "After gate" subtracts the gate GEMM alone, which both
routers run unchanged.
| Tokens | Stock router | Fused router | After gate: stock -> fused | Speedup | Saved per 48 layers |
| ---: | ---: | ---: | ---: | ---: | ---: |
| 1 | 22.6 us | 8.5 us | 18.6 -> 4.5 us | 2.6x | 0.68 ms |
| 16 (decode, per rank) | 23.0 us | 8.8 us | 18.9 -> 4.7 us | 2.6x | 0.68 ms |
| 64 | 26.9 us | 9.0 us | 22.4 -> 4.5 us | 3.0x | 0.86 ms |
| 128 | 30.2 us | 8.8 us | 26.1 -> 4.8 us | 3.4x | 1.03 ms |
| 512 | 40.6 us | 10.8 us | 36.6 -> 6.9 us | 3.8x | 1.43 ms |
| 2048 (prefill chunk) | 78.2 us | 19.9 us | 72.0 -> 13.7 us | 3.9x | 2.80 ms |
| 8192 (largest prefill step) | 208.9 us | 56.1 us | 193.4 -> 40.7 us | 3.7x | 7.33 ms |
At decode sizes the stock chain is launch-bound (flat ~19 us after the gate);
at prefill sizes its extra passes over the (T, E) scores dominate, so prefill
and mixed prefill+decode steps also gain.
**End to end.** Qwen3.8-Flash-Next, 48 layers, real weights, DP4/EP4 on 4 GB300,
64 sequences at ~2.1k context, FULL CUDA graphs, with the Dist-MoE
decode-routing stack:
| | Before | After |
| --- | --- | --- |
| Decode step | 16.43 ms | 15.06 ms (-8.3%) |
| Arrival steps (new prompts join) | 36.4-37.9 ms | 34.2-35.9 ms |
| Kernels per decode replay | 3732 | 3204 |
The full-model rows also include a separate change that fuses Dist-MoE's two
padding `masked_fill`s (about 0.14 ms per step, not in this PR); this PR alone
accounts for about 1.2 ms of the 1.37 ms. They were measured on the Flash-Next
generation stack this PR sits on (#6443, #6202, #6203, #6308) with the
Dist-MoE decode-routing stack.
## Testing
```bash
pytest -q tests/rl/unit_tests/gpu/test_moe_router.py # 20 passed, GB300
pytest -q tests/rl/unit_tests/cpu/test_vllm_wrapper.py
```
The microbenchmark script is not part of this PR (it builds the Flash-Next
125B-A6B router config and times both routers as described above).
- `test_moe_router.py` (new): bitwise equality with the stock router across the
shapes, inputs and configs above. Catches a fused kernel whose outputs drift
from the stock router, including a PyTorch update that changes the ATen
softmax, sum or `torch.topk` orders the kernel reproduces.
- `test_vllm_wrapper.py` (extended): which routers the generator swaps. The
Qwen3 MoE debug flavor's softmax `TokenChoiceTopKRouter` is swapped; the
same model in batch-invariant mode, and with its routers converted to
`RoundRobinTokenChoiceTopKRouter` (a softmax subclass that selects experts
its own way), keeps the stock router. Catches the swap reaching routers whose
numerics it does not reproduce, e.g. a type check loosened to `isinstance`.
- Locally, `test_vllm_replacement_preserves_attention_sharding[kda]` in
`test_vllm_wrapper.py` fails to import `copy_replay_tails` from the installed
Attention Gym; that is an environment issue unrelated to this change.
## Known issues / follow-ups
- The kernel reproduces ATen's internal softmax, sum and top-k orders, which a
PyTorch update can change; `test_moe_router.py` fails if it does.
## Self-review
pr-review (branch mode) at f416c5763: needs discussion. Fixed after it: the
swap and `__post_init__` now also require `device_type == "cuda"` (XPU no
longer gets the kernel); the subclass test case uses a real softmax router
subclass (it used DeepSeek V3, rejected for its sigmoid score instead);
`_softmax_topk` is inlined into its only caller; the `_MAX_TOP_K` comment
states why the cap is 32. Not addressed:
- Whether torchtitan should host a hand-written Triton kernel that copies ATen
internals -- a maintainer question; it is generator-only, and the GPU test
fails if a PyTorch update changes the orders it depends on.
- Eligibility checks live in both the swap and `__post_init__`; a softmax
router beyond 2048 experts or top-32 would now raise at generator startup
instead of keeping the stock router (no in-repo flavor is close: max E=512,
K=10).
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
this approach, and what you checked yourself. -->
## Why
The Flash-Next training model selects complete four-token blocks plus the current
incomplete tail. Generation needs to read those selections from vLLM's physical
KV pages across appends, request reordering, and graph padding. The existing
vLLM replacement does not implement that QSA cache contract.
For a request with 11 tokens selecting block 0, attention must read token
positions `[0, 1, 2, 3, 8, 9, 10]`, even if its logical pages have moved.
## What changed
- Add a parameter-free vLLM page owner calling Attention Gym `paged_sparse_decode`.
- Add `QSAPagedMetadataBuilder`, which builds decode metadata as views of vLLM's
persistent runner buffers. vLLM already pads them for `FULL_DECODE_ONLY` graphs
(zero lengths, null pages, `-1` slots), so replay reads each step's request
layout without extra copies. It only uses vLLM's generic backend and
`CommonAttentionMetadata` contracts, like `TorchTitanLinearAttentionMetadataBuilder`.
- Preserve request-local addressing, incomplete causal tails, and inactive rows.
- Reject unsupported cache dtypes, speculative decoding, decode CP, and graph modes.
- Every step calls Attention Gym's `paged_sparse_decode` once with vLLM's
per-request block table, `query_start_loc` and `seq_lens`, and no host
query-length bound (meta-pytorch/attention-gym#1032): each packed row finds
its request on the device, so decode-only and mixed prompt+decode steps use
the same call, and no step gathers a prompt's context or needs host token
counts.
QSA attention per layer, GB300, 24/2 heads, top-512 blocks, CUDA graph replay:
| Step | `paged_sparse_decode` |
| --- | --- |
| 64 decode at 2K context | 55.4 us |
| 64 decode at 16K context | 55.8 us |
| 16 decode + 2 x 137 | 55.8 us |
| 64 decode + 8 x 210 | 144.1 us |
| 64 decode + 8 x 1000 | 995.9 us |
| 2 x 4096 | 2474.5 us |
Each prompt row is its own program and loads its selected K/V, so long prompt
chunks cost more per row than decode; short-prompt RL steps are dominated by
decode rows.
- Bump the Attention Gym pin from 755691f to 8d156fd (current main), which has
`paged_sparse_decode` without a host query-length bound (#1032) and the paged
lightning indexer (#959, #960) used by the next commit. The bump also brings
Attention Gym's Warpdrive GDN/KDA chunk kernels as the default on SM100-family
GPUs (#907, #912), which changes GDN/KDA numerics on B200/GB300 for every
model that uses them.
- Add `torchtitan/rl/generator/local_compile.py` with two shared
`local_compile` region names for generator-only functions,
`INFERENCE_BATCH_INVARIANT_REGION` and `INFERENCE_BATCH_VARIANT_REGION`;
`inference_local_compile(batch_invariant=...)`, which registers a function
under the matching one; and `inference_regions()`, which returns the regions
that have registered functions (leaving out the batch-variant one in
batch-invariant mode), so a generator can enable them without knowing which
layers registered functions. Core `torchtitan/distributed/local_compile.py`
is unchanged. QSA's padding-row helper registers under the batch-invariant
region; the generator enables the regions in #6202.
- The common Attention Gym export additions are mechanical import plumbing.
vLLM remains responsible for allocation and reclamation; Python-owned request
caches would duplicate that ownership.
## User-facing changes
| Before | After |
| --- | --- |
| No paged QSA attention adapter | Sparse block IDs read directly from vLLM KV pages |
| No QSA graph metadata | `FULL_DECODE_ONLY` decode replays QSA attention |
## Testing
`pytest -q tests/rl/unit_tests/gpu/test_vllm_qsa.py`
The attention test checks reordered physical pages against an independent sparse
causal reference, including incomplete tails and padding. The graph test refreshes
persistent metadata buffers in place with vLLM's padding, as vLLM's runner does,
and checks replay after changing page tables, lengths, and live request counts.
Full Flash-Next generation additionally needs the indexer and PLE changes in the
next two commits.
## Validation scope
This commit alone is covered by `tests/rl/unit_tests/gpu/test_vllm_qsa.py`; the
training-loss and generation checks below cover the whole stack.
Validation scope: at the new pin (8d156fd), on GB300, `test_vllm_qsa.py`,
`test_vllm_ple.py`, `test_moe_router.py` and `test_vllm_wrapper.py` pass for the
whole stack (47 tests). The training and generation checks below were run on
local B200 GPUs before the pin bump, with an Attention Gym development build that
had the paged sparse APIs.
The complete stack passed `pre-commit run --all-files`. A deterministic seed-42
BF16 debug-model forward/backward (32 tokens) was compared against
`44ff1567196fe91ba8a8f96a1aeefbc6715dda8c`: loss `4.4367218017578125`, gradient
norm `22.315799713134766`, logits, and all 192 parameter gradients were bitwise
identical using `torch.equal`. This is one-GPU training evidence, not a
representative-data convergence run or a 125B performance measurement.
Additional cache-reuse validation: 38 focused tests pass, including native
metadata, padded cache strides, and extra sequence-parallel model rows.
Across three rounds of two requests, generated tokens and log probabilities
are exactly equal to published stack 02f9eb9 in BF16 Dist-MoE TP2/EP2 + SP,
both eager and FULL_DECODE_ONLY, on both ranks. Full pre-commit checks pass.
liangel-02
added a commit
that referenced
this pull request
Dec 1, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
this approach, and what you checked yourself. -->
## Why
`TokenChoiceTopKRouter` (`torchtitan/models/common/moe/moe.py`) is the stock MoE
router: a gate GEMM scores every expert for each token, then a softmax, top-k,
gather, optional renormalization and scale produce each token's experts and
weights, plus a routing map. It is the router of Qwen3 MoE, GPT-OSS,
Qwen3.5/3.6/3.8 and Flash-Next.
In generation, decode steps are tiny (about 16 tokens per rank), so everything
after the gate GEMM is launch- and latency-bound: PyTorch runs it as about 12
small kernels per MoE layer. On Qwen3.8-Flash-Next (512 experts, top-10, 48 MoE
layers) that chain takes about 19 us per layer, about 0.9 ms of every decode step,
for almost no arithmetic.
**Example.** One MoE layer, one decode step (16 tokens per rank, 512 experts,
top-10):
```
before: gate GEMM -> softmax -> topk -> gather -> sum -> add -> div -> mul
-> memset + scatter (routing map) ... ~12 kernels, ~19 us
after: gate GEMM -> _softmax_topk_kernel 1 kernel, ~4.7 us
(same scores, expert IDs in the same order and routing map, bitwise)
```
## What changed
- `FusedSoftmaxTopKRouter` (`torchtitan/rl/generator/moe_router.py`), a
`TokenChoiceTopKRouter` subclass: the gate GEMM is unchanged; one Triton
kernel computes the softmax, top-k, gather, renormalization, scale and routing
map. Its outputs equal the stock router's bitwise: it reproduces PyTorch's
CUDA softmax and sum reduction orders and `torch.topk(sorted=False)`'s output
order.
- `_replace_vllm_layer_configs` swaps it in, as it already does for the QSA,
GDN, KDA and PLE generation layers, only for routers that are exactly
`TokenChoiceTopKRouter` with a softmax score. Kept as is:
- router subclasses (DeepSeek V3/V4, round-robin, quantile-balanced) and
non-softmax (e.g. sigmoid) scores;
- batch-invariant mode, which overrides `aten::sum`, so the stock router there
computes different numbers than the default order this kernel reproduces;
- non-CUDA accelerators and ROCm, whose reduction orders differ
(`device_type == "cuda"` and `torch.version.hip is None`, checked in the
swap and again in `FusedSoftmaxTopKRouter.Config.__post_init__`).
- Training never uses `FusedSoftmaxTopKRouter`; trainer numerics are unchanged.
How the kernel works (one launch per router call; each program owns a tile of
1 token row, or 4 above 1024 tokens):
1. Softmax over the E expert logits with 32 lanes per row, in the order of
PyTorch's warp-per-row softmax (per-lane partial max/sum, then an XOR
butterfly), which ATen uses for rows of up to 2048 FP32 elements.
2. Top-k by K rounds of row argmax (ties to the lower expert ID), adding the
expert bias to the selection score only, as the stock router does.
3. The routing map is the set of experts picked in step 2.
4. The K picks are reordered into `torch.topk(sorted=False)`'s output order,
renormalized with a halving tree sum that matches Reduce.cuh's K-element
warp reduction, and scaled. The kernel compiles with
`enable_fp_fusion=False` so no multiply-add fusion changes rounding.
Batch invariance: each Triton program handles a tile of token rows, and every
reduction runs along one row's expert axis in an order fixed by E and K. A
token's routing depends only on its own gate logits, not on the batch size,
padding or the other rows.
Router consumers audited: `MoE.forward`, `KimiK3MoE.forward` and
`MuseSparkMoE.forward` pass the router outputs on unchanged. The local and
all-to-all token dispatchers read the routing map and still get it; DeepEP,
HybridEP and Dist-MoE ignore it.
## Alternatives considered
- A `local_compile` region over the same chain: 9.8 us per layer after the gate
(vs 4.3 us for this kernel, measured in the same earlier run),
and not bitwise (Inductor's softmax, 10-element sum and fp32 division round
differently), so it could pick different experts on near-ties than the
trainer.
- vLLM's fused `topk_softmax` op: not written to reproduce ATen's softmax
and top-k orders, so its outputs are not guaranteed to match the trainer's
router bitwise (not tested).
- Moving routing into Dist-MoE: out of scope there; Dist-MoE takes top-k
expert IDs and scores from the caller and keeps routers out of its API.
## User-facing changes
| Before | After |
| --- | --- |
| Generator MoE layers run the stock router's eager chain | Generator MoE layers with a softmax `TokenChoiceTopKRouter` run one fused kernel; outputs bitwise equal |
| Training | Unchanged |
No config fields or flags; the swap is automatic and limited to the cases above.
## Numerics
- Router outputs (scores, expert IDs in order, routing map) are bitwise equal to
the stock router on 5 (E, K) shapes x 4 input kinds (normal, ties, underflow,
NaN/inf) x 3 configs (route_norm on/off, route_scale, expert bias).
- Full Flash-Next model, seeded generation with FULL CUDA graphs: decode tokens
and logprobs are bitwise identical before and after on 88/88 requests, with
the shared-expert side-stream overlap both off and on.
## Performance
**Router microbenchmark.** Flash-Next's router config (hidden 2560, E=512,
K=10, route_norm, BF16 input), one GB300. Each number is the average per call
of 48 back-to-back router calls captured in one CUDA graph (one call per MoE
layer), 50 replays. "After gate" subtracts the gate GEMM alone, which both
routers run unchanged.
| Tokens | Stock router | Fused router | After gate: stock -> fused | Speedup | Saved per 48 layers |
| ---: | ---: | ---: | ---: | ---: | ---: |
| 1 | 22.6 us | 8.5 us | 18.6 -> 4.5 us | 2.6x | 0.68 ms |
| 16 (decode, per rank) | 23.0 us | 8.8 us | 18.9 -> 4.7 us | 2.6x | 0.68 ms |
| 64 | 26.9 us | 9.0 us | 22.4 -> 4.5 us | 3.0x | 0.86 ms |
| 128 | 30.2 us | 8.8 us | 26.1 -> 4.8 us | 3.4x | 1.03 ms |
| 512 | 40.6 us | 10.8 us | 36.6 -> 6.9 us | 3.8x | 1.43 ms |
| 2048 (prefill chunk) | 78.2 us | 19.9 us | 72.0 -> 13.7 us | 3.9x | 2.80 ms |
| 8192 (largest prefill step) | 208.9 us | 56.1 us | 193.4 -> 40.7 us | 3.7x | 7.33 ms |
At decode sizes the stock chain is launch-bound (flat ~19 us after the gate);
at prefill sizes its extra passes over the (T, E) scores dominate, so prefill
and mixed prefill+decode steps also gain.
**End to end.** Qwen3.8-Flash-Next, 48 layers, real weights, DP4/EP4 on 4 GB300,
64 sequences at ~2.1k context, FULL CUDA graphs, with the Dist-MoE
decode-routing stack:
| | Before | After |
| --- | --- | --- |
| Decode step | 16.43 ms | 15.06 ms (-8.3%) |
| Arrival steps (new prompts join) | 36.4-37.9 ms | 34.2-35.9 ms |
| Kernels per decode replay | 3732 | 3204 |
The full-model rows also include a separate change that fuses Dist-MoE's two
padding `masked_fill`s (about 0.14 ms per step, not in this PR); this PR alone
accounts for about 1.2 ms of the 1.37 ms. They were measured on the Flash-Next
generation stack this PR sits on (#6443, #6202, #6203, #6308) with the
Dist-MoE decode-routing stack.
## Testing
```bash
pytest -q tests/rl/unit_tests/gpu/test_moe_router.py # 20 passed, GB300
pytest -q tests/rl/unit_tests/cpu/test_vllm_wrapper.py
```
The microbenchmark script is not part of this PR (it builds the Flash-Next
125B-A6B router config and times both routers as described above).
- `test_moe_router.py` (new): bitwise equality with the stock router across the
shapes, inputs and configs above. Catches a fused kernel whose outputs drift
from the stock router, including a PyTorch update that changes the ATen
softmax, sum or `torch.topk` orders the kernel reproduces.
- `test_vllm_wrapper.py` (extended): which routers the generator swaps. The
Qwen3 MoE debug flavor's softmax `TokenChoiceTopKRouter` is swapped; the
same model in batch-invariant mode, and with its routers converted to
`RoundRobinTokenChoiceTopKRouter` (a softmax subclass that selects experts
its own way), keeps the stock router. Catches the swap reaching routers whose
numerics it does not reproduce, e.g. a type check loosened to `isinstance`.
- Locally, `test_vllm_replacement_preserves_attention_sharding[kda]` in
`test_vllm_wrapper.py` fails to import `copy_replay_tails` from the installed
Attention Gym; that is an environment issue unrelated to this change.
## Known issues / follow-ups
- The kernel reproduces ATen's internal softmax, sum and top-k orders, which a
PyTorch update can change; `test_moe_router.py` fails if it does.
## Self-review
pr-review (branch mode) at f416c5763: needs discussion. Fixed after it: the
swap and `__post_init__` now also require `device_type == "cuda"` (XPU no
longer gets the kernel); the subclass test case uses a real softmax router
subclass (it used DeepSeek V3, rejected for its sigmoid score instead);
`_softmax_topk` is inlined into its only caller; the `_MAX_TOP_K` comment
states why the cap is 32. Not addressed:
- Whether torchtitan should host a hand-written Triton kernel that copies ATen
internals -- a maintainer question; it is generator-only, and the GPU test
fails if a PyTorch update changes the orders it depends on.
- Eligibility checks live in both the swap and `__post_init__`; a softmax
router beyond 2048 experts or top-32 would now raise at generator startup
instead of keeping the stock router (no in-repo flavor is close: max E=512,
K=10).
liangel-02
force-pushed
the
qwen38-rl-1-qsa
branch
from
December 1, 2026 21:20
869a5e2 to
9558eb9
Compare
liangel-02
added a commit
that referenced
this pull request
Dec 1, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
this approach, and what you checked yourself. -->
## Why
`TokenChoiceTopKRouter` (`torchtitan/models/common/moe/moe.py`) is the stock MoE
router: a gate GEMM scores every expert for each token, then a softmax, top-k,
gather, optional renormalization and scale produce each token's experts and
weights, plus a routing map. It is the router of Qwen3 MoE, GPT-OSS,
Qwen3.5/3.6/3.8 and Flash-Next.
In generation, decode steps are tiny (about 16 tokens per rank), so everything
after the gate GEMM is launch- and latency-bound: PyTorch runs it as about 12
small kernels per MoE layer. On Qwen3.8-Flash-Next (512 experts, top-10, 48 MoE
layers) that chain takes about 19 us per layer, about 0.9 ms of every decode step,
for almost no arithmetic.
**Example.** One MoE layer, one decode step (16 tokens per rank, 512 experts,
top-10):
```
before: gate GEMM -> softmax -> topk -> gather -> sum -> add -> div -> mul
-> memset + scatter (routing map) ... ~12 kernels, ~19 us
after: gate GEMM -> _softmax_topk_kernel 1 kernel, ~4.7 us
(same scores, expert IDs in the same order and routing map, bitwise)
```
## What changed
- New opt-in override `torchtitan_recipes/overrides/fused_softmax_topk_router.py`
(see `torchtitan/config/OVERRIDE.md`), activated by listing
`torchtitan_recipes.overrides.fused_softmax_topk_router.fused_softmax_topk_router`
in the RL controller's `override.imports` (or `--override`). Nothing changes
unless a recipe opts in; no core file is touched.
- `FusedSoftmaxTopKRouter`, a `TokenChoiceTopKRouter` subclass: the gate GEMM is
unchanged; one Triton kernel computes the softmax, top-k, gather,
renormalization, scale and routing map. Its outputs equal the stock router's
bitwise: it reproduces PyTorch's CUDA softmax and sum reduction orders and
`torch.topk(sorted=False)`'s output order.
- The `@override` factory claims only the generator's routers
(`fqns=["generator.model.*"]`) and only exact `TokenChoiceTopKRouter.Config`
nodes (`exact=True`), so router subclasses (DeepSeek V3/V4, round-robin,
quantile-balanced) and the trainer's routers keep the stock router. The kernel
has no backward, and `forward` raises if called with grad enabled.
- Unsupported cases raise instead of falling back:
- non-softmax scores, more than 2048 experts or top-k above 32, and non-CUDA
accelerators or ROCm, whose reduction orders differ
(`FusedSoftmaxTopKRouter.Config.__post_init__`);
- batch-invariant mode, which replaces `aten::sum`, so the stock router there
computes different numbers than the default order this kernel reproduces
(`FusedSoftmaxTopKRouter.__init__`).
- `rl_grpo_qwen3_8_flash_next_debug` enables the override, so the 4-GPU B200 RL
integration test runs it end to end.
How the kernel works (one launch per router call; each program owns a tile of
1 token row, or 4 above 1024 tokens):
1. Softmax over the E expert logits with 32 lanes per row, in the order of
PyTorch's warp-per-row softmax (per-lane partial max/sum, then an XOR
butterfly), which ATen uses for rows of up to 2048 FP32 elements.
2. Top-k by K rounds of row argmax (ties to the lower expert ID), adding the
expert bias to the selection score only, as the stock router does.
3. The routing map is the set of experts picked in step 2.
4. The K picks are reordered into `torch.topk(sorted=False)`'s output order,
renormalized with a halving tree sum that matches Reduce.cuh's K-element
warp reduction, and scaled. The kernel compiles with
`enable_fp_fusion=False` so no multiply-add fusion changes rounding.
Batch invariance: each Triton program handles a tile of token rows, and every
reduction runs along one row's expert axis in an order fixed by E and K. A
token's routing depends only on its own gate logits, not on the batch size,
padding or the other rows.
Router consumers audited: `MoE.forward`, `KimiK3MoE.forward` and
`MuseSparkMoE.forward` pass the router outputs on unchanged. The local and
all-to-all token dispatchers read the routing map and still get it; DeepEP,
HybridEP and Dist-MoE ignore it.
## Alternatives considered
- Swapping the router automatically in the vLLM model wrapper (this PR's first
revision): that makes the generator's MoE module differ from the trainer's by
default, against "Training and Inference Share Modules"
(`.claude/rules/models.md`). As an override the kernel is opt-in, the shared
model definition is unchanged, and the hand-written CUDA-specific kernel is
held to the override bar (`OVERRIDE.md`, "Hardware-specific kernels").
- A `local_compile` region over the same chain: 9.8 us per layer after the gate
(vs 4.3 us for this kernel, measured in the same earlier run),
and not bitwise (Inductor's softmax, 10-element sum and fp32 division round
differently), so it could pick different experts on near-ties than the
trainer.
- vLLM's fused `topk_softmax` op: not written to reproduce ATen's softmax
and top-k orders, so its outputs are not guaranteed to match the trainer's
router bitwise (not tested).
- Moving routing into Dist-MoE: out of scope there; Dist-MoE takes top-k
expert IDs and scores from the caller and keeps routers out of its API.
## User-facing changes
| Before | After |
| --- | --- |
| No fused router | Recipes can list the `fused_softmax_topk_router` override; the generator's softmax `TokenChoiceTopKRouter`s then run one fused kernel, outputs bitwise equal |
| `rl_grpo_qwen3_8_flash_next_debug` runs the stock router in the generator | It runs the fused router in the generator |
| Training | Unchanged |
No new config fields or flags; the override uses the existing `override.imports`.
## Numerics
- Router outputs (scores, expert IDs in order, routing map) are bitwise equal to
the stock router on 5 (E, K) shapes x 4 input kinds (normal, ties, underflow,
NaN/inf) x 3 configs (route_norm on/off, route_scale, expert bias).
- Full Flash-Next model, seeded generation with FULL CUDA graphs: decode tokens
and logprobs are bitwise identical before and after on 88/88 requests, with
the shared-expert side-stream overlap both off and on.
## Performance
**Router microbenchmark.** Flash-Next's router config (hidden 2560, E=512,
K=10, route_norm, BF16 input), one GB300. Each number is the average per call
of 48 back-to-back router calls captured in one CUDA graph (one call per MoE
layer), 50 replays. "After gate" subtracts the gate GEMM alone, which both
routers run unchanged.
| Tokens | Stock router | Fused router | After gate: stock -> fused | Speedup | Saved per 48 layers |
| ---: | ---: | ---: | ---: | ---: | ---: |
| 1 | 22.6 us | 8.5 us | 18.6 -> 4.5 us | 2.6x | 0.68 ms |
| 16 (decode, per rank) | 23.0 us | 8.8 us | 18.9 -> 4.7 us | 2.6x | 0.68 ms |
| 64 | 26.9 us | 9.0 us | 22.4 -> 4.5 us | 3.0x | 0.86 ms |
| 128 | 30.2 us | 8.8 us | 26.1 -> 4.8 us | 3.4x | 1.03 ms |
| 512 | 40.6 us | 10.8 us | 36.6 -> 6.9 us | 3.8x | 1.43 ms |
| 2048 (prefill chunk) | 78.2 us | 19.9 us | 72.0 -> 13.7 us | 3.9x | 2.80 ms |
| 8192 (largest prefill step) | 208.9 us | 56.1 us | 193.4 -> 40.7 us | 3.7x | 7.33 ms |
At decode sizes the stock chain is launch-bound (flat ~19 us after the gate);
at prefill sizes its extra passes over the (T, E) scores dominate, so prefill
and mixed prefill+decode steps also gain.
**End to end.** Qwen3.8-Flash-Next, 48 layers, real weights, DP4/EP4 on 4 GB300,
64 sequences at ~2.1k context, FULL CUDA graphs, with the Dist-MoE
decode-routing stack:
| | Before | After |
| --- | --- | --- |
| Decode step | 16.43 ms | 15.06 ms (-8.3%) |
| Arrival steps (new prompts join) | 36.4-37.9 ms | 34.2-35.9 ms |
| Kernels per decode replay | 3732 | 3204 |
The full-model rows also include a separate change that fuses Dist-MoE's two
padding `masked_fill`s (about 0.14 ms per step, not in this PR); this PR alone
accounts for about 1.2 ms of the 1.37 ms. They were measured on the Flash-Next
generation stack this PR sits on (#6443, #6202, #6203, #6308) with the
Dist-MoE decode-routing stack.
## Testing
```bash
pytest -q tests/unit_tests/gpu/recipes/test_fused_softmax_topk_router_override.py # 21 passed, GB300
python -m tests.integration_tests.run_tests <output_dir> --test_suite rl_b200 \
--test_name rl_grpo_qwen3_8_flash_next_debug --ngpu 4
```
The microbenchmark script is not part of this PR (it builds the Flash-Next
125B-A6B router config and times both routers as described above).
- `test_fused_softmax_topk_router_override.py` (new):
- bitwise equality with the stock router across the shapes, inputs and configs
above. Catches a fused kernel whose outputs drift from the stock router,
including a PyTorch update that changes the ATen softmax, sum or
`torch.topk` orders the kernel reproduces;
- applying the override to an RL controller config replaces every generator
router and no trainer router. Catches an `fqns` glob that silently matches
nothing (losing the speedup) or reaches the trainer.
- `rl_grpo_qwen3_8_flash_next_debug` (existing B200 RL integration test) now
runs with the override, covering the fused router under vLLM with Dist-MoE
and decode CUDA graphs. Locally on 4 GB300 it ran 3 GRPO steps with
validation, the override log showing all 8 generator routers replaced. The
local run moved weights through TorchStore (`model_state_dict_transport=None`):
this devserver's NIXL/UCX backend aborts the trainer in
`register_model_state_dict_source`, with and without this PR.
## Known issues / follow-ups
- The kernel reproduces ATen's internal softmax, sum and top-k orders, which a
PyTorch update can change; `test_fused_softmax_topk_router_override.py` fails
if it does.
## Self-review
pr-review (branch mode) at f416c5763 asked to fix the one-sided design: the
generator swapped in an inference-only router by default, against
`.claude/rules/models.md`. This revision makes it an opt-in override instead
(see "Alternatives considered"). Earlier fixes kept: `device_type == "cuda"` is
required (XPU never gets the kernel), and `_MAX_TOP_K`'s comment states why the
cap is 32. Not addressed:
- Whether torchtitan should host a hand-written Triton kernel that copies ATen
internals -- as an override it is opt-in and held to the override bar, and the
GPU test fails if a PyTorch update changes the orders it depends on.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary (human-written)
Why
The Flash-Next training model selects complete four-token blocks plus the current
incomplete tail. Generation needs to read those selections from vLLM's physical
KV pages across appends, request reordering, and graph padding. The existing
vLLM replacement does not implement that QSA cache contract.
For a request with 11 tokens selecting block 0, attention must read token
positions
[0, 1, 2, 3, 8, 9, 10], even if its logical pages have moved.What changed
Add a parameter-free vLLM page owner calling Attention Gym
paged_sparse_decode.Add
QSAPagedMetadataBuilder, which builds decode metadata as views of vLLM'spersistent runner buffers. vLLM already pads them for
FULL_DECODE_ONLYgraphs(zero lengths, null pages,
-1slots), so replay reads each step's requestlayout without extra copies. It only uses vLLM's generic backend and
CommonAttentionMetadatacontracts, likeTorchTitanLinearAttentionMetadataBuilder.Preserve request-local addressing, incomplete causal tails, and inactive rows.
Reject unsupported cache dtypes, speculative decoding, decode CP, and graph modes.
Every step calls Attention Gym's
paged_sparse_decodeonce with vLLM'sper-request block table,
query_start_locandseq_lens. Decode-only stepskeep the host-bound call (
max_seqlen_q=1). Steps with prompt rows passmax_seqlen_q=Noneandcausal_topk=True(the paged lightning indexer'soutput satisfies that contract), so each row finds its request on the device
and prompt rows are attended in query tiles that load each K/V chunk once.
No step gathers a prompt's context or needs host token counts. This needs the
Attention Gym change that adds
causal_topk(make paged_sparse_decode cudagraphable meta-pytorch/attention-gym#979).
QSA attention per layer, GB300, 24/2 heads, against gathering each prompt's
context and running
gather_attn(timed eagerly, since it needs host counts):gather_attncausal_topkAdd
torchtitan/rl/generator/local_compile.pywith two sharedlocal_compileregion names for generator-only functions,INFERENCE_BATCH_INVARIANT_REGIONandINFERENCE_BATCH_VARIANT_REGION;inference_local_compile(batch_invariant=...), which registers a functionunder the matching one; and
inference_regions(), which returns the regionsthat have registered functions (leaving out the batch-variant one in
batch-invariant mode), so a generator can enable them without knowing which
layers registered functions. Core
torchtitan/distributed/local_compile.pyis unchanged. QSA's padding-row helper registers under the batch-invariant
region; the generator enables the regions in Integrate the paged lightning indexer with compressed QSA caches #6202.
The common Attention Gym export additions are mechanical import plumbing.
vLLM remains responsible for allocation and reclamation; Python-owned request
caches would duplicate that ownership.
User-facing changes
FULL_DECODE_ONLYdecode replays QSA attentionTesting
pytest -q tests/rl/unit_tests/gpu/test_vllm_qsa.pyThe attention test checks reordered physical pages against an independent sparse
causal reference, including incomplete tails and padding. The graph test refreshes
persistent metadata buffers in place with vLLM's padding, as vLLM's runner does,
and checks replay after changing page tables, lengths, and live request counts.
Full Flash-Next generation additionally needs the indexer and PLE changes in the
next two commits.
Validation scope
This commit alone is covered by
tests/rl/unit_tests/gpu/test_vllm_qsa.py; thetraining-loss and generation checks below cover the whole stack.
Validation used local B200 GPUs and an Attention Gym development build preserving
the original cuDNN linear kernels, with the paged sparse APIs added. The pinned
attn-gym==0.0.20alone does not supply these APIs. No GDN/KDA migration is included.The complete stack passed
pre-commit run --all-files. A deterministic seed-42BF16 debug-model forward/backward (32 tokens) was compared against
44ff1567196fe91ba8a8f96a1aeefbc6715dda8c: loss4.4367218017578125, gradientnorm
22.315799713134766, logits, and all 192 parameter gradients were bitwiseidentical using
torch.equal. This is one-GPU training evidence, not arepresentative-data convergence run or a 125B performance measurement.
Additional cache-reuse validation: 38 focused tests pass, including native
metadata, padded cache strides, and extra sequence-parallel model rows.
Across three rounds of two requests, generated tokens and log probabilities
are exactly equal to published stack 02f9eb9 in BF16 Dist-MoE TP2/EP2 + SP,
both eager and FULL_DECODE_ONLY, on both ranks. Full pre-commit checks pass.