Skip to content

Connect Flash-Next generation and add a debug RL recipe - #6308

Open
liangel-02 wants to merge 1 commit into
qwen38-rl-3-plefrom
liangel-02/stack/31
Open

liangel-02 wants to merge 1 commit into
qwen38-rl-3-plefrom
liangel-02/stack/31

Conversation

@liangel-02

@liangel-02 liangel-02 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

What changed

  • The vLLM generator serves text-only Flash-Next with the stock
    VLLMModelWrapper. Qwen38FlashNextModel.forward now defaults
    ple_input_ids to the token IDs and document_positions to the positions
    when they are not passed, which is what generation supplies (one document per
    request, token-ID inputs); it raises if the model does not embed token IDs
    itself or gets no positions. Training always passes both and is unchanged.
  • register_to_vllm rejects multimodal Flash-Next and vision processors for
    generation.
  • rl_grpo_qwen3_8_flash_next_debug (torchtitan_recipes/tests/rl/alphabet_sort.py):
    random-init Flash-Next on four GPUs, an FSDP2 trainer and a TP2/EP2
    generator with compressed QSA caches, cached PLE and FULL_DECODE_ONLY
    graphs, with validation on like the other recipes. It runs as a 4-GPU B200
    RL integration test. Flash-Next pipeline parallelism ([qwen3_8_fn] 6/n Add pipeline parallelism #6055) has not landed,
    so the trainer does not use PP yet.

Testing

python -m tests.integration_tests.run_tests <output_dir> --test_suite rl_b200 --ngpu 4
pytest -q tests/rl/unit_tests/cpu/test_model_defaults.py

Comment on lines +325 to +329
if isinstance(model_config, Qwen38FlashNextModel.Config):
if vision_processor is not None or isinstance(
model_config, Qwen38FlashNextMultimodalModel.Config
):
raise ValueError("Flash-Next RL generation currently supports text only")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

what makes it not supported?

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 8s —— View job


Approve -- please address the items before merging (missing human-written summary, answer @tianyu-l's question and simplify the multimodal guard): review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. The change is small and stays inside the Flash-Next model and the generator's registration. The remaining items are local edits: the missing summary, an answer to @tianyu-l's question, and a simpler guard. A maintainer still needs to review, because the PR touches model code and the RL generator.

What this PR does. The text-only Flash-Next model can now run under the stock VLLMModelWrapper. When ple_input_ids and document_positions are not passed, forward uses the token IDs and the vLLM positions instead. register_to_vllm rejects multimodal Flash-Next. The PR also adds a 4-GPU B200 RL recipe and an integration test: PP2 Interleaved1F1B trainer, TP2/EP2 Dist-MoE generator, FULL_DECODE_ONLY graphs.

Example.

# vLLM step, 2 requests packed: input_ids=[a b c | d e], positions=[0 1 2 | 0 1]
VLLMModelWrapper.forward -> model(input_ids, positions=positions)
before: TypeError, missing keyword-only args document_positions / ple_input_ids
after:  ple_input_ids=input_ids, document_positions=positions
        (document_starts -> [0 0 0 3 3], one document per request)
trainer: preprocess_inputs still passes both, so training numerics are unchanged

Must fix

  1. The "Summary (human-written)" section is empty. The author needs to fill it in.
  2. torchtitan/rl/generator/vllm/registry.py:325 -- @tianyu-l's question ("what makes it not supported?") has no answer yet. I answered it inline. Short version: the multimodal wrapper runs Decoder.forward_embeddings, which passes no token IDs or document positions to the Flash-Next blocks and skips the residual streams. The guard can shrink to isinstance(model_config, Qwen38FlashNextMultimodalModel.Config), because the controller already rejects the other combinations. It should carry a TODO and an error message that gives this reason.

Should consider

  • torchtitan/models/qwen3_8_flash_next/model.py:368 -- handle only the case where both values are None, and add a comment saying this is the vLLM generation contract (inline suggestion).

Questions

  • torchtitan_recipes/tests/rl/alphabet_sort.py:1173 -- the sibling Dist-MoE recipe uses cuda_graph.mode = "FULL". Is FULL_DECODE_ONLY needed here because QSA or PLE prefill can't be captured? If so, a one-line comment would help.
Details
  • Multimodal checks in the controller: controller.py:492-510 already raises for a multimodal config without vision_processor, and for a vision_processor without a multimodal config that has a vision encoder. The vision_processor is not None half of the new check is therefore redundant.
  • Where the defaulting lives: I also considered having the wrapper pass the two kwargs. That would add a Flash-Next branch to the shared VLLMModelWrapper. Keeping the defaults in the model's forward is the smaller change and keeps one module for training and serving.
  • PP: later PP stages have tok_embeddings is None, so they hit the new ValueError instead of hashing hidden states. Training never reaches that case, because preprocess_inputs passes both values on every stage.
  • Prefix caching: VLLMPLELayer.__init__ already raises when prefix caching is on, so the recipe's enable_prefix_caching: False is required, not tuning.

Not verified: I did not run the new rl_grpo_qwen3_8_flash_next_debug B200 integration test.

Comment on lines +325 to +329
if isinstance(model_config, Qwen38FlashNextModel.Config):
if vision_processor is not None or isinstance(
model_config, Qwen38FlashNextMultimodalModel.Config
):
raise ValueError("Flash-Next RL generation currently supports text only")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Answering @tianyu-l's question: the multimodal path never gives Flash-Next the inputs it needs. VLLMMultimodalModelWrapper.forward (multimodal_wrapper.py:444) calls self.model.forward_embeddings(inputs_embeds, positions, ...). Flash-Next does not override that, so this resolves to Decoder.forward_embeddings (models/common/decoder.py:366), which:

  • calls each Qwen38FlashNextBlock without ple_input_ids_T / document_positions_T, so the first block fails with a TypeError;
  • never expands the input to the S residual streams and never runs hyper_connection_mixer;
  • gets only embeddings and (3, T) M-RoPE positions, so PLE has no token IDs to hash and no 1D document positions.

The check can also be shorter. Controller.Config already rejects a text-only config that has a vision_processor (controller.py:503-510), and it rejects a multimodal config that has none (controller.py:493). The only case that gets this far is a Qwen38FlashNextMultimodalModel.Config with a vision processor. The error message should give the reason, and the limitation should be a TODO:

Suggested change
if isinstance(model_config, Qwen38FlashNextModel.Config):
if vision_processor is not None or isinstance(
model_config, Qwen38FlashNextMultimodalModel.Config
):
raise ValueError("Flash-Next RL generation currently supports text only")
# TODO: VLLMMultimodalModelWrapper runs Decoder.forward_embeddings on merged
# embeddings and M-RoPE positions; Flash-Next's PLE needs the token IDs and 1D
# document positions, and its residual streams need its own forward.
if isinstance(model_config, Qwen38FlashNextMultimodalModel.Config):
raise ValueError(
"Flash-Next RL generation supports text only: the multimodal wrapper "
"passes embeddings, not the token IDs that PLE hashes"
)

Comment on lines +368 to +377
if document_positions is None or ple_input_ids is None:
if self.tok_embeddings is None or positions is None:
raise ValueError(
"Flash-Next needs document_positions and ple_input_ids unless it "
"embeds the token IDs itself and gets text positions"
)
document_positions = (
positions if document_positions is None else document_positions
)
ple_input_ids = tokens if ple_input_ids is None else ple_input_ids

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This block has no comment saying why these defaults exist, and it handles cases no caller produces. preprocess_inputs always passes both values, and the vLLM wrapper passes neither, so "only one of them is None" never happens. With one branch and a comment, a reader can tell this is the generation contract, not a training fallback:

Suggested change
if document_positions is None or ple_input_ids is None:
if self.tok_embeddings is None or positions is None:
raise ValueError(
"Flash-Next needs document_positions and ple_input_ids unless it "
"embeds the token IDs itself and gets text positions"
)
document_positions = (
positions if document_positions is None else document_positions
)
ple_input_ids = tokens if ple_input_ids is None else ple_input_ids
if document_positions is None and ple_input_ids is None:
# vLLM generation: token-ID inputs and one document per request, so the
# request positions are the document positions.
if self.tok_embeddings is None or positions is None:
raise ValueError(
"Flash-Next needs document_positions and ple_input_ids unless it "
"embeds the token IDs itself and gets text positions"
)
document_positions, ple_input_ids = positions, tokens

If a call passes only one of the two, the other stays None and _forward_streams fails on the type. If you want an explicit error for that case too, raise when exactly one of them is None.

@liangel-02
liangel-02 marked this pull request as draft November 21, 2026 12:44
@liangel-02
liangel-02 changed the base branch from qwen38-rl-3-ple to main November 21, 2026 12:44
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 21, 2026
@liangel-02
liangel-02 force-pushed the liangel-02/stack/31 branch 2 times, most recently from 6ffab5f to 096bce8 Compare November 21, 2026 12:44
@liangel-02
liangel-02 changed the base branch from main to qwen38-rl-3-ple November 21, 2026 12:44
@liangel-02
liangel-02 marked this pull request as ready for review November 21, 2026 12:44
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 21, 2026
tianyu-l pushed a commit that referenced this pull request Nov 21, 2026
…onfig (#6316)

Stacked PRs:
 * #6305
 * #6308
 * #6203
 * #6202
 * #6201
 * __->__#6316


--- --- ---

### [qwen3_8_fn] Drop the removed ModelConfigConverter from
build_model_config


## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

#6164 deleted `ModelConfigConverter`, `validate_converter_compatibility`
and
the `converters` argument of every `build_model_config`, while the
Flash-Next
model (#6046-#6054) landed still using them. On main, importing
`torchtitan.models.qwen3_8_flash_next` fails with
`ImportError: cannot import name 'ModelConfigConverter'`, so every
Flash-Next
test errors at collection.

This applies #6164's change to Flash-Next: remove the import, the
`converters`
argument and its conversion block from `build_model_config`, as #6164
did for
the other models. Recipes apply converters as transforms with
`apply_transforms`. No in-repo caller passes `converters` to Flash-Next.

```bash
pytest -q tests/unit_tests/cpu/models/qwen3_8_flash_next
```
wwwjn pushed a commit that referenced this pull request Nov 23, 2026
Stacked PRs:
 * #6305
 * #6308
 * #6203
 * #6202
 * __->__#6201
 * #6316


--- --- ---

### Add vLLM paged QSA attention and graph metadata


## 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`. Decode-only
steps
keep the host-bound call (`max_seqlen_q=1`). Steps with prompt rows pass
`max_seqlen_q=None` and `causal_topk=True` (the paged lightning
indexer's
output 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`
  (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):

  | Step | `gather_attn` | `causal_topk` |
  | --- | --- | --- |
  | 16 decode + 2 x 137 | 143.5 us | 46.3 us |
  | 64 decode + 8 x 210 | 271.2 us | 119.3 us |
  | 64 decode + 8 x 1000 | 827.6 us | 438.3 us |
  | 2 x 4096 | 1360.0 us | 1034.2 us |
  | 1 x 8192 | 1970.6 us | 1924.5 us |

- 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 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.20` alone does not supply these APIs. No GDN/KDA
migration is included.

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 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).
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).
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why
     this approach, and what you checked yourself. -->

## What changed

- The vLLM generator serves text-only Flash-Next with the stock
  `VLLMModelWrapper`. `Qwen38FlashNextModel.forward` now defaults
  `ple_input_ids` to the token IDs and `document_positions` to the positions
  when they are not passed, which is what generation supplies (one document per
  request, token-ID inputs); it raises if the model does not embed token IDs
  itself or gets no positions. Training always passes both and is unchanged.
- `register_to_vllm` rejects multimodal Flash-Next and vision processors for
  generation.
- `rl_grpo_qwen3_8_flash_next_debug` (`torchtitan_recipes/tests/rl/alphabet_sort.py`):
  random-init Flash-Next on four GPUs, an FSDP2 trainer and a TP2/EP2
  generator with compressed QSA caches, cached PLE and FULL_DECODE_ONLY
  graphs, with validation on like the other recipes. It runs as a 4-GPU B200
  RL integration test. Flash-Next pipeline parallelism (#6055) has not landed,
  so the trainer does not use PP yet.

## Testing

```bash
python -m tests.integration_tests.run_tests <output_dir> --test_suite rl_b200 --ngpu 4
pytest -q tests/rl/unit_tests/cpu/test_model_defaults.py
```
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

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants