Skip to content

[qwen3_8_fn] 1/n Add Flash-Next model, DTensor PLE, FSDP and EP - #6046

Merged
shuhuayu merged 1 commit into
mainfrom
qwen3-8-fn-1-model
Nov 21, 2026
Merged

shuhuayu merged 1 commit into
mainfrom
qwen3-8-fn-1-model

Conversation

@shuhuayu

@shuhuayu shuhuayu commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Enable qwen 3.8 flash next in torchttian. 1) verfied model definition and numerics. 2) distmuon + adamw optimizer 3) fsdp + ep, row sharded ple table on dp mesh.

Why

TorchTitan cannot build or load Qwen3.8-Flash-Next on main. The architecture extends Qwen3.5 with four gated residual streams, Qwen Sparse Attention (QSA) and a hashed n-gram embedding (PLE). Ordinary FSDP would all-gather its 51.2B-parameter PLE table: 95.37 GiB in BF16.

Example. Two DP owners retain rows 0-3 and 4-7 of an eight-row table. Requests [6,1,6] route unique IDs [1,6] to their owners and return [E6,E1,E6]. Backward returns vector gradients to those owners.

config = qwen38_flash_next_debugmodel(
    parallelism=ParallelismConfig(
        data_parallel_shard_degree=2,
        expert_parallel_degree=2,
    ),
)
# PLE rows: Shard(0) over DP, excluded from FSDP all-gathers.
# Experts: existing EP placements and dispatcher, independent of PLE.

Builds on the merged GDN determinism prerequisite #5784 and the attn-gym 0.0.20 pin (#6063). Supersedes #5782, which holds the earlier review discussion.

What changed

Model (torchtitan/models/qwen3_8_flash_next/)

  • Reuse Qwen3.5 GDN, vision and lifecycle; add gated residual streams, document-local hashed PLE, QSA and an HF state dict adapter.
  • Following Qwen3.5's text/multimodal split, Qwen38FlashNextModel is the text decoder (debugmodel) and Qwen38FlashNextMultimodalModel adds the vision encoder (debugmodel_mm, 125B-A6B). Its config repeats the vision_encoder field instead of inheriting Qwen35MultimodalModel.Config, because two slotted dataclass bases that both add fields cannot be combined.
  • row_sharded_embedding.py (model-agnostic, model-local until a second model needs it): public PyTorch functional collectives route sorted unique IDs, vectors and gradients to DP row owners. The lookup is an autograd.Function whose backward spells out the only collective (the reverse all-to-all), so DTensor's autograd chooses no collectives; it carries an SPMD type rule. The table is a DTensor on the dense SPMD mesh (Shard(0) on dp, replicated on cp/tp) and is initialized through DTensor's RNG like other parameters, so existing clipping, optimizers and native DCP handle it; HF fragments use the public CheckpointableTensor coordinate fields, and export gathers no table rows.
  • QSA attention runs on Attention Gym gather_attn: the selected blocks and the incomplete tail are sparse KV indices into the packed sequence, with separate values and grouped KV heads. CUDA uses the fused Triton grouped kernel (SM100/SM103); CPU uses the reference implementation, as in DeepSeek-V4.
  • QSA blocks are selected with Attention Gym lightning_indexer over valid tokens with per-document offsets, so candidates are exactly the document-local blocks. QSAIndexMetadata builds that layout once per microbatch, shared by all QSA layers. The indexer scores each query chunk only against the block window its documents can reach: the data pipeline caps documents at the model's max_context_length (text packing splits them, multimodal datasets skip longer samples), so a chunk's selections fall in W = ceil((chunk + max_context_length - 1) / R) consecutive block ids (1280 of 4096 for 16K tokens at 125B shapes). A device-side assert catches a producer that breaks the cap.
  • The no-grad indexer teacher gathers the selected keys once and runs one strided baddbmm per KV head (bf16 inputs, fp32 accumulation), 512 queries per chunk, with one block_kl over all tokens. Indexer KL scores use 1024-query checkpointed chunks. The selected-key count J = k * R + R - 1 is odd, which sends cuBLAS to an unaligned kernel, so the teacher pads J to a multiple of 8 with masked slots (2.1x faster per 125B QSA layer on GB300).
  • GDN/QSA projections and gates are two ordinary Linear modules whose outputs are interleaved per head, so they can take separate optimizers without a concatenated weight copy or custom autograd.
  • The router is the shared TokenChoiceTopKRouter built with make_router_config (HiMidLoLinear gate, softmax), as in Qwen3/Qwen3.5. The HF reference rounds router logits and top-k scores to BF16; the shared router keeps them in FP32. Same-weight HF parity still matches every expert ID exactly and lowers the logit error against an FP32 reference (table below).
  • QSAIndexMetadata is required by the QSA layer and indexer; it is built once per microbatch, so missing metadata fails instead of being rebuilt per layer.
  • SPMD: modules typecheck globally except PLELayer and the QSA indexer, which stay local_spmd because they index the token axis with rank-local positions (documented inline).
  • Layout changes are explicit spmd calls in forward, since ShardingConfig only declares layouts: restore the residual layout after the vision scatter, gather the residual stream around PLE, and gather before lm_head. Without TP they return their input unchanged, so they change no computation in this PR.
  • Gated-residual and PLE projections whose outputs feed bare ops mark those outputs with remat.recompute_needs_tensor, so selective remat policies that save the projections recompute correctly (full remat never reads them).
  • Padding: like the GDN layers, PLE does not skip padding inside a document. Every in-repo producer starts trailing padding at document position 0, so padding never enters a real document's n-gram history.

Optimizer recipe (torchtitan_recipes/models/qwen3_8_flash_next.py)

  • Report policy (section 3.1): DistMuon for decoder linear maps; AdamW for embeddings, head, router, GR, gates, decay/beta, norms, convolutions and vision; Adam with zero weight decay for PLE. BlockShard separates Q/K/V heads.
  • DistMuon: Nesterov momentum 0.95, eight Polar Express iterations, epsilon 1e-14, 0.2 * sqrt(max(rows, columns)) scaling.
  • Optimizer layouts follow recipe parallelism; post-init raises on an EP layout mismatch instead of rewriting the optimizer.

Tests and tools

  • HF parity script: text, standalone vision and image/video forward/backward with parameter/input gradients and exact expert/token selections.
  • qwen3_8_flash_next_fsdp in the B200 suite (fused gather_attn needs SM100/SM103): FSDP2/EP2, save at step 5, load and continue to step 10.

Mechanical (skimmable): public Qwen3.5 factory names (make_qwen35_vision_encoder_config, make_qwen35_deltanet_config).

Alternatives considered

  • Plain FSDP on the PLE table: all-gathers 95.37 GiB per step.
  • TorchRec: broader embedding stack than fixed row ownership with individual-vector lookups needs; all-to-all plus F.embedding reuses torchtitan's DTensor optimizers, clipping and DCP.
  • Plain local parameters instead of a DTensor table: would need new core contracts for clipping and DCP.
  • QSA on chunked MATH SDPA: ~10 s forward+backward per layer at T=4096, versus 3.3 ms with fused gather_attn on GB300.
  • Indexer teacher with replicated keys and fp32 multiply-sum: one 125B QSA layer forward+backward takes 80.0 ms and 2893 GPU ops, versus 20.4 ms and 631 with grouped GEMMs.

User-facing changes

Before After
Flash-Next cannot be built or loaded Debug and released flavors, HF adapter, FSDP and EP
An embedding table is all-gathered by FSDP DP row owners exchange selected vectors and gradients
— qwen38_flash_next_debugmodel / _mm recipes with the report optimizer policy

Numerics

HF parity uses a reduced model initialized by HF and loaded through the adapter (checkpoint schema de4b8e4d43b917e7706784d8bb445c9af86a3540, Transformers 494470d677d05d44153d235d795e0d01040307ab), attn-gym 0.0.20.

Check Hardware Result
Projection/gate head order and reassembled parameter gradients, FP32 CPU GDN and QSA match the fused oracle bitwise
HF text forward/backward, BF16 GB300 Max logit error vs BF16 HF 4.64e-3; vs an FP32 HF copy 4.03e-3 (BF16 HF itself: 4.28e-3); gradient cosine 0.999926; expert IDs and selections match exactly
HF image/video forward/backward, BF16 decoder + FP32 vision GB300 Max logit error vs BF16 HF 3.17e-3; vs an FP32 HF copy 4.34e-3 (BF16 HF itself: 4.59e-3); gradient cosine 0.999953
Standalone HF vision, FP32 GB300 Max output error 3.35e-7; gradient cosine > 0.999999999999
Multimodal fixture, FSDP2/EP2, 10 steps, seed 42, deterministic (measured at an earlier revision, before the router and PLE-init changes) Two GB300s Loss 7.772000312805176 -> 3.043048858642578; bitwise reproducible across runs; SPMD typechecking on
C4, FSDP2/EP2, 50 steps (earlier revision) Two GB300s Loss 7.77 -> 3.07; loss and gradient norms finite
Padded indexer teacher vs unpadded GB300 Teacher probabilities differ only by fp32 summation order (<= 4.4e-9)
Default and full remat vs no remat, block with PLE and gated residuals CPU Parameter gradients bitwise equal

HF parity gate

Both BF16 models round differently from the exact result, so the script gates logits against an FP32 copy of the HF model: torchtitan's max error must stay within twice the BF16 HF reference's (text 4.03e-3 vs 4.28e-3, image/video 4.34e-3 vs 4.59e-3), as the repo's kernel-override tests do. Router scores are compared at the reference's BF16 dtype. Tolerances are unchanged.

Offline comparisons across parallelisms

Measured at an earlier revision (before the router switch); the layout-invariance conclusions do not depend on it. Same native DCP checkpoint, logical inputs, two microbatches and step-global CE/auxiliary normalization. Parameters remain FP32 master tensors; FSDP-managed compute (including vision) is BF16, and gradient reduction is FP32. Each case compares logits, CE, MoE/indexer objectives, all parameter gradients reconstructed through their DTensor placements, token-embedding and image/video input gradients, and the global gradient norm.

Comparison against unsharded gather_attn Max logit error Gradient norm ratio Gradient cosine Routing and QSA selection
Image/video, FSDP2/EP1 fused 0 1.000012399 0.999998398 exact
Image/video, FSDP2/EP2 fused 0 1.000012408 0.999998401 exact
Text, FSDP2/EP1 reference 0 0.999985289 0.999997679 exact
Text, FSDP2/EP2 reference 0 0.999985302 0.999997685 exact

With the fused kernel, text logits exceed the forward bound in 182 of 159,744 entries (first microbatch), all in the second document of logical rank 1; QSA selections stay exact, and in the second microbatch one token's expert routing changes. Cause: fused gather_attn is not bitwise invariant to a query's row in the packed batch. Isolated, the same queries at rows 39-77 of a 78-token batch versus rows 0-38 of their own batch differ by one BF16 ulp, starting at row 64 (a 64-query tile boundary); the reference kernel is bitwise invariant. The unsharded layout concatenates both logical ranks, so it places those tokens at different rows than FSDP does. This is an Attention Gym kernel property, not a sharding difference; the image/video fixture stays within one tile and matches bitwise.

Checkpoint resume: the integration test saves at step 5, loads and continues to step 10. Model, optimizer and dataloader state are restored exactly (two resumes from one checkpoint are bitwise identical), but resumed training is not bitwise identical to uninterrupted training from step 9: the shared compiled vision flex_attention picks static or dynamic shapes from the process's history (#6093). With torch._dynamo.config.automatic_dynamic_shapes = False, they match bitwise.

Performance

Released 125B-A6B from its HF checkpoint on 16 GB300s: FSDP16 + EP16 (HybridEP, one NVLink domain), PLE rows over DP16, 4K tokens per rank, full remat, default local_compile regions, 30 C4 steps. The run uses a local launcher; the 125B recipe lands in #6053.

s/step (steps 3-30) tokens/s/GPU Memory Step-30 loss
3.62 1131 150.85 GiB 2.42466

The step is CPU launch bound (~56k GPU ops per step); accelerator-graph capture follows in #6053.

QSA on gather_attn

Released 125B-A6B QSA shapes on one GB300 (T=4096, 24 query heads, 2 KV heads, head dim 256, 2051 selection slots from the real indexer over two documents). BF16 relative error against an FP64 dense masked-attention oracle:

Implementation out dq dk dv
Fused gather_attn 3.4e-3 4.4e-3 4.4e-3 3.6e-3
Chunked MATH SDPA (alternative) 3.1e-3 4.0e-3 9.1e-3 8.2e-3

Fused outputs and gradients are bitwise identical within a process, across processes and from cold Triton caches, with and without deterministic algorithms. The CPU test checks output and gradients against dense masked SDPA in FP64.

QSA selection on lightning_indexer

Released 125B-A6B indexer shapes on one GB300 (T=4096, two documents, padding inside a document and at the end), compared with ranking every complete block per query (argsort):

Mode Rows selecting identical blocks Differences
Deterministic algorithms 4096/4096 none; selected scores bitwise equal
Default 3964/4096 132 rows swap blocks with exactly equal cutoff scores

ReLU scores tie exactly (2.2% of selected scores at random init). With deterministic algorithms the CuTe backend resolves ties toward earlier blocks, independent of later candidates; otherwise the choice among cutoff ties is backend-defined. On CPU, Attention Gym's reference uses torch.topk. Indexer forward+backward: 51 ms vs 64 ms for argsort.

Testing

  • pre-commit, including typechecking: pass.
  • 53 targeted CPU tests: 21 Flash-Next (selective-remat gradients, head ordering, HF-exact gated-norm rounding, document/hash boundaries with HF-pinned multipliers, PLE convolution/gradients, sparse selection and attention backward, indexer-only gradients, HF roundtrips/inventory, row-sharded lookup and DTensor table layout) and 32 shared AuxLoss/MoE.
  • Four-rank CPU/Gloo lookup tests: routed values, accumulated gradients and optimizer updates against a dense reference at atol=0 (covering the explicit-backward lookup), global clipping and native checkpoint resharding.
  • Offline unsharded vs FSDP/EP comparisons with real NCCL communication, as above.
  • B200-suite integration qwen3_8_flash_next_fsdp (FSDP2/EP2, SPMD typechecking, save/load/continue): passes on two GB300s.
python -m pytest tests/unit_tests/cpu/models/qwen3_8_flash_next \
  tests/unit_tests/cpu/models/common/test_aux_loss.py \
  tests/unit_tests/cpu/models/common/test_moe.py -q
python -m scripts.checkpoint_conversion.numerical_tests_qwen3_8_flash_next \
  --device cuda --output outputs/flash_next_hf.json
python -m tests.integration_tests.run_tests outputs/flash_next_integration \
  --test_suite b200 --execution_mode real_pg --ngpu 2 \
  --test_name qwen3_8_flash_next_fsdp --no-parallel

Known issues / follow-ups

  • Reduced models are qualified for numerics; 262,144-token training of the released model is unqualified. Dense FP32 PLE parameters, gradients and two Adam moments cost 95.37 GiB per owner at DP8.
  • CPU offload and deferred FSDP reduction for PLE are unsupported. Rows must divide the DP degree. A fresh table is reproducible for a given layout but, as for every DTensor parameter, differs across DP/TP layouts; training loads it from the HF checkpoint. Native checkpoints support resharding.
  • The lookup's all-to-all keeps NCCL connection buffers for every DP peer (unlike FSDP's ring collectives), so that memory grows with DP; measured only within one NVLink domain (16 GPUs). TODO at the all-to-all.
  • Fused gather_attn with separate values and grouped KV heads requires SM100/SM103; other GPUs raise in Attention Gym.
  • The indexer teacher is model-local pending the shared indexer teacher.
  • Resumed vs uninterrupted training: Compiled FlexAttention depends on process history, so resumed training is not bitwise identical to uninterrupted training #6093.
  • TP/SP, PP and CP are rejected by this PR's configuration.

Stack

Managed with gh stack on upstream branches.

  1. This PR: Flash-Next model, DTensor PLE, FSDP/EP, report optimizer policy.
  2. [qwen3_8_fn] 2/n Give QSA metadata and block selection static shapes #6047: QSA with static shapes for accelerator-graph capture.
  3. [qwen3_8_fn] 3/n Route row-sharded PLE lookups through fixed-capacity slots #6052: fixed-capacity PLE row-sharded routing (no host-synchronized splits).
  4. [qwen3_8_fn] 4/n Add the 125B-A6B recipe and an accelerator-graph test #6053: the released 125B-A6B recipe and an accelerator-graph test.
  5. [qwen3_8_fn] 5/n Add tensor and sequence parallelism #6054: tensor and sequence parallelism.
  6. [qwen3_8_fn] 6/n Add pipeline parallelism #6055: pipeline parallelism.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 12, 2026
@shuhuayu shuhuayu added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 12, 2026
@shuhuayu shuhuayu changed the title qwen3 8 fn 1 model [qwen3_8_fn] 1/n Add Flash-Next model, DTensor PLE, FSDP and EP Nov 12, 2026
@shuhuayu
shuhuayu marked this pull request as ready for review November 12, 2026 02:58
@github-actions
github-actions Bot requested a review from ivy-zhou November 12, 2026 02:58
@shuhuayu
shuhuayu added this pull request to stack #6048 November 12, 2026 03:27
@pytorch-bot pytorch-bot Bot added the ciflow/b200 Trigger B200 CI label Nov 12, 2026

@liangel-02 liangel-02 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.

my agent is also saying that

The author reports reproducible uninterrupted training, but resumed loss/grad_norm diverge from step 9. 
The integration checks save/load completion without comparing trajectories."

ive not fact checked this but maybe worth taking a look?

def hash_ids(
self, input_ids_T: torch.Tensor, *, document_positions_T: torch.Tensor
) -> torch.Tensor:
input_ids_T = input_ids_T.long()

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.

should we thread padding_mask_T through here and use it to mask out padding w/ EOS? otherwise i think this will change the hashing of future tokens

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks! I checked who produces padding_mask: the text packer, TextCollator and the multimodal packer all start trailing padding at document position 0, so padding is its own document and never enters a real document's hash history. The GDN layers (3 of 4) also ignore padding_mask, so padding inside a document isn't supported by the model as a whole; masking it only in PLE wouldn't make outputs padding-invariant. I documented this in the hash_ids docstring and the README (e084762) and left the hash unchanged. If we later need padding inside a document, GDN has to handle it too.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 24s —— View job


Request changes: checkpoint resume diverges from step 9 with no known cause, and the new resume test can't catch it. Also open: @liangel-02's question on padding in the PLE hash, plus a design question for maintainers on the DTensor-based PLE. See the 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: Request changes -- checkpoint resume diverges from uninterrupted training for an unknown reason, and the new resume test can't catch it. A maintainer also needs to sign off on the DTensor-based PLE design.

What this PR does. It adds Qwen3.8-Flash-Next as a new model folder that reuses Qwen3.5's GDN and vision code. On top of that it adds four gated residual streams, a hashed n-gram embedding (PLE), and QSA sparse attention on Attention Gym gather_attn / lightning_indexer, plus an HF state dict adapter. The 51.2B-row PLE table is a Shard(0) DTensor over DP. FSDP skips it, and lookups are routed to the row owners with all-to-all (torchtitan/distributed/row_sharded_embedding.py). A recipe helper sets up DistMuon + AdamW + Adam(PLE) optimizer groups.

Example. Two DP ranks each own half of an 8-row table:

rank0 requests ids [6,1,6] -> unique [1,6] -> id 1 to rank0, id 6 to rank1
rank1 returns E6; rank0 expands it -> [E6,E1,E6]
backward: dE6 (sum of 2 rows) goes back to rank1, dE1 stays on rank0; the table is never all-gathered

Must fix

  1. tests/integration_tests/b200.py:219 -- the resume test never compares trajectories, while the README admits resume diverges from step 9 (inline). Root-cause the divergence, then make the test fail on it.
  2. torchtitan/models/qwen3_8_flash_next/embedding.py:225 -- @liangel-02's padding comment is unanswered. hash_ids ignores padding_mask_T, so a pad ID inside a document enters the hashes of the next ngram_size - 1 tokens. The conv taps at L337-349 also count pad positions. QSA handles the same case by compacting to valid tokens (attention.py:147-182), so the two halves of one model treat padding differently. No in-repo data source produces padding inside a document today (packer, MM collator and RL batcher all pad at the end of a document), so current runs are unaffected. Either compact PLE to valid tokens the way QSA does, or reject padding inside a document and drop that claim from the QSA code and the description.
  3. tests/integration_tests/models.py:13 -- revert the blank-line-only change (inline).

Should consider

  • torchtitan/models/qwen3_8_flash_next/attention.py:329 -- per-layer nonzero/bincount syncs; compute them once in QSAIndexMetadata.from_inputs (inline).
  • torchtitan/models/common/moe/moe.py:195 -- keep the gate-type widening in FlashNextRouter.Config instead of changing the shared router (inline).
  • tests/unit_tests/cpu/models/common/test_flops_estimators.py:39 -- the new row is a self-snapshot, not a value preserved from main (inline).
  • torchtitan/models/qwen3_8_flash_next/state_dict_adapter.py:218-243 -- from_hf checks layout state in one direction only. If complete HF shards arrive after a DTensor to_hf, the full table is passed to DTensor.from_local(run_check=False) as if it were one rank's shard. Raise when owned != (layer_id in self._ngram_weight_layouts).
  • torchtitan/models/qwen3_8_flash_next/embedding.py:176-178 -- ple_layer_index, seed and split_ngram_parts have defaults that no flavor overrides. split_ngram_parts is only read by the adapter. Hardcode the first two and move the third onto the adapter.
  • torchtitan/models/qwen3_8_flash_next/README.md:133-152 -- the logit-by-logit parity story and the offline comparison tables belong in the PR description. The README should describe current state.

Questions (for maintainers)

  • direction.md says not to add DTensor-specific code in new features. Here the PLE table is built with DTensor.from_local, read with .to_local in forward, and has DTensor branches in the adapter. To keep FSDP away from it, an FSDP unit is created whose only parameter is ignored (model.py:173-181). The stated payoff is reusing clipping, optimizers and DCP unchanged. Is that the accepted exception, or should this use spmd_types (the token dispatcher already does typed variable-split spmd.all_to_all, token_dispatcher.py:298-406)?
  • row_sharded_embedding.py + ROW_SHARDED_EMBEDDING.md go into shared distributed/ with a single consumer. The rules say to start in the model folder. Keep it shared, or move it under qwen3_8_flash_next/?
Details

Necessity gate. The problem is real: main can't build or load this model, and plain FSDP would all-gather a 95 GiB BF16 table. Row ownership plus all-to-all is a reasonable minimal answer. The gate passes, apart from the two design questions above.

Resume divergence. Ruled out as causes:

  • expert bias: load_balance_coeff is unset, so there is no expert_bias_E;
  • AuxLoss accumulators: non-persistent and metrics-only;
  • PLE hash buffers: recomputed deterministically;
  • LR schedule: total_steps=10 in both halves.

Remaining candidates are dataloader window-shuffle state and an optimizer-state mismatch that stays below stdout precision for the first post-resume steps (inline). Both are unverified.

Checked, no issue found.

  • row_sharded_embedding.py:
    • split order in forward and the reverse path;
    • duplicate-ID gradient accumulation via F.embedding(inverse);
    • HSDP: the flattened dp rank order matches (Shard(0), Shard(0)) over (dp_replicate, dp_shard), so each row has exactly one owner and there is no double reduction.
  • The per-microbatch .cpu().tolist() host sync is acknowledged and planned for removal.
  • Adapter: Q/gate and GDN head interleaving and PLE fragment offsets.
  • norm.py and residual.py don't duplicate existing modules.

Not verified: whether resume divergence comes from the dataloader or the optimizer; HF-writer merging of PLE parts split across ranks when DP doesn't divide 128; GPU numerics claims in the description. A maintainer still needs to review: this PR touches models/common/moe and distributed/.

Comment on lines +219 to +231
IntegrationTestDefinition(
configs=[
qwen38_flash_next_debugmodel_mm_checkpoint_save,
qwen38_flash_next_debugmodel_mm_checkpoint_load,
],
test_descr=(
"Qwen3.8-Flash-Next FSDP, EP, image fusion, PLE, sparse attention "
"and checkpoint resume"
),
test_name="qwen3_8_flash_next_fsdp",
ngpu=2,
use_real_pg=True,
),

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 entry only checks that the save run and the load run finish. It has no golden_numerics_path and no trajectory comparison. The model README (TODO at line 159) says resumed training diverges from uninterrupted training at step 9, so this test passes on a known resume bug and would also pass on any future one.

Per CLAUDE.md, checkpoint resume must reproduce uninterrupted numerics. Please root-cause the divergence first, then make this test fail on it, either by comparing the load run's steps 6-10 against an uninterrupted golden or with golden_numerics_path as kimi_k3_mm_muon does above.

Two leads (unverified):

  • The fixture uses streaming_shuffle_buffer_size=128 (Grain window shuffle). If its iterator state is restored incorrectly, the first few post-resume batches can still match and divergence shows up only after the window refills. That fits "matches through step 8, differs from step 9".
  • Compare the TensorBoard values bitwise. Stdout's 5 significant digits can hide a step-6 optimizer-state mismatch (DistMuon momentum with bf16 compute layouts, or the PLE Adam state on the row-owned table) until it grows large enough to see.

Disabling the shuffle buffer and diffing model, optimizer and dataloader state saved vs. loaded at step 5 should separate the two.

Comment thread tests/integration_tests/models.py Outdated
training process, so it must stay importable from this module.
"""


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 is a drive-by change: the file's only edit is an added blank line. Please revert it.

Suggested change

Comment on lines +329 to +335
valid_U = valid_T.nonzero().flatten()
starts_U = starts_T[valid_U]
new_document_U = F.pad(starts_U[1:] != starts_U[:-1], (1, 0), value=True)
document_U = new_document_U.cumsum(0) - 1
tokens_N = torch.bincount(document_U)
cu_seqlens = F.pad(tokens_N.cumsum(0), (1, 0)).int()
cu_seqlens_k = F.pad((tokens_N // self.compress_ratio).cumsum(0), (1, 0)).int()

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.

valid_T.nonzero() and torch.bincount(document_U) (no minlength, so its size depends on the data) run in every QSA layer, on every forward and again on recompute. Each one is a device-to-host sync. Their inputs depend only on QSAIndexMetadata, which already calls nonzero in from_inputs (lines 159-162).

Compute valid_U, document_U, cu_seqlens and cu_seqlens_k once in from_inputs and store them on the metadata. That leaves one sync per microbatch instead of one per QSA layer per pass, and it shrinks what the planned static-shape PR has to rework.

Comment thread torchtitan/models/common/moe/moe.py Outdated
class Config(Module.Config):
num_experts: int
gate: HiMidLoLinear.Config
gate: Linear.Config

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 widens the shared router contract (FP32 gate logits) for every MoE model, but only Flash-Next needs it. Every other caller (deepseek_v3/v4, gpt_oss, kimi_k3, muse_spark, config_utils.make_router_config) still passes HiMidLoLinear.Config, so their numerics don't change. However, the shared comment no longer states the FP32 guarantee those models rely on.

FlashNextRouter.Config already exists. Overriding gate: Linear.Config there (with the pyrefly ignore used elsewhere in this PR) would keep this change inside the model folder and leave moe.py untouched.

Separately (unverified): Flash-Next's router gate is now a plain Linear. Check that float8/MX converters don't quantize it unless they filter it out by FQN.

Comment on lines +39 to +50
@@ -46,7 +47,7 @@ def _build(family, flavor="debugmodel", **kwargs):
],
)
def test_text_estimates_preserve_main(family, flavor, expected):
# Values recorded from main before introducing the shared estimator.
# Values recorded before migrating these models to the shared estimator.

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.

test_text_estimates_preserve_main protects estimates recorded on main before the shared-estimator migration. 57_128_736 is instead a snapshot of the new model's own output, and the comment was reworded so the new row fits.

The new row adds no regression protection. Drop it and restore the original comment.

@shuhuayu

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @shuhuayu's task in 3m 19s —— View job


Needs discussion: all earlier must-fix items are resolved; only the maintainer decision on the DTensor-based PLE table remains. See the review.

Comment on lines +124 to +130
all_to_all_single(
local_vectors_MD,
metadata.input_splits,
metadata.output_splits,
metadata.row_mesh,
)
)

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.

would we have the max_cta problem again when world size is large?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

i suspect not. here is a big all to all per microbatch, but in distmuon, we are doing small all to all per bucket. so reusing the fsdp cta limit sounds fine to me.

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.

The problem is on memory, not on communication time, right?

FSDP doesn't need Omega(N) where N is world size, it only needs O(1) because all-gather & reduce-scatter only talks to neighbors.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

correct. on large dp groups, this memory usage will be in Omega(N) for all to all. but if it is a big all to all, small cta can make it bandwidth bound. added a TODO for this. will followup later.

@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-1-model branch 2 times, most recently from 57f6956 to f5fe541 Compare November 19, 2026 00:22
@shuhuayu

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @shuhuayu's task in 3m 45s —— View job


Request changes: @tianyu-l's comments are all addressed, but the new windowed indexer scoring can crash training on valid multimodal data. See the 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: Request changes -- @tianyu-l's comments are all addressed, but the new windowed indexer scoring trusts rope.max_context_length as a bound on document length. That bound doesn't hold for multimodal documents, so a device-side assert can kill training on valid data.

What this PR does. It adds Qwen3.8-Flash-Next on top of Qwen3.5's GDN and vision code: gated residual streams, a hashed n-gram embedding (PLE) whose table is a Shard(0) DTensor over DP, QSA sparse attention on Attention Gym, and an HF adapter. This re-review covers the squashed 5e080bb against @tianyu-l's 11-17 review and my 11-13 review.

Example (the new failure).

125B-A6B (multimodal), seq_len=4096, 16K-token rows (the shapes in attention.py:329-330)
document = 8000 tokens, mostly image placeholders; MRoPE positions stay < 4096
query near token 8000 selects a block near token 0 -> the chunk spans ~2000 blocks
window = ceil((1024 + 4095) / 4) = 1280 -> _assert_async fires -> CUDA device assert, job dies

Resolved since the last review

  • @tianyu-l, explicit backward collective: _OwnerLookup now spells out the reverse all-to-all and builds the DTensor gradient locally. This also settles my open DTensor-vs-spmd_types question: the table stays a DTensor and its collectives are explicit.
  • @tianyu-l, mesh choice: the table is on the dense SPMD mesh, and the dp_replicate/dp_shard remapping is gone. clip_grad_norm_ groups gradients by mesh, so the extra mesh is handled.
  • @tianyu-l, the manual RNG init and requires_grad=False wrapper: removed; the table uses DTensor init.
  • @tianyu-l, router dtype and its source of truth: Float32Softmax/FlashNextRouter removed; it uses the shared make_router_config with FP32 logits. The description's parity table reflects this.
  • @tianyu-l: Identity norm now has a comment; early break added; residual.py folded into model.py; the helpers are private; local_spmd is documented and limited to PLE and the indexer; the all-to-all memory TODO was added; load resharding is deferred to #6054.
  • @tianyu-l, merging row_sharded_embedding.py into embedding.py: you declined with a reason (module vs. lookup protocol), and there has been no pushback yet.
  • My earlier suggestion: QSA metadata is now required, and the fallback arguments are gone.

Must fix

  1. torchtitan/models/qwen3_8_flash_next/attention.py:271 -- the window bound comes from rope.max_context_length, which bounds MRoPE positions but not a document's token count (inline). Either drop the windowing here and land it with #6053, or compute the bound from cu_seqlens in QSAIndexMetadata.from_inputs. The windowing is also missing from the PR description.

Should consider

  • torchtitan/models/qwen3_8_flash_next/row_sharded_embedding.py:200-204 -- the to_local() outside the Function only reads a shape, and the checks repeat invariants _parallelize already enforces (inline).
  • torchtitan/models/qwen3_8_flash_next/ROW_SHARDED_EMBEDDING.md:52 -- still says the lookup "uses ordinary autograd" (inline).
  • torchtitan/models/qwen3_8_flash_next/attention.py:352 -- the torch._assert_async TODO has no upstream issue link. This goes away if the windowing is dropped.

Not verified: GPU numerics and the description's performance claims; whether DCP resume is unchanged after moving the table from the FSDP storage mesh to the dense SPMD mesh, which only the B200 integration test covers. A maintainer still needs to review.

Comment on lines +269 to +271
# Documents restart positions at 0, so none spans more tokens than RoPE
# covers; this bounds how far back a query's candidate blocks reach.
self.max_context_length = config.rope.max_context_length

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.

The window bound assumes no document has more tokens than rope.max_context_length. That holds for text, where the 1D RoPE cache lookup bounds positions. It does not hold for the multimodal flavors, and 125B-A6B is multimodal. MultiModalCollator._build_mrope_positions gives each image or video one grid of 3D positions, so the temporal position advances by much less than the number of placeholder tokens. A document's token span can therefore exceed max_context_length while every rotary position stays inside the cache.

Concrete case, from the shapes in the comment at L329-330: seq_len=4096, 16K-token rows, one image-heavy document of 8000 tokens with MRoPE positions under 4096. A query near token 8000 can select a block near token 0, so the chunk spans about 2000 blocks, but window = ceil((1024 + 4095) / 4) = 1280. The _assert_async at L354 then fires. On CUDA that is a device-side assert, which kills the job partway through training, on valid data.

This windowing is also new since the last review and isn't in the PR description. In this PR it only runs when seq_len is smaller than the packed row: the integration fixture uses seq_len=1024 with 1024-token rows, so window >= num_blocks there and the path never runs. Smallest fix: drop the windowing from this PR and land it with the 125B recipe in #6053, where it is measured. If you keep it, bound the window by the real maximum document length. QSAIndexMetadata.from_inputs already host-syncs on cu_seqlens, so it can compute that bound, or window itself, once per microbatch instead of reading it from the RoPE config. Either way, the chunk_size comment at L239-240 ("for any packed-row length") needs the same correction.

Comment on lines +200 to +204
local_shape = weight_RD.to_local().shape
if len(local_shape) != 2 or local_shape[0] != metadata.num_local_rows:
raise ValueError("weight_RD must contain exactly this owner's row shard")
if weight_RD.device != metadata.local_row_ids.device:
raise ValueError("weight_RD and routed IDs must be on the same device")

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.

nit: weight_RD.to_local() runs here, outside _OwnerLookup, only to read a shape. On the requires-grad parameter it records an unused autograd node on every forward, which is the DTensor autograd path this PR just moved into the Function.

The two checks guard invariants that NGramTable._parallelize already establishes: rows divisible by DP, and num_local_rows derived from the same table and mesh. Principle 8 says not to add checks "just in case". Either drop them and read the feature width from weight_RD.shape[1], or move them into _OwnerLookup.forward, which already calls to_local().


Collectives sum gradients without mesh-size division. The caller normalizes
the loss and keeps weights fixed through accumulated microbatches. The helper
uses ordinary autograd; optimizer updates happen after backward. Gradients

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.

Stale: since the switch to _OwnerLookup, the lookup no longer "uses ordinary autograd". State the current contract instead: an autograd.Function whose backward runs only the reverse all-to-all, and which builds the DTensor gradient locally.

@shuhuayu

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @shuhuayu's task in 2m 10s —— View job


Approve -- my last must-fix was wrong: multimodal datasets already drop samples longer than max_context_length tokens, so the windowed indexer bound holds. The other earlier items are fixed. See the 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 -- my last must-fix was wrong: the data pipeline already caps multimodal documents at max_context_length tokens, so the windowed indexer bound holds. The other items from that review are fixed. A maintainer still needs to review.

What this PR does. It adds Qwen3.8-Flash-Next on top of Qwen3.5's GDN and vision code: gated residual streams, a hashed n-gram embedding (PLE), QSA sparse attention on Attention Gym, and an HF adapter. The PLE table is a Shard(0) DTensor over DP. Lookups go to the owning rank by all-to-all, and the backward collective is written out in an autograd.Function. This re-review covers c3c9065.

Example (the windowing bound, now verified).

125B-A6B, seq_len=4096, 16K-token packed rows, chunk_size=1024, R=4
mm_datasets.py:336 and :595 drop any sample with len(input_ids) > max_context_length
  (image/video placeholders count as tokens), and trainer.py:244 / :304 pass
  config.model.max_context_length = seq_len = rope.max_context_length
-> no document exceeds 4096 tokens -> a chunk's selected blocks span < ceil((1024+4095)/4) = 1280 ids

Resolved since the last review

  • attention.py:334 windowing: valid. My earlier 8000-token image-heavy document can't reach the model. _filter_overlong_sample and the packing-path filter both count tokens, not MRoPE positions, against the same max_context_length the RoPE cache uses. Text packing splits long documents at that length. The validator builds its loader with the same value. The comment at L269-273 and the description now state this contract, and the _assert_async catches any producer that breaks it. test_qsa_selection_matches_document_local_block_oracle[windowed=True] runs the windowed path on CPU.
  • row_sharded_embedding.py: the to_local() and the redundant shape/device checks outside _OwnerLookup are gone.
  • ROW_SHARDED_EMBEDDING.md:52: it now describes the autograd.Function with the reverse all-to-all as the only backward collective.
  • @tianyu-l's 11-20 point on all-to-all memory growing as Omega(DP): a TODO is at the collective, and the description lists it under known issues.
Details

I couldn't fetch the earlier squashed revision, so this pass re-read the areas the last review flagged plus the indexer teacher (attention.py:491-552):

  • Padding J to a multiple of 8 only appends masked slots after the B * R block slots, so block max-pooling is unchanged.
  • Masked logits equal finfo.min exactly, and a fully masked row contributes zero after * valid_TJ.
  • Each windowed index_select uses distinct indices, so its backward has no colliding adds.

Not verified: the GB300 numerics and performance figures in the description, and the baddbmm(out_dtype=...) path, which only runs on CUDA.

@tianyu-l tianyu-l 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.

looks great

Comment on lines +101 to +114
@local_compile("gated_residual", batch_invariant=True)
def _read_streams(
read_logits_TC: torch.Tensor, x_norm_TC: torch.Tensor, num_streams: int
) -> torch.Tensor:
"""Average the streams weighted by their sigmoid read gates."""
read_TSD = read_logits_TC.sigmoid().unflatten(-1, (num_streams, -1))
return (read_TSD * x_norm_TC.unflatten(-1, (num_streams, -1))).mean(-2)


@local_compile("gated_residual", batch_invariant=True)
def add_residuals(
update_TD: torch.Tensor, residual_TC: torch.Tensor, write_TS: torch.Tensor
) -> torch.Tensor:
return residual_TC + (update_TD.unsqueeze(-2) * write_TS.unsqueeze(-1)).flatten(-2)

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.

let's put these two functions as (static) methods into the class where they are consumed, if they are not used by other classes

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

moved.

routing=ple_routing,
padding_mask_T=padding_mask_T,
)
x_TC = x_TC + replicate_to_residual(update_TC)

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.

#5740 is going to land soon, please see if rebase onto the idea helps

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

it is good idea, if it lands before this i will rebase otherwise will followup.

Comment on lines +29 to +40
# The report specifies eight Polar Express iterations; coefficients are from
# https://github.com/liangyuwang/FSDP-Canzona/blob/426e8c50363cc3401e64eeb80c9e6e2451ea2ed4/matrix_based_optimizer/optimizers/muon.py
_POLAR_EXPRESS_COEFFICIENTS = (
(8.2051, -22.9019, 16.4607),
(4.0664, -2.8612, 0.5184),
(3.9096, -2.8234, 0.5250),
(3.2856, -2.4153, 0.4853),
(2.2779, -1.6198, 0.3985),
(1.8726, -1.2307, 0.3585),
(1.8564, -1.2132, 0.3568),
(1.8750, -1.2500, 0.3750),
)

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.

hmm interesting that different models use different coefficients -- would love to learn more offline

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

i guess this is from model specific finetune from some static baselines.

Qwen3.8-Flash-Next extends Qwen3.5 with four gated residual streams, Qwen
Sparse Attention (QSA) and a hashed n-gram embedding (PLE). This adds the
model, its HF state dict adapter, the report's optimizer policy, FSDP and EP.

- Model (torchtitan/models/qwen3_8_flash_next/): Qwen3.5 GDN, vision and
  lifecycle reused; gated residual streams; document-local hashed PLE; QSA on
  Attention Gym gather_attn with lightning_indexer block selection and the
  no-grad indexer teacher (the indexer scores each query chunk only
  against the blocks its documents can reach, since the data pipeline caps
  documents at max_context_length); text (Qwen38FlashNextModel) and multimodal
  (Qwen38FlashNextMultimodalModel) classes; the shared TokenChoiceTopKRouter.
- Row-sharded PLE (row_sharded_embedding.py): the table is a DTensor on the
  dense SPMD mesh (Shard(0) on dp, replicated on cp/tp), excluded from FSDP
  all-gathers; lookups route unique IDs, vectors and gradients to their DP row
  owners through an autograd.Function with an explicit backward.
- Optimizer recipe (torchtitan_recipes/models/qwen3_8_flash_next.py): DistMuon
  for decoder linear maps, AdamW for embeddings, head, router, gates, norms and
  vision, Adam for PLE.
- HF parity script (scripts/checkpoint_conversion/): text, vision and
  image/video forward/backward with exact expert and token selections; logits
  gated against an FP32 copy of the reference.
- qwen3_8_flash_next_fsdp in the B200 suite: FSDP2 + EP2, save and resume.
- Mechanical: public Qwen3.5 config factory names.
@shuhuayu
shuhuayu merged commit a4c9ffb into main Nov 21, 2026
30 of 31 checks passed
shuhuayu added a commit that referenced this pull request Nov 21, 2026
…6047)

## Summary (human-written)

add cudagraph support for attention metadata. 

## Why

Stacked on #6046 (1/n).

Flash-Next cannot run with accelerator (CUDA) graphs. Capture needs
fixed shapes and no host synchronization, and QSA breaks both on 1/n:

- `QSAIndexMetadata.from_inputs` calls `nonzero` and `bincount`. Their
output sizes depend on the batch, so each call synchronizes with the
host; capture fails with `cudaErrorStreamCaptureUnsupported` at
`valid_T.nonzero()`.
- The number of complete blocks G, the number of valid tokens U and the
number of documents change every batch, so the metadata passed into the
graph changes shape and cannot be refreshed in place. `QSAIndexer` also
scatters `_select_blocks` results back with `blocks_TB[valid_indices_U]
= ...`, another U-shaped op.

**Example.** Two batches of T=256 tokens, block size R=4: documents
`(100, 156)` with the last 20 tokens padded, then `(40, 60, 70, 86)`
with 8 padded tokens inside the second document.

| | Batch 1 | Batch 2 |
| --- | --- | --- |
| 1/n: complete blocks G (`block_indices_GR` rows) | 59 | 61 |
| 1/n: `cu_seqlens` entries | 3 | 5 |
| This PR: `block_indices_GR` rows (T // R) | 64 | 64 |
| This PR: `cu_seqlens_N` entries (T + 1) | 257 | 257 |

After this PR every metadata tensor has a shape that depends only on T,
so a graph captured on batch 1 replays batch 2 after copying batch 2's
metadata into the same buffers. This is exactly the new GPU test.

## What changed

All logic changes are in
`torchtitan/models/qwen3_8_flash_next/attention.py`.

- `QSAIndexMetadata` (still built once per microbatch and required by
`QSAIndexer.forward`, as in 1/n) now has only T-sized fields:
- `block_indices_GR` has `T // R` rows. Complete blocks fill the first
rows; the remaining rows are inactive and point at the first valid
token. They lie outside every document's candidate range, so they are
never selected.
- `valid_indices_T` is a fixed-length compaction of the valid tokens
(first U entries are token indices, the rest zero), built with
`scatter_` instead of `nonzero`. `valid_T`, `compact_T` and `document_T`
map between token order and compacted order.
- `cu_seqlens_N` / `cu_seqlens_k_N` have `T + 1` slots, the most
documents a microbatch can hold; unused slots repeat the valid-token
count. Attention Gym's `lightning_indexer` only binary-searches the
offsets per token, so the spare slots cost nothing and no document
capacity has to be configured.
- SPMD annotations: per-token fields use the shared
`token_id_placement()`; offsets stay rank-local.
- `QSAIndexer._select_blocks` runs `lightning_indexer` over the
compacted tokens with those offsets and gathers results back to token
order (`compact_local_TB[compact_T]`, masked by `valid_T`) instead of
scattering. `lightning_indexer` handles this layout directly: repeated
offsets, offsets ending before T, inactive candidates.
- Comment-only: `QSAInnerAttention` explains which ranks take the
empty-sum branch now that ranks with fewer than R tokens are the only
ones without block slots.
- New GPU test
`tests/unit_tests/gpu/models/qwen3_8_flash_next/test_qsa_graph.py`,
added to the B200 workflow (one line in
`.github/workflows/integration_test_b200.yaml`).

## User-facing changes

| Before | After |
| --- | --- |
| Accelerator-graph capture fails in QSA (`nonzero`) | QSA captures and
replays with changing document layouts |
| QSA selection width `min(token_budget / R, G)` | `min(token_budget /
R, T / R)`; unused slots are `-1` |
| `QSAIndexMetadata` fields `valid_indices_U`, `document_U`,
`cu_seqlens`, `cu_seqlens_k` | `valid_T`, `document_T`, `compact_T`,
`valid_indices_T`, `cu_seqlens_N`, `cu_seqlens_k_N` (internal to the
model) |

No config changes.

## Numerics

Selections and gradients are unchanged when a batch has T/R complete
blocks. Otherwise the block pool grows from G to T/R rows, which changes
the shape of the dense indexer-score GEMM and `lightning_indexer` and
thus only rounding.

All rows below were measured at an earlier revision of the stack (before
1/n switched to the shared fp32 `TokenChoiceTopKRouter` and moved the
PLE table to `spmd_dense_mesh`). The QSA-layer and kernel checks do not
involve the router or PLE; the end-to-end runs do.

| Check | Result |
| --- | --- |
| Released 125B QSA layer forward+backward, T=4096, one GB300 | Output,
input gradient and every parameter gradient bitwise equal to 1/n |
| Old vs new code in float64 on CPU, with padding | Agree to `7.7e-16` |
| Fused CuTe indexer on GB300, `T + 1` offsets vs exact-length offsets,
20 random 4096-token layouts | Bitwise identical selections |
| Debug recipe, one GB300, 10 steps | Loss and gradient norm identical
to 1/n at every step |
| FSDP2/EP2 multimodal integration, two GB300s, 10 steps | Steps 1-8
identical to 1/n; steps 9-10 differ by `7.5e-4` loss |

The step-9/10 difference is the larger block pool: padding only 1/n's
block pool to T/R rows reproduces the new trajectory exactly (step-10
loss `3.04579`, gradient norm `5.2072`, measured at an earlier
revision), and widening only the selection reproduces 1/n exactly. No
golden loss files cover Flash-Next.

## Testing

- New GPU test `test_indexer_graph_replay_refreshes_document_layout`
(SM90+, runs in the B200 workflow): captures the debug indexer
forward+backward on the batch-1 layout above, copies the batch-2 layout
into the same buffers, replays, and requires selections, loss and
parameter gradients equal to eager on batch 2 (`atol=rtol=0`,
deterministic algorithms). It guards the static-shape invariant, which
nothing else checks: capture fails on any host sync, and replay is wrong
if any metadata shape depends on the captured batch. On 1/n, the
graph-enabled debug recipe fails at capture in `valid_T.nonzero()`.
- Flash-Next CPU tests and the FSDP2/EP2 integration test (SPMD
typechecking, checkpoint save at step 5 and resume) pass (run at an
earlier revision).
- Downstream evidence from 6/n heads measured today, which carry this
PR's static-shape QSA metadata (pre-rebase copy of this commit): the
graph-enabled Dist-MoE debug config
`qwen38_flash_next_debugmodel_fsdp2_ep2_pp2` (FSDP2+EP2+PP2, 4 GB300s,
seed 42, deterministic) passes, and the released 125B recipe with graphs
trains on 16 GB300s (FSDP16+EP16).

```bash
python -m pytest tests/unit_tests/cpu/models/qwen3_8_flash_next -q
python -m pytest tests/unit_tests/gpu/models/qwen3_8_flash_next -q
python -m tests.integration_tests.run_tests outputs/flash_next_integration \
  --test_suite b200 --execution_mode real_pg --ngpu 2 \
  --test_name qwen3_8_flash_next_fsdp
```

## Known issues / follow-ups

- PLE row-sharded routing still synchronizes with the host under
FSDP/EP; 3/n (#6052) makes it fixed-capacity. The end-to-end
accelerator-graph test lands in 4/n (#6053).

## Stack

1. #6046 (1/n): Flash-Next model, DTensor PLE, FSDP/EP, optimizer
policy, QSA indexer performance.
2. **#6047 (2/n, this PR)**: static-shape QSA metadata and selection.
3. #6052 (3/n): fixed-capacity PLE row-sharded routing.
4. #6053 (4/n): the released 125B-A6B recipe and an accelerator-graph
test (also registers `LinearAttentionMetadata` for graph replay).
5. #6054 (5/n): tensor/sequence parallelism.
6. #6055 (6/n): pipeline parallelism.
shuhuayu added a commit that referenced this pull request Nov 21, 2026
… slots (#6052)

## Summary (human-written)

add cudagraph support for row-sharded ple table.

## Why

Stacked on #6047 (2/n).

After 2/n, PLE row-sharded routing is the remaining blocker for
accelerator graphs under FSDP. On 2/n, `prepare_row_sharded_embedding`
deduplicates with `torch.unique`, copies per-owner counts to the host
(`splits.cpu().tolist()`), and passes per-batch `input_splits` /
`output_splits` lists into `_OwnerLookup`, whose forward and backward
all-to-alls are sized by them. The routing tensors change shape every
batch, and the split lists are non-tensor inputs that change every
batch, so graph replay is impossible. The host copy also synchronizes
every step.

**Example.** Eight-row table, two owners (rows 0-3 and 4-7), `C=2`,
requests `[6,1,6]`.

```
2/n:  unique [1,6], splits [1,1] copied to host  -> shapes follow the data
3/n:  slots  [[1,-],[6,-]]   (request exchange [P, C+1], last column = validity flag)
      owner 0 reads local rows [1,0], owner 1 reads [2,0]
      requester gathers [E6,E1,E6]; the unused slots (local row 0) are never selected
```

Every batch exchanges the same shapes, with equal splits.

## What changed

- `prepare_row_sharded_embedding(..., max_ids_per_owner=C)`
(`row_sharded_embedding.py`): every requester sends each owner a fixed
slot of `C` distinct IDs. Dedup is a stable sort plus a first-occurrence
mask instead of `torch.unique`; per-owner counts stay on the device and
only feed the validity flag. The request exchange is `[P, C + 1]` with
equal splits. Owners receive `[P*C]` local row IDs; unused slots point
at local row 0, and `inverse_indices` never selects them.
- Validation: each requester appends a flag (all IDs in `[0,
num_embeddings)` and at most `C` distinct IDs per owner) to every
owner's slot. Owners check the received flags with `torch._assert_async`
after the exchange, so invalid input still fails on every owner, now
asynchronously instead of as a host-side `ValueError` before the
exchange. `max_ids_per_owner < 1` raises `ValueError`.
- `RowShardedEmbeddingMetadata` drops `input_splits` / `output_splits`
and is registered with `torch.export.register_dataclass`, so graph input
copying refreshes its tensors on replay.
- `_OwnerLookup` (the `torch.autograd.Function` from 1/n) loses its two
split-list arguments: forward and the hand-written backward both use
equal-split `all_to_all_single(..., None, None, row_mesh)` over `[P*C,
D]`. Otherwise unchanged: forward does the owner `F.embedding` lookup
and the response all-to-all; backward does the reverse all-to-all,
`aten.embedding_backward` in the weight dtype, and `DTensor.from_local`
with the weight's placements; the `spmd_typecheck` hook is renamed to
the `Q` (`P*C`) suffix. Unused slots get zero gradient. This part is
mechanical.
- Flash-Next derives `C` from its hash layout
(`NGramEmbedding.max_ids_per_owner(T, num_owners=P)` in `embedding.py`,
called from `model.py`). Each of the 16 hash heads owns a contiguous row
range and each token reads one ID per head, so an owner receives at most
`min(T, overlap)` distinct IDs from each head, where `overlap` is how
many of the head's rows it owns. `C` is the largest per-owner sum, which
depends only on the table layout and `T`.
- Docs (skim): `ROW_SHARDED_EMBEDDING.md` and the model README describe
the slots, the traffic table below and the equal-`C` requirement.

## User-facing changes

| Before | After |
| --- | --- |
| `prepare_row_sharded_embedding(ids, num_embeddings=, row_mesh=)` |
adds required `max_ids_per_owner=` (at least 1) |
| Host synchronization in every step's routing; graph replay impossible
| No host synchronization; fixed shapes and equal splits |
| Invalid IDs raise `ValueError` on every owner before the exchange |
Invalid IDs or capacity overflow fail an async `RuntimeError` assertion
on every owner after the request exchange |

`max_ids_per_owner` must be equal on every rank of the row mesh, because
the equal-split exchanges are sized from the local value; a mismatch
mis-sizes the exchange instead of raising. Flash-Next derives it from
the table layout and `T`, which packing fixes to the configured tokens
per microbatch on every rank.

## Cost

Each rank exchanges `P*C` slots per direction; on 2/n it sent only its
distinct IDs, at most `16*T` (one per hash head per token). `P*C /
(16*T)` is the new traffic relative to that old worst case, for the
released table (same numbers as the README table):

| Row owners | `C` at `T=4096` | `P*C / (16*T)` | `C` at `T=16384` |
`P*C / (16*T)` |
| --- | ---: | ---: | ---: | ---: |
| DP8 | 8,604 | 1.05 | 33,180 | 1.01 |
| DP16 | 4,508 | 1.10 | 16,796 | 1.03 |
| DP64 | 4,508 | 4.40 | 16,796 | 4.10 |

The released recipe (#6053) runs DP16 at 16K tokens per rank: 1.03x.
Beyond DP16 several owners split one hash head and each reserves a slot
for every token, so traffic grows with `P`. No recipe uses DP64 today,
and it was not measured.

Eager A/B on the released model, 125B-A6B, 16 GB300s, DP16 + EP16, 16K
tokens per rank, HF checkpoint, averages over steps 3-30 (measured at an
earlier revision, before 1/n switched to the shared fp32 router and
moved the PLE table to `spmd_dense_mesh`):

| | Without this PR (2/n + the #6053 recipe) | With this PR (#6053) |
Full stack (#6055) |
| --- | ---: | ---: | ---: |
| tps / GPU | 3,931 | 3,971 | 3,958 |
| TFLOPS / GPU | 166.6 | 168.3 | 167.8 |
| Peak memory (GiB) | 163.9 | 163.8 | 164.6 |

No regression: throughput was 0.7-1.0% higher with the fixed slots,
close to run-to-run variation (about 0.3% between identical configs),
and peak memory was unchanged. A profile of that configuration (also an
earlier revision, with a bound twice as loose) showed the PLE vector
exchange at about 0.3 ms per call, three calls per step (forward,
recompute, backward), out of a step of about 4 s.

At the current stack, the graphed 125B recipe (16 GB300, FSDP16 + EP16,
Dist-MoE, 8x16K) with the current `_OwnerLookup` runs at 378.8 TFLOPS /
GPU and 243.59 GiB peak, steps 4-30 (measured on an earlier 6/n head,
bfdb1ad02, which includes this PR; no same-day A/B without it).

## Numerics

No arithmetic change: each owner still sums the same requester
contributions in the same order; unused slots add exact zeros.

| Check | Result |
| --- | --- |
| Four-rank CPU/Gloo lookup vs dense reference: values, accumulated
gradients, AdamW state, duplicate IDs, BF16 cancellation, empty
requesters, int32, recompute, full and unused slots | Exact
(`atol=rtol=0`) |
| FSDP2/EP2 multimodal integration, two GPUs, 10 steps (measured at an
earlier revision) | Loss and gradient norm identical to 2/n at every
step |
| Full stack debug configs (seed 42, deterministic): FSDP2+TP2+SP+EP2
typechecked; FSDP2+EP2+PP2 with Dist-MoE + graphs | Pass; identical on
every printed digit across the `_OwnerLookup` and `spmd_dense_mesh`
revisions |

## Testing

- `test_row_sharded_embedding.py`: the dense-reference test uses the
tightest valid bound (`max_ids_per_owner=2`, equal to rows per owner),
so each microbatch fills one owner's slots and leaves an unused slot for
the other. `test_invalid_routing_fails_on_entire_row_group` (renamed
from `test_invalid_ids_fail_on_entire_row_group`) checks that
out-of-range IDs (`-1`, `4`) and capacity overflow (two distinct IDs,
one slot) raise on every owner. Catches: routing that silently drops or
mis-slots IDs, and invalid input failing on only some ranks (a hang).
- Flash-Next CPU unit tests and the FSDP2/EP2 integration (SPMD
typechecking, checkpoint save and resume) pass.
- With non-blocking HybridEP on FSDP2/EP2, CUDA sync debugging over a
full training step reported no synchronization inside forward/backward
(only the trainer's step logging remains); on 2/n, routing synchronized
three times per step (measured at an earlier revision).

```bash
python -m pytest tests/unit_tests/cpu/models/qwen3_8_flash_next/test_row_sharded_embedding.py -q
python -m pytest tests/unit_tests/cpu/models/qwen3_8_flash_next -q
python -m tests.integration_tests.run_tests outputs/flash_next_integration \
  --test_suite b200 --execution_mode real_pg --ngpu 2 \
  --test_name qwen3_8_flash_next_fsdp
```

## Known issues / follow-ups

- Traffic grows with `P` beyond DP16 (table above); not a concern for
the released DP16 recipe.
- The response all-to-all keeps NCCL buffers for every DP peer, so its
memory grows with DP (TODO in `_OwnerLookup.forward`, carried from 1/n).

## Stack

1. #6046: Flash-Next model, DTensor PLE (`_OwnerLookup`, table on
`spmd_dense_mesh`), FSDP/EP, optimizer policy, QSA indexer performance.
2. #6047: static-shape QSA metadata and selection (document offsets
always have `T + 1` slots).
3. **This PR (#6052)**: fixed-capacity PLE row-sharded routing.
4. #6053: the released 125B-A6B recipe and an accelerator-graph test.
5. #6054: tensor/sequence parallelism.
6. #6055: pipeline parallelism.
shuhuayu added a commit that referenced this pull request Nov 21, 2026
#6053)

## Summary (human-written)

add recipe with kernel overrides

## Why

Stacked on #6052 (3/n).

After 2/n (static QSA) and 3/n (fixed-capacity PLE routing), Flash-Next
forward/backward has no host synchronization and no batch-dependent
shapes when expert dispatch is CPU-free, so a step can be captured and
replayed as one accelerator graph. Nothing guards that: a later change
that adds a `.tolist()` or a data-dependent shape would only show up
when someone turns graphs on. There is also no recipe for the released
125B-A6B model.

**Example.** On the debug model with FSDP2 + EP2 and Dist-MoE, step 3
captures forward/backward and step 4 replays it with a different
document layout. A host sync fails capture (before 2/n:
`cudaErrorStreamCaptureUnsupported` at `valid_T.nonzero()`). Metadata
passed into the graph but not registered as a pytree fails graph input
validation at step 4. Replay reading stale state that is not a graph
input is not caught until the test has a golden (see Known issues).

## What changed

**Recipe and flavor**
- `qwen38_flash_next_125b_dist_moe` in
`torchtitan_recipes/models/qwen3_8_flash_next.py` fine-tunes the
released decoder from its HF checkpoint on 16 GB300s:
- FSDP16 + EP16 (all 512 experts, 32 per rank, in one NVLink domain)
with Dist-MoE, and PLE rows over DP16.
- 2M tokens per step: 8 packed 16K-token microbatches per rank
(documents split at the model's 4K context). This is the per-GPU work of
a 33.5M-token step on 256 GPUs.
- Full remat, the model's `local_compile` regions, and forward/backward
as one accelerator graph.
- `max_num_documents=64`, because graph replay needs a fixed document
capacity (twice `c4_document_capacity`'s 16K estimate).
- Dist-MoE activation slot 0.5: about the first half of the MoE layers
keep their expert intermediates instead of recomputing them (decided per
layer on device), +2.9% throughput for ~45 GiB. Factor 1.0 (~94 GiB)
reached 264 GiB and thrashed the allocator. Saving whole GDN blocks from
remat bought ~1% for 31.6 GiB and is not used.
- Two overrides, below: the fused gated residual read and the fused QSA
indexer teacher. The indexer KL coefficient is 1.0; the comment explains
it only matters through global gradient clipping.
- 30 steps at a small learning rate, for throughput measurement; a real
run sets `training.steps` and the schedule.
- `125B-A6B-text` flavor: the released decoder without the vision
encoder, loaded from the multimodal checkpoint. With `125B-A6B`, the
encoder runs a dummy forward on text batches every step for no training
signal.

**Fused gated residual read (opt-in override, enabled by this recipe)**

Every sublayer reads its four residual streams through `GatedResidual`,
97 calls per forward. Two parts were slow at 125B shapes (T = 16K, C = 4
x 2560, rank 320):
- `hc_norm`'s compiled backward fuses the input gradient into the
weight-gradient sum over tokens, a column-major loop over 16K rows (0.73
ms per call).
- `inject`'s `[10240 -> 4]` GEMM is too narrow for a fast kernel (sm80
CUTLASS), and `down` and `inject` each produce an `x_norm` gradient that
autograd adds.

```text
x_TC -> hc_norm -> x_norm -+-> down   [10240 -> 320]  -> mix = silu(down / 4) -> up -> read -> mixed
                           +-> inject [10240 -> 4]    -> write = 2 sigmoid(inject / 4)
                           +-> read

module:   hc_norm (compiled) + separate down / inject GEMMs     2.56 ms  (one call, fwd+bwd, graph replay)
override: hc_norm (Triton)   + one [down | inject] GEMM          1.52 ms
```

- `torchtitan_recipes/overrides/flash_next_grouped_rms_norm.py`:
`GroupedOffsetRMSNorm` as Triton kernels with a hand-written backward
(input gradient row by row; weight gradient as per-chunk partials summed
afterwards, deterministic). Wrapped as a `torch.library.custom_op` with
fake and autograd registrations so it traces and graph-captures.
- `torchtitan_recipes/overrides/flash_next_gated_residual.py`:
`FusedGatedResidual`, `@override(target=GatedResidual.Config)`. `down`
and `inject` run as one `F.linear` over their concatenated weights,
padded to a 16-row multiple (324 -> 336) for cuBLAS. `up` and the stream
read are unchanged. Parameters and checkpoint keys are unchanged. Config
validation rejects a `Linear` subclass, a bias, or an `hc_norm` other
than a plain `GroupedOffsetRMSNorm`, since `forward` reads their weights
directly.

**Fused QSA indexer teacher (opt-in override, enabled by this recipe)**

The indexer's KL target is the head-mean softmax over each query's
selected tokens, max-pooled per block. The model's
`QSAInnerAttention._teacher` gathers a `[Q, J, H_kv, K]` key copy,
writes fp32 logits and runs a separate softmax: 18.8 ms per layer per
microbatch at 125B shapes (16K tokens, J = 2051). `gather_attn` already
computes the softmax normalizer, so each token's probability `exp(S -
lse_h)` does not depend on the rest of the selection.

```text
per 64-query tile, per 128-key tile of its window:
    S = scale * Q_h @ K_g^T               # per head h, KV head g = h // group
    sums += exp(S - lse_h)                # head sum, fp32
teacher[q, b] = max over block b's tokens of sums[q, token] / H   -> [T, B]
```

- `torchtitan_recipes/overrides/flash_next_qsa_teacher.py`:
`FusedTeacherQSAInnerAttention` asks `gather_attn` for the log-sum-exp
and runs one Triton kernel densely per 64-query tile against the context
window before it (tensor-core GEMMs, skipping key tiles before the
tile's first selected token), then gathers and max-pools the selected
blocks: 1.4-2.2 ms depending on document lengths. The override targets
`QSAAttention.Config` (not the inner attention) to read the indexer's
RoPE context, which bounds each tile's window. Same parameters (none)
and attention output; only the KL target is computed differently. Its
`forward` mirrors `QSAInnerAttention.forward` except for the LSE request
and the teacher call. A TODO notes the teacher is generic to sparse
attention with an indexer teacher and belongs in Attention Gym.

Reviewers can read the three override files separately from the recipe.

**GDN in_proj split (model code, every flavor)**

Flash-Next's GDN `in_proj` is a `SplitLinear` (q|k|v projection GEMM,
z|a|b gates GEMM). `SplitLinear` interleaves the two outputs per key
head into the single-`Linear` layout only for the shared `GDN` to split
them again:

```text
projection  [q0 k0 v0 | q1 k1 v1]
gates       [z0 a0 b0 | z1 a1 b1]
SplitLinear [q0 k0 v0 z0 a0 b0 | q1 k1 v1 z1 a1 b1]    <- copy skipped
GDN split   mixed_qkv [q0 q1 | k0 k1 | v0 v1], z, a, b
```

- `torchtitan/models/qwen3_8_flash_next/gdn.py`: `SplitInProjGDN`, a
`GDN` subclass in the model folder, builds `mixed_qkv`, `a`, `b` and the
gate straight from the two GEMM outputs (in a `gdn_split_in_proj`
local-compile region). This removes a ~540 MB copy and its backward
split per layer call. The shared `GDN` is unchanged.
- `flavors.py` builds Flash-Next's linear-attention layers as
`SplitInProjGDN.Config` via `derive`; same parameters, so HF checkpoint
loading is unchanged.

**Graph test**
- B200 integration test
`qwen3_8_flash_next_dist_moe_fsdp_ep_accelerator_graph`: FSDP2 + EP2
with row-sharded PLE, Dist-MoE and full remat; step 3 captures, step 4
replays. Replay uses a new document layout, so the test fails on any
host synchronization or batch-dependent shape. It has no golden loss
file yet (see Known issues). SPMD typechecking is off, with a TODO,
because Dist-MoE does not register its autograd functions with it;
`qwen3_8_flash_next_fsdp` typechecks the model with the default
dispatcher. The test's debug config enables neither override.
- A text-only `qwen38_flash_next_debugmodel` test config
(`torchtitan_recipes/tests/models/qwen3_8_flash_next.py`) backs the
graph test.
- The B200 workflow's pytest list adds the QSA teacher override's GPU
test.

**Mechanical (skim)**
- `gdn.py`: the split helpers are private static methods of
`SplitInProjGDN`.
- Model README: the 125B recipe (416 TFLOP/s per GPU, 16.7% MFU, under
forced round-robin routing), Dist-MoE under EP, and the graph test.

No library code changes outside the model folder, `torchtitan_recipes/`,
the tests, and the one-line registration.

## Alternatives considered

- **HybridEP instead of Dist-MoE.** Blocking HybridEP has per-layer host
syncs, so it can't run under graphs. Non-blocking HybridEP pads expert
buffers to capacity factor 1.0 (every token to every local expert) and
was 1.5x slower than eager.
- **Compile the whole `GatedResidual.forward` as one region.** The
forward got 0.43 ms faster, but Inductor's backward got 0.42 ms slower,
for the same column-loop reason.
- **Fully fused residual kernels** (norm folded into per-stream
projection GEMMs, `up` with a Triton read epilogue, custom backward):
316.7 TFLOPS against 321.3 (measured at an earlier revision), in about
560 lines.
- **Change `GatedResidual` itself.** That changes eager numerics and
goldens for every Flash-Next config; as an override it stays opt-in.
- **QSA teacher with one query per program** (selected keys gathered per
query): 4.3 ms per layer per microbatch, against 1.4-2.2 ms dense.
- **Change the shared `GDN` or `SplitLinear`.** Only Flash-Next uses the
split `in_proj`; a subclass in the model folder keeps shared code
untouched.

## User-facing changes

| Before | After |
| --- | --- |
| No released-model recipe | `qwen38_flash_next_125b_dist_moe` (16
GB300s, 2M tokens per step, Dist-MoE + graphs) |
| Only `125B-A6B` (with vision encoder) | Adds `125B-A6B-text` |
| No Flash-Next overrides |
`torchtitan_recipes.overrides.flash_next_gated_residual.fused_gated_residual`
(and `...flash_next_grouped_rms_norm.fused_grouped_offset_rms_norm` for
the norm alone),
`torchtitan_recipes.overrides.flash_next_qsa_teacher.fused_qsa_teacher`
|
| Flash-Next GDN layers are `GDN` | `SplitInProjGDN` (same parameters
and checkpoint keys, bitwise-identical numerics) |
| Flash-Next graph capture/replay untested | B200 FSDP2 + EP2 Dist-MoE
graph test (capture and replay; golden to follow) |

## Performance

125B-A6B, 16 GB300s, FSDP16 + EP16, Dist-MoE + graphs, full remat, 2M
tokens per step, activation slot 0.5, HF checkpoint. Mean over steps
4-30, peak memory max over ranks.

Current stack (with 1/n's shared fp32 router and PLE table on
`spmd_dense_mesh`):

| Routing | TFLOPS / GPU | Peak memory |
| --- | ---: | ---: |
| Natural | **378.6-379.0** | 243.59 GiB |
| Forced round-robin | 416.4 | 243.89 GiB |

Per-optimization deltas (measured at an earlier revision, before 1/n's
router change; torch nightly 20261118):

| Step | Natural routing | Round-robin |
| --- | ---: | ---: |
| Fused gated residual read | 304.8 -> 321.3 | |
| Fused QSA teacher (after 1/n's indexer window) | 335.1 -> 369.4 | |
| GDN in_proj split | 369.4 -> 378.5 | 406.0 -> 418.2 |
| Final (at that revision) | 378.5 (15.14% MFU), 243.4 GiB | 418.2
(16.73% MFU), 243.8 GiB |

The GDN split left peak memory unchanged. For reference, the earlier
eager blocking-HybridEP recipe ran at 168.3 TFLOPS (6.73% MFU) with one
16K microbatch per step.

## Numerics

- Graph replay runs the same kernels as eager. On two GB300s with FSDP2
+ EP2 and Dist-MoE, graphs and eager matched bitwise in loss and
gradient norm over 4 steps, (measured at an earlier revision, before the
GDN split moved into model code and the 1/n router switch).
- The GDN split is bitwise: a GPU unit test compares outputs and all
gradients against the shared `GDN` (eager and compiled region), and the
debug model's loss, grad_norm and indexer loss matched the shared `GDN`
bitwise over 10 steps (seed 42, deterministic).
- The gated residual override is not bitwise: the merged GEMM and the
Triton norm change summation order. Its output and every gradient stay
at or below the eager module's error against an fp64 golden (measured at
an earlier revision):

| Tensor (T = 16K, bf16, rel. L2 vs fp64) | Eager module | Override |
| --- | ---: | ---: |
| mixed / write | 3.38e-3 / 1.80e-3 | 3.38e-3 / 1.80e-3 |
| d x | 3.76e-3 | 3.38e-3 |
| d hc_norm.weight / d Wd / d Wu / d Wi | 3.74e-3 / 5.07e-3 / 5.11e-3 /
4.18e-3 | 3.37e-3 / 5.07e-3 / 5.11e-3 / 3.84e-3 |

125B loss at step 30 tracked the run without it: 2.27436 vs 2.27435
(earlier revision).
- The QSA teacher override is not bitwise: relative error against an
fp64 golden 1.52e-7 vs 1.21e-7 for the model's teacher. 125B loss at
step 30: 2.27438 vs 2.27436 (earlier revision).
- Current stack, 125B natural routing: loss 2.34428-2.34429 at step 1
and 2.27433-2.27437 at step 30. The 125B recipe is not run-to-run
bitwise (~1e-4 in loss, up to 5e-3 in grad_norm between runs of the same
math); the debug configs are.
- Goldens are unaffected by the overrides because no golden config
enables them.

## Testing

```bash
python -m tests.integration_tests.run_tests outputs/flash_next_b200 \
  --test_suite b200 --execution_mode real_pg --ngpu 2 \
  --test_name qwen3_8_flash_next_dist_moe_fsdp_ep_accelerator_graph
pytest tests/unit_tests/gpu/recipes/test_flash_next_gated_residual_override.py \
  tests/unit_tests/gpu/recipes/test_flash_next_qsa_teacher_override.py \
  tests/unit_tests/gpu/models/qwen3_8_flash_next/test_gdn.py
```

- The graph test passed, along with the other Flash-Next B200 tests and
the CPU tests, before the GDN split moved into model code; it has not
been rerun on B200 since.
- `test_flash_next_gated_residual_override.py` (new) bounds the
override's error against an fp64 golden by 2x the eager module's error
(plus the dtype's rounding floor): output and all gradients, with and
without `inject`, at 256 and 257 tokens; a second case covers the norm
alone with leading dims and a non-power-of-two group size. It catches a
wrong hand-written backward or a broken `[down | inject]` split.
- `test_flash_next_qsa_teacher_override.py` (new, SM100; added to the
B200 workflow's pytest list, since the A10G GPU job skips it) bounds the
fused teacher's error against an fp64 golden by 2x the model teacher's
error, over mixed document lengths that straddle the 64-query tiles, and
checks that padding rows (no selected tokens) get zeros.
- `test_gdn.py` (new) compares `SplitInProjGDN` against the shared `GDN`
bitwise (outputs and all gradients), eager and with the
`gdn_split_in_proj` region compiled. It catches a q/k/v or z/a/b slice
that disagrees with the shared split, e.g. after a `SplitLinear`
head-layout change.
- The recipe ran for 30 steps on 16 GB300s at the current stack (numbers
above). Loading the 125B HF checkpoint still works (~320-345 s).

## Known issues / follow-ups

- The graph test has no golden loss file yet. A golden checked bitwise
against the same config run eagerly would also catch replay reusing
stale state; until now the B200 lane stopped at its pytest step on main
(`test_dist_moe.py::test_eager_dist_moe_recipe_supports_accelerator_graphs_with_pipeline_parallelism`),
so no integration test ran to produce it. #6263 fixed that test on
2026-11-20; the golden follows once the lane runs again. TODO in the
test. The earlier golden was removed because 1/n's router switch changed
this test's numerics.
- The stack is rebased onto main, which already registers
`LinearAttentionMetadata` as a pytree dataclass (#5680), so this PR no
longer carries that change.
- The gated residual override expects bias-free plain `Linear`
projections and raises otherwise.
- TP/SP layouts are not exercised with the overrides; the 125B recipe
does not use TP. 5/n (#6054) adds the QSA teacher override's TP path
with the model's.
- The QSA teacher kernel belongs in Attention Gym next to `gather_attn`
(TODO in the code).

## Stack

1. #6046: Flash-Next model, DTensor PLE, FSDP/EP, optimizer policy, QSA
indexer performance.
2. #6047: static-shape QSA metadata and selection.
3. #6052: fixed-capacity PLE row-sharded routing.
4. **This PR (#6053)**: the released 125B-A6B recipe, fused gated
residual and QSA teacher overrides, the GDN in_proj split, and an
accelerator-graph test.
5. #6054: tensor/sequence parallelism.
6. #6055: pipeline parallelism.
shuhuayu added a commit that referenced this pull request Nov 21, 2026
## Summary (human-written)

add tp/sp. 

## Why

Stacked on #6053 (4/n).

Flash-Next rejects TP at config time. TP needs model-specific pieces
beyond the shared decoder sharding:

1. QSA's indexer teacher is a max-pool over blocks of the head-mean
attention probability. With heads sharded, pooling each shard first
computes a different target: max(mean over all heads) is not the mean of
per-shard maxes.
2. The indexer is TP-replicated, so its KL gradient would be counted TP
times.
3. PLE's table, owned by DP rows since 1/n, also needs TP column
ownership.
4. Several Flash-Next sharding declarations only typecheck for TP + SP
and text-only inputs.

**Example.** Two heads, one block of two tokens, head probabilities
`h0=[0.9,0.1]` and `h1=[0.1,0.9]`. The true teacher is `max([0.5,0.5]) =
0.5`. Pooling per TP shard and then averaging gives `(0.9+0.9)/2 = 0.9`.

## What changed

- **QSA teacher** (`QSAInnerAttention._teacher`): for each query chunk,
each rank divides its head-probability sum by the global head count,
all-reduces across TP, then max-pools blocks, so peak memory stays per
chunk as before. The KL contribution is scaled by `1/TP` in backward,
since the TP-replicated indexer's gradients are summed over TP ranks.
DeepSeek-V4's compressor uses the same two patterns; TODOs at both sites
point to sharing them (the scale belongs in `AuxLoss`).
- **4/n fused teacher override** (`flash_next_qsa_teacher.py`): same TP
path. `qsa_teacher` takes `num_global_heads` and returns the unpooled
per-token probabilities `[T, num_blocks * compress_ratio]`;
`_fused_teacher` all-reduces them over TP (when TP > 1) and then
max-pools. The indexer KL gets the same `1/TP` scale.
- **PLE table**: its `ngram_table_sharding` weight placement goes from
`{dp: S(0), tp: R}` to `{dp: S(0), tp: S(1)}`, i.e. DP-row x TP-column
owned. TP ranks hold the same token IDs (PLE runs TP-replicated), so
only DP ranks exchange IDs and vectors, at the local feature width;
`NGramEmbedding` then redistributes the looked-up vectors `S(2) -> R`
over TP. `NGramTable` already builds the weight as a DTensor on
`spmd_dense_mesh` with placements read from the sharding config (1/n),
so the column shard needs no mesh code. With TP and DP=1, `NGramTable`
uses the size-1 `dp_shard` mesh as its row mesh. The
`row_sharded_embedding` docstring now says D is the local feature width.
- **TP with or without SP**: TP-unsharded weights read by the residual
stream (the gated residuals' grouped `hc_norm` and mixer linears) take
the TP type of their input via `_unsharded_param_placement`: `I` without
SP, `R` with SP, as the shared `norm_sharding_config` does.
- **Multimodal flavors**: like Qwen3.5 (`qwen3_5/model.py`), the
multimodal forward declares the fused embeddings' DP x CP token sharding
(`spmd.assert_type`) before `replicate_to_residual`, which otherwise
fails typechecking under TP.
- **Text-only embeddings** run in the global SPMD context. Inside
`spmd_local_context("dp")`, the SP-scattered embedding recorded only
`(tp)` on the token dimension and lost its DP shard, so with DP > 1 the
first block failed typechecking. Only the multimodal vision path still
uses the DP-local context.
- **`SplitLinear`** unflattens gates by their fixed per-group width. The
SPMD checker reads a size passed to `unflatten` as global; the
projection's local group count is not, so FSDP2 x TP2 failed
typechecking in `cat`.
- **Config validation** (`build_model_config`): TP must divide the QSA
KV heads (2 in every flavor, so TP 1 or 2). PP still raises.
- **DistMuon**: the Flash-Next DistMuon policy raises `ValueError` under
TP, since DistMuon does not support TP storage layouts until #5678
(TODO).
- Mechanical / skimmable: README TP/SP row, docstring updates.

## User-facing changes

| Before | After |
| --- | --- |
| `tensor_parallel_degree > 1` raises | TP works, with or without SP,
for text and multimodal flavors, when TP divides the 2 QSA KV heads |
| DistMuon policy under TP: fails inside the optimizer | `ValueError` at
config time, TODO pointing to #5678 |

## Numerics

TP=1 is unchanged: the teacher runs the same ops (the all-reduce and the
`1/TP` scale are skipped; the fused override pools the same tensor it
pooled before), the TP placements only matter when TP > 1, and the
global-context embedding runs the same ops.

Fresh initialization under TP depends on the PLE table's mesh: DTensor
RNG offsets depend on the layout, so DP2, DP4, DP2 x TP2 and HSDP give
different tables (each distinct per owner). Loss at step 1 therefore
differs between layouts that don't load the same checkpoint.

The runs below used local configs that are not part of this PR (it adds
no recipe or integration entry), at earlier revisions, before TP without
SP and multimodal TP were enabled:

| Check (GB300, deterministic, seed 42) | Result |
| --- | --- |
| FSDP2 x TP2 + SP x EP2 debug model (typechecked, 4 GPUs, AdamW), 10
steps | Step 1 loss 7.76143 / grad norm 9.4439, step 5 6.63181, step 10
5.60357 / 3.465 |
| Resharding save/resume: FSDP4 x EP2 steps 1-5, then load at FSDP2 x
TP2 + SP x EP2, steps 6-10 | Load finished with no missing-key or
optimizer warnings; step 6 5.58456 / grad norm 4.4042, step 10 5.26044 |
| FSDP2 x EP2 (2 GPUs) vs FSDP2 x TP2 + SP x EP2 (4 GPUs), AdamW, same
seed checkpoint and global batch, 10 steps | Step 1 loss 7.732883 vs
7.733495 (+6.1e-4), grad norm 9.29617 vs 9.28646 (-1.0e-3 relative);
steps 2-10 within 6.0e-3 loss and 1.4e-2 relative grad norm, no
systematic offset |
| TP2 + SP x EP2 with Dist-MoE, accelerator graphs vs eager, 4 steps |
Loss and grad norm bitwise equal |

A wrong `1/TP` indexer scale or a doubled PLE gradient reduction would
show as a systematic grad-norm offset in the TP vs no-TP comparison.

TP without SP and multimodal TP were checked on fake process groups with
SPMD typechecking (FSDP2 x TP2 x EP2, fused teacher, 5 steps each): text
without SP, multimodal with and without SP, plus the existing text TP +
SP and multimodal FSDP2 x EP2 layouts as regression checks. They have
not run on GPUs.

## Testing

- CPU:
`test_qsa_teacher_sums_tp_head_shards_and_scales_indexer_gradient` runs
two simulated head shards (mocked TP all-reduce) against the unsharded
teacher. It guards the order (all-reduce before pooling) and the `1/TP`
indexer gradient scale, which a TP run's loss alone would not reveal.
- GPU (SM100): `test_teacher_matches_golden_with_and_without_tp_split`
checks the fused kernel's per-KV-head probabilities, summed then pooled,
against the golden teacher.
- This PR adds no integration entry. Real-GPU TP coverage in CI comes
from #6055's `qwen3_8_flash_next_fsdp_tp_sp_ep_pp` (FSDP2 + TP2 + SP +
EP4 + PP2, text, AdamW).

```bash
python -m pytest tests/unit_tests/cpu/models/qwen3_8_flash_next -q
python -m pytest tests/unit_tests/gpu/recipes/test_flash_next_qsa_teacher_override.py -q
```

## Known issues / follow-ups

- No CI covers TP without SP or multimodal TP, and no test checks a
resume that reshards the PLE table across TP.
- DistMuon under TP waits on #5678.
- TODOs: share the TP head-sum reduction and the `1/TP` scale with
DeepSeek-V4's compressor (the scale belongs in `AuxLoss`).

## Stack

1. #6046: model. 2. #6047: static QSA. 3. #6052: fixed-capacity PLE
routing. 4. #6053: 125B recipe + accelerator-graph test. 5. **#6054: TP
+ SP (this PR).** 6. #6055: pipeline parallelism.
shuhuayu added a commit that referenced this pull request Nov 21, 2026
…_config

#6164 deleted ModelConfigConverter, validate_converter_compatibility and
the converters argument of every build_model_config. The Flash-Next stack
(#6046-#6054) landed after it with CI from the older base, so
qwen3_8_flash_next/flavors.py still imports them and fails at import time.
Remove the import, the argument and its loop, as #6164 did for the other
models; no Flash-Next caller passes converters.
sdmyzlp pushed a commit to sdmyzlp/torchtitan that referenced this pull request Nov 21, 2026
…_config

pytorch#6164 deleted ModelConfigConverter, validate_converter_compatibility and
the converters argument of every build_model_config. The Flash-Next stack
(pytorch#6046-pytorch#6054) landed after it with CI from the older base, so
qwen3_8_flash_next/flavors.py still imports them and fails at import time.
Remove the import, the argument and its loop, as pytorch#6164 did for the other
models; no Flash-Next caller passes converters.
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
```
tianyu-l pushed a commit that referenced this pull request Nov 21, 2026
…_config (#6314)

## Summary (human-written)

as titled. 

## Why

`main` fails to import Flash-Next. #6164 deleted `ModelConfigConverter`,
`validate_converter_compatibility` and the `converters` argument of
every `build_model_config`. The Flash-Next stack (#6046-#6054) merged
about 2.5 hours later, but its CI had run against the older base, so
`torchtitan/models/qwen3_8_flash_next/flavors.py` still imports the
deleted names.

**Example.**

```
$ python -c "import torchtitan.models.qwen3_8_flash_next"
ImportError: cannot import name 'ModelConfigConverter' from 'torchtitan.config.transform'
```

On `main` (65e88e9) this breaks:
- CPU Unit Test: the 4 Flash-Next CPU test modules fail to collect;
- 1 GPU and Multi-GPU Unit Tests: the Flash-Next GPU test modules fail
to collect;
- lint: pyrefly `missing-module-attribute` at
`qwen3_8_flash_next/flavors.py:19-21`.

## What changed

- `qwen3_8_flash_next/flavors.py`: remove the import, the `converters`
argument of `build_model_config` and its loop, as #6164 did for the
other 13 models. No Flash-Next caller passes `converters`; recipes apply
transforms with `apply_transforms`.

## Numerics

None: the removed branch ran only when `converters` was passed, and no
caller passed it.

## Testing

- `pytest tests/unit_tests/cpu` (with `main`'s attn-gym pin): all
Flash-Next tests pass. The 12 failures are in `test_loss`,
`test_dist_moe`, `test_lora` and `qwen3_5`; the same 12 fail in this
environment on `main` before the Flash-Next stack (31d93fe), so they
come from the local environment, not this change.
- Pyrefly reports no errors in `qwen3_8_flash_next/flavors.py`.

## Known issues / follow-ups

- #6055 (6/n, pipeline parallelism) needs a rebase onto `main` with this
change.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI 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.

3 participants