Skip to content

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

Closed
shuhuayu wants to merge 11 commits into
pytorch:mainfrom
shuhuayu:qwen3-8-fn-02-model
Closed

shuhuayu wants to merge 11 commits into
pytorch:mainfrom
shuhuayu:qwen3-8-fn-02-model

Conversation

@shuhuayu

@shuhuayu shuhuayu commented Nov 3, 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

Based on main, which includes the merged GDN determinism prerequisite #5784. Depends on #6017 (Attention Gym pin 0d0197fb) for gather_attn separate values and grouped fused kernels.

TorchTitan cannot build or load Qwen3.8-Flash-Next on main. The architecture extends Qwen3.5 with four gated residual streams, QSA and 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.

What changed

  • Reuse Qwen3.5 GDN, vision and lifecycle; implement gated residual streams, document-local hashed PLE, QSA block selection and HF-compatible checkpoint conversion.
  • Add distributed/row_sharded_embedding.py: public PyTorch functional collectives route sorted unique IDs, vectors and gradients. The table is a Shard(0) DTensor on the dense storage mesh. Existing clipping and native DCP handle it; HF fragments use the public CheckpointableTensor coordinate fields. Export gathers no table rows.
  • Run QSA attention through Attention Gym gather_attn: the selected blocks and the incomplete tail are sparse KV indices into the packed sequence (no sliding window), 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. The no-grad indexer teacher is unchanged.
  • Select QSA blocks with Attention Gym lightning_indexer, as in DeepSeek-V4, instead of ranking every complete block per query. It runs over valid tokens with per-document offsets in valid-token space, so its candidates are exactly the document-local blocks even with padding inside a document. Selected blocks are sorted ascending; their KL scores keep the previous math (dense GEMM per checkpointed chunk, then a gather).
  • Store GDN/QSA projections and gates as two ordinary Linear modules and interleave their outputs per head. This permits separate optimizers without a concatenated weight copy or custom autograd. The output interleave retains saved child outputs for selective remat.
  • Put the report optimizer policy in torchtitan_recipes/models/qwen3_8_flash_next.py, consumed by the small text/MM fixtures. DistMuon handles decoder linear maps; AdamW handles embeddings, head, router, GR, gates, decay/beta, norms, convolutions and vision; Adam with zero weight decay handles PLE. BlockShard separates Q/K/V heads; native expert dimensions separate gate/up matrices.
  • Build optimizer layouts from recipe parallelism. Post-init validates EP layout agreement and raises on a mismatched override; it never rewrites the optimizer. Model config requires exactly one PLE layer. PLE master gradients are independent of backbone FSDP reduction dtype.
  • Simplify HF parity from 956 to 651 lines: text, standalone vision and image/video forward/backward, with the same fixtures and tolerance bounds, parameter/input gradients, and exact expert/token selections.
  • Mechanical: public Qwen3.5 factory names and router gate typing; rename residual addition; fold router dtype handling and rotary rounding into model/attention files; remove the two small files and checkpoint-schema JSON; consolidate FSDP+EP integration coverage in the multimodal fixture. Generic lookup docs describe its contract; Qwen-specific rationale, precision and capacity live in the model README.

Muon uses the existing DistMuon API: Nesterov momentum 0.95, eight Polar Express iterations, epsilon 1e-14 and 0.2 * sqrt(max(rows, columns)) scaling. Assignment follows report section 3.1; coefficients follow the published schedule. Debug learning rates and batches suit the reduced training fixtures.

User-facing changes

Before After
Flash-Next cannot be built or loaded Debug/released flavors, HF adapter, FSDP and EP.
Ordinary FSDP gathers an embedding table DP row owners exchange selected vectors and gradients.
Fused QKV/gates share an optimizer parameter Separate native Linear parameters; per-head Muon projection updates.
PLE receives backbone optimizer settings Dedicated Adam group with zero weight decay.
QSA would need per-chunk gathers and MATH SDPA (~10 s forward+backward per layer at T=4096) Fused gather_attn: 3.3 ms per layer on GB300.

Numerics

Checkpoint schema revision: de4b8e4d43b917e7706784d8bb445c9af86a3540; Transformers: 494470d677d05d44153d235d795e0d01040307ab. HF parity uses a reduced model initialized by HF and loaded through the adapter.

Check Hardware Result
Projection/gate head order and reassembled parameter gradients, FP32 CPU GDN and QSA match the fused oracle bitwise.
HF text and image/video forward/backward GB300 Existing bounds pass; gradient cosine 0.999923 text and 0.999946 multimodal; expert IDs and selected-token masks match exactly.
Standalone HF vision, FP32 GB300 Maximum output error 3.35e-7; gradient cosine exceeds 0.999999999999.
C4, FSDP2/EP2, 50 steps Two GB300s Prior convergence evidence: loss 7.772286415100098 -> 3.0675439834594727; loss and gradient norms finite.
CC12M fixture, FSDP2/EP2, 10 steps Two GB300s Loss 7.7723836898803711 -> 3.0521817207336426; loss and gradient norms finite; SPMD typechecking enabled.

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
Previous chunked MATH SDPA 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 debug model (two GB300s, seed 42, 10 steps) matches the previous implementation to about 1e-3 in loss at every step (step 10: 7.49278 vs 7.49127). 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 the previous argsort ranking:

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, as the previous stable ranking did, independent of later candidates; otherwise the choice among cutoff ties is backend-defined. On CPU, Attention Gym's reference uses torch.topk, so the former CPU tie-order test is removed. Indexer forward+backward: 51 ms vs 64 ms. Debug model (two GB300s, seed 42, 10 steps): step-1 loss identical, later steps within 2e-3 (step 10: 7.49411 vs 7.49278).

Offline comparisons across parallelisms

These comparisons, the HF parity rows above and the checkpoint-resume qualification below were measured with the previous chunked MATH-SDPA QSA and argsort selection (before c3d743ff0) and have not been rerun on the Attention Gym kernels.

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 evaluation/training logits, CE, MoE/indexer objectives, all parameter gradients reconstructed through their DTensor placements, token-embedding and image/video input gradients, and the native global gradient norm. Expert IDs and QSA token selections match exactly.

Comparison against unsharded QSA query chunk Max logit error Gradient norm ratio Gradient cosine
Text, FSDP2/EP1 1 0 1.000013080 0.999997670
Text, FSDP2/EP2 1 0 1.000013071 0.999997676
Image/video, FSDP2/EP1 16 0 0.999941820 0.999996484
Image/video, FSDP2/EP2 16 0 0.999941815 0.999996487

All four cases pass the existing bounds: logits atol=1/256, rtol=1/128; parameter/input gradient RMS and maximum errors atol=1e-4, rtol=1/32; CE atol=rtol=2e-4. Logit probability KL is zero, and top-1/top-5 sets agree exactly. There are 198 text and 239 multimodal logical parameter gradients per case.

The inputs contain two real packed documents per logical rank, so both layouts use the same shared GDN varlen path. Text uses one query per QSA chunk to keep MATH SDPA batch shapes identical. With default 16-query chunks, the first text microbatch has maximum logit error 0.0078125 and 96/159744 entries exceed the HF script's forward bound. The first difference is two BF16 elements in QSA output, with bitwise-identical Q/K/V and ordered selections; both outputs pass an independent FP64 attention oracle. The default-chunk gradients pass their bounds (norm ratio 0.999910545, cosine 0.999982893). These diagnostic results are retained, and qualification tolerances are unchanged.

Artifacts in the local 1/n worktree: outputs/test_review_20261109_01a1b222/verification_summary.json, offline_parity_packed/text/comparison_qsa1.json, offline_parity_packed/mm/comparison.json, and offline_parity_packed/text/qsa_rounding_oracle.json. Matrix-specific harnesses, checkpoints and logs remain generated outputs.

Training uses seed 42 and strict determinism. Mixed optimizers and split parameter initialization change the training trajectory. Separate GEMMs can change BF16 gradients relative to fused computation; HF tolerances are unchanged. The 1,627-key HF name/shape inventory, including 128 PLE parts, is unchanged.

Validated model source: 578e9757e72960743e46c368b112c3a5b9491f58 plus the current test/recipe/README changes. Rebased revision: 35d853ff02f4001821c061129274f0e2ae47c314, based on upstream main baf7cf9b01c2d6161909ef839a13f90fe99d7533. The model implementation is unchanged by this revision. Runtime: PyTorch 2.16.0.dev20261108+cu132 (1392e1f8e4903657d4391f3bd8fcc9ca8a74b758), Attention Gym 0.0.19.dev10+g26beb363c. The gather_attn revision was validated with Attention Gym 0.0.19 at 0d0197fb.

Rebase validation on two GB300s: the ten-step multimodal FSDP2/EP2 recipe (seed 42, strict determinism) reproduces every full-precision TensorBoard loss and gradient norm bitwise versus 62aaef7fa. All six 1/n patches are unchanged in git range-diff. Lint and all 56 targeted CPU tests pass. Artifacts: outputs/rebase_main_20261110_01a1b222/numerics.json and range_diff.txt.

Checkpoint resume qualification uses the same two GB300s, seed 42, strict determinism and SPMD typechecking. At step 5, all model parameters and optimizer tensors, including both owners' PLE rows and Adam moments, restore bitwise; the next inputs match bitwise too. The first resumed backward differs only in vision gradients (maximum 2.98e-8); decoder and PLE gradients match bitwise. Across ten steps, the maximum restart-versus-uninterrupted differences are loss 1.8000602722167969e-4 and gradient norm 5.269050598144531e-4, first visible in scalars at step 9. A fresh uninterrupted control reproduces the prior ten-step loss and gradient norm bitwise. Artifacts: outputs/pr1_checkpoint_resume_01a1b222/verification_summary.json, checkpoint_tensor_comparison.json and control_comparison.json.

Testing

  • Grouped normalization now honors offset_rmsnorm with the Qwen3.5 decorator settings. CPU FP32/BF16 checks verify bitwise forward/backward results with the region disabled and Inductor execution when enabled; five focused PLE/indexer cases pass. CPU tests cover gradients with no complete blocks, while the multimodal integration does not explicitly force that imbalance across ranks.
  • All-file pre-commit run --all-files, including typechecking: pass. The validation runtime uses isolated stubs for optional dependencies.
  • 54 targeted CPU tests: pass (20 model, 2 distributed lookup, 32 shared AuxLoss/MoE). The reviewed model file is reduced from 49 to 18 parametrized cases. It keeps head-ordering, BF16 normalization/router rounding, document/hash boundaries, PLE convolution/gradients, sparse selection and attention backward, indexer-only gradients, HF roundtrips/inventory, and block-to-MoE padding-mask wiring. Shared tests cover AuxLoss accumulation/reset/replay and MoE padding semantics.
  • Four offline unsharded/FSDP/EP comparisons: pass with real NCCL communication, as detailed above.
  • Four-rank CPU/Gloo lookup tests cover routed values, accumulated gradients, optimizer updates, global clipping and native checkpoint resharding against a dense reference.
  • The existing two-GPU multimodal integration passes FSDP2/EP2 with SPMD typechecking: train steps 1-5, save a full native DCP checkpoint, explicitly load step 5 and continue through step 10. It uses the same CI entry and two GPUs, with a ten-step LR schedule across both stages.
python -m pytest tests/unit_tests/cpu/models/qwen3_8_flash_next \
  tests/unit_tests/cpu/distributed/test_row_sharded_embedding.py \
  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 models --execution_mode real_pg --ngpu 2 \
  --test_name qwen3_8_flash_next_fsdp --no-parallel

Limits and alternatives

  • Reduced models are qualified. Released-model capacity/throughput and 262,144-token training are 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; fresh initialization depends on owner count. Native checkpoints support resharding.
  • QSA's fused gather_attn path with separate values and grouped KV heads requires SM100/SM103; other CUDA GPUs raise in Attention Gym rather than falling back. The indexer teacher stays chunked pending the shared indexer teacher, which can replace QSAIndexerLoss; the trained indexer's KL scores still use a dense query x block GEMM.
  • Fixed row ownership and individual-vector lookups fit PyTorch all-to-all plus F.embedding. DTensor reuses existing clipping, optimizers and DCP; plain local parameters would require additional core contracts. TP/SP, PP and CP are rejected by this configuration.

Stack

  1. [gdn] Honor deterministic GDN normalization #5784: merged prerequisite for deterministic GDN normalization.
  2. [qwen3_8_fn] 1/n Add Flash-Next model, DTensor PLE, FSDP and EP #5782: Flash-Next model, DTensor PLE, FSDP/EP and report optimizer policy.
  3. [qwen3_8_fn] 2/n Add tensor and sequence parallelism #5783: tensor/sequence parallelism.
  4. [qwen3_8_fn] 3/n Add pipeline stages, remat and numerical integration coverage #5785: pipeline stages, remat and numerical integration coverage.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 3, 2026
@shuhuayu shuhuayu changed the title [qwen3_8_fn] 2/n Add Flash-Next model, FSDP and checkpoint reference coverage [qwen3_8_fn] 1/n Add Flash-Next model, FSDP and checkpoint reference coverage Nov 3, 2026
@shuhuayu
shuhuayu changed the base branch from users/shuhuayu/qwen3-8-fn-01-shared-contracts to main November 3, 2026 22:49
@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 3, 2026
@shuhuayu

shuhuayu commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

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


Request changes -- see the review (indexer grads can be None on some ranks under FSDP; the QSA reference path doesn't scale).

@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 -- under FSDP the QSA indexer can end up with None grads on some ranks, and the QSA training path's saved activations grow with sequence length times the 2,048-token budget. An attention-gym path for the same pattern already exists in deepseek_v4.

What this PR does. Adds torchtitan/models/qwen3_8_flash_next/, built on Qwen35Model. The model has a four-stream gated residual, a hashed n-gram PLE in layer 1, and QSA every fourth layer (the other layers are Qwen3.5 GDN). QSA is an indexer that picks top-k complete 4-token blocks, plus selected-token SDPA and an optional indexer KL loss. The PR also makes two Qwen3.5 config factories public, widens the shared router gate type to Linear.Config, and turns AttentionMetadata into a Protocol. FSDP only; TP, EP, PP and CP raise.

Example. build_model_config("debugmodel", seq_len=64, parallelism=ParallelismConfig()) builds 8 layers, with QSA at layer_id 3 and 7 and GDN elsewhere. Activations go [T, 256] -> repeat -> [T, 1024]. In each block, a gated read gives [T, 256], then attention or MoE, then a gated write back to [T, 1024]. With token_budget=16, a QSA query at position 38 of one document attends to the 4 best complete earlier blocks (16 tokens) plus its own incomplete tail of up to 3 tokens. Each attended token is gathered per query, then attended with SDPA MATH.

Must fix

  1. PR description. "Summary (human-written)" is empty. Also, the title says "1/n Add Flash-Next model", but commit e0aceb3 is "2/n Add Flash-Next model" and the body says "TP/SP and EP follow in 2/n".
  2. Design: the QSA training path doesn't scale (attention.py:182-209, :282-320). It is a Python loop over 16-query chunks that gathers K/V per query and runs SDPA MATH. The saved activations are about 4 MB per token per QSA layer at the released settings, plus an O(T^2) indexer score term (inline comment). deepseek_v4/compressor.py and deepseek_v4/attention.py already do indexer top-k, gathered sparse attention and KL distillation on attn_gym's lightning_indexer / gather_attn (meta-pytorch, allowed by core principle 3). Please say whether those kernels can express QSA (4-token blocks plus tail, 2 KV heads). If they can, use them. If not, add a TODO with an attention-gym issue link, and state in the README which sequence lengths are trainable.
  3. attention.py:281-299 -- indexer grad=None on ranks with no complete block, so FSDP2 reduce-scatters may not match (inline comment, with a one-line fix).

Should consider

  • attention.py:236 -- QSAInnerAttention.Config.num_heads cancels in block_kl; delete it.
  • norm.py:56 -- renamed kwargs force rewriting the sharding config in flavors.py:410-416, and the override drops @local_compile.
  • state_dict_adapter.py:120 -- the MTP warning never fires on the DCP path; drop the keys explicitly instead.
  • test_qwen3_8_flash_next.py:488 -- the shard-order test can't catch the sort bug it is named for. The file also belongs in a qwen3_8_flash_next/ test folder.
  • numerical_tests_qwen3_8_flash_next.py:182 -- imports private GPU-test helpers and monkeypatches production code.
  • tests/assets/qwen3_8_flash_next/checkpoint_schema.json (1,635 lines) has one consumer, and no other model keeps such an asset. Replace it with a compact check: key count, one GDN-layer and one QSA-layer key pattern, the shard count, and a hash of the sorted names.
  • embedding.py:67,78 -- the "feature-sharded" docstrings are inaccurate: NGramTable is replicated over TP and all-gathered whole by FSDP. For 125B-A6B that means all-gathering a 51.2B-parameter table in both forward and backward. Either reject that flavor for training or document it.
  • Tests that don't earn their cost:
    • test_router_bfloat16_ties_mixing_and_backward[compiled] exercises a path no recipe enables.
    • test_packed_padding_is_excluded_from_moe_auxiliary_gradients mostly duplicates common/test_moe.py, and it swaps out the configured batch_wise loss.
    • test_deltanet_uses_sigmoid_output_gate runs in FP32 with ones-initialized weights, so it can't tell InputDtypeGatedRMSNorm apart from the base class.
  • torchtitan_recipes/tests/models/qwen3_8_flash_next.py:49 -- qwen38_flash_next_debugmodel_ac has no consumer.

Questions

  • With indexer_loss=None (the default), the indexer never gets a gradient, so training from scratch keeps it at random init. Is that intended? If only fine-tuning is supported in that mode, should training with indexer_loss=None raise?
  • N-gram hashing resets history at EOS and at positions == 0, but the PLE conv and QSA visibility reset only at positions == 0. Does that match the reference?
Details
  • Shared changes. These look fine. HiMidLoLinear subclasses Linear, so every existing router config still type-checks, and no isinstance check depends on the AttentionMetadata union. The qwen3_5/flavors.py renames are mechanical.
  • FSDP2 grad handling. post_backward collects only params whose unsharded_param.grad is not None. So a rank with zero complete blocks in its microbatch sends a smaller reduce-scatter for that block's FSDP unit.
  • Memory arithmetic (released config). Per query, the gathered K is 2 KV heads x 2051 tokens x 256 dims x 2 bytes = 2.1 MB, and V is the same. That is about 4.2 MB per token per QSA layer, kept for backward, before any MATH-backend GQA repeat.
  • Hidden syncs. The .nonzero() calls in QSAIndexMetadata.from_inputs sync once per step, and min(block_topk, block_ends_G.numel()) makes shapes data-dependent. Accelerator graphs are rejected, so this is acceptable for now, but any compiled region around the indexer would recompile every step.

Not verified: the FSDP2 desync and the memory estimates were not reproduced on GPUs. Whether gather_attn supports multiple KV heads is unverified.

Comment on lines +281 to +299
raw_sum = scores_TB.new_zeros(())
for start in range(0, query_THK.shape[0], self.chunk_size):
stop = start + self.chunk_size
indices_QJ = selected_indices_TJ[start:stop].long()
valid_QJ = indices_QJ >= 0
query_QH1K = query_THK[start:stop].unsqueeze(2)
keys_QHJK = key_THK[indices_QJ.clamp_min(0)].transpose(1, 2)
values_QHJV = value_THV[indices_QJ.clamp_min(0)].transpose(1, 2)
with sdpa_kernel(SDPBackend.MATH):
output_QHV = F.scaled_dot_product_attention(
query_QH1K,
keys_QHJK,
values_QHJV,
attn_mask=valid_QJ[:, None, None],
scale=scale,
enable_gqa=enable_gqa,
).squeeze(2)
outputs.append(output_QHV)
if train_indexer and num_blocks:

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.

Indexer params can get grad=None on some ranks, so FSDP2 reduce-scatters may not match. The KL is the indexer's only gradient path: its input is x_TD.detach() (L370) and the selected indices are integers.

When a rank's microbatch has no complete 4-token block (all padding, or every document shorter than 4 valid tokens), num_blocks == 0. Then raw_sum stays the detached new_zeros(()), and index_qk_proj, q_layernorm and k_layernorm get grad=None on that rank while other ranks have grads. FSDP2 only reduces params whose grad is not None, so the ranks would issue different reduce-scatters. The all_padding unit test runs in one process and can't catch this.

Smallest fix: seed the sum from the graph, so the inject always carries a (zero) indexer gradient.

raw_sum = scores_TB.sum() * 0  # keep indexer params in the graph on every rank

I haven't reproduced this on multiple GPUs.

Comment on lines +286 to +297
query_QH1K = query_THK[start:stop].unsqueeze(2)
keys_QHJK = key_THK[indices_QJ.clamp_min(0)].transpose(1, 2)
values_QHJV = value_THV[indices_QJ.clamp_min(0)].transpose(1, 2)
with sdpa_kernel(SDPBackend.MATH):
output_QHV = F.scaled_dot_product_attention(
query_QH1K,
keys_QHJK,
values_QHJV,
attn_mask=valid_QJ[:, None, None],
scale=scale,
enable_gqa=enable_gqa,
).squeeze(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.

Saved activations here grow as T x J, not with the chunk size. Each 16-query chunk gathers keys_QHJK and values_QHJV with J = 2048 + 3, 2 KV heads and head dim 256. MATH SDPA keeps these inputs for backward. At the released settings that is about 2 MB per token each for K and V, so roughly 17 GB per QSA layer at T=4096, with 12 QSA layers. That is before any GQA expansion inside the math backend (unverified). The indexer's scores_QHG.relu() adds another O(T^2) fp32 term (L184-187).

The README says gathers are "bounded by query chunks". That holds for transient memory only, not for what is saved for training. See the design item in the review body: deepseek_v4 already runs indexer top-k plus gathered sparse attention through attn_gym's lightning_indexer / gather_attn.

@dataclass(kw_only=True, slots=True)
class Config(InnerAttention.Config):
compress_ratio: int
num_heads: 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.

num_heads has no effect. Its only use is / self.num_heads at L311. teacher_QB is then renormalized in block_kl (L225-226), so the constant cancels. The field also duplicates QSAAttention.Config.n_heads without a consistency check. Delete the field, the attribute and the division.

class Config(GatedRMSNorm.Config):
pass

def forward(self, input_THD: torch.Tensor, gate_THD: torch.Tensor) -> torch.Tensor:

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 override renames the base kwargs input/gate to input_THD/gate_THD. That rename is the only reason flavors.py:410-416 has to copy and rewrite gated_rms_norm_sharding_config() keys behind an assert. The override also drops the base class's @local_compile("gated_rmsnorm", batch_invariant=False).

Keep the parent's parameter names and the decorator, then pass gated_rms_norm_sharding_config() unchanged in flavors. That removes about 6 lines.

Comment on lines +120 to +123
if any(key.startswith("mtp.") for key in state_dict):
logger.warning(
"The Flash-Next Transformers reference excludes the MTP draft head; loading the backbone and vision weights only."
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This warning never fires on the HF load path. DCP calls to_hf, loads only those keys, then calls from_hf, so mtp.* never arrives here. In offline conversion the keys are actually dropped by the parent's silent continue on unmapped keys.

Following "explicit over implicit", drop the MTP keys deliberately with a comment saying why (MTP is outside this model), and remove the warning. Related: ple = self.flash_config.layers[layer_id].ple at L108 raises AttributeError rather than ValueError for shards on a layer without PLE.

Comment on lines +488 to +495


def test_adapter_roundtrip_and_numeric_shard_order(config):
model = config.build()
model.init_states()
adapter = Qwen38FlashNextStateDictAdapter(config, None)
state = model.state_dict()
hf = adapter.to_hf(state)

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 name says "numeric_shard_order", but this test can't catch a lexicographic-sort bug. The debug flavor has split_parts=4, and shard_0..shard_3 sort the same either way; the bug needs 11 or more parts (shard_10 before shard_2). Reversing dict order only shows the result doesn't depend on insertion order.

Either build the adapter with split_ngram_parts >= 11 or rename the test.

Separately, this file should live in tests/unit_tests/cpu/models/qwen3_8_flash_next/, matching the sibling qwen3_5/ and qwen3_8/ folders.

Comment on lines +182 to +196
from tests.unit_tests.gpu.models.qwen3_5.test_qwen3_5_deltanet import (
_reference_causal_conv1d_varlen,
ReferenceGatedDeltaKernel,
)
from torchtitan.models.common.attention.gdn import GDN

for layer in native.layers.values():
if isinstance(layer.attention, GDN):
layer.attention.inner_attention.kernel = ReferenceGatedDeltaKernel()
reference_stack.enter_context(
patch(
"torchtitan.models.common.attention.gdn._causal_conv1d_varlen",
_reference_causal_conv1d_varlen,
)
)

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 script depends on private test internals and monkeypatches:

  • It imports _reference_causal_conv1d_varlen from a GPU test module (here and again at L769).
  • It patches gdn._causal_conv1d_varlen and replaces the kernel object.
  • It patches RoutedExperts.forward with an FP32 oracle (L220-222).

Any rename in those tests silently breaks this script, and the parity check no longer runs the production path. _run is also a single ~1000-line function, where sibling scripts (qwen3_5: 447 lines) split into build/run/compare.

Please either promote the reference kernels to a non-test, non-private location that both consumers import, or drop the patched variants. The script is 1,184 lines; the patched variants are a large share of it.

@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-02-model branch 3 times, most recently from f387642 to 1232b90 Compare November 5, 2026 08:21
@shuhuayu

shuhuayu commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @shuhuayu's task in 4m 47s —— View job


Approve -- please address the items below before merging -- see the review (earlier must-fix items resolved; one dead accelerator-graph check to delete).

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. All three earlier must-fix items are resolved at 1232b90. One small new item remains: a dead runtime check. This PR touches shared code (common/moe/moe.py, qwen3_5/flavors.py, tests/integration_tests/models.py), so a maintainer still needs to review.

What this PR does. It adds torchtitan/models/qwen3_8_flash_next/ on top of Qwen35Model. The model has four gated residual streams, a hashed n-gram PLE in layer 1, and block-selecting QSA every fourth layer; the other layers are Qwen3.5 GDN. The PR also makes two Qwen3.5 config factories public and widens the router gate type to Linear.Config. Only FSDP is supported; TP, EP, PP and CP raise in build_model_config.

Example. build_model_config("debugmodel", seq_len=64, parallelism=ParallelismConfig(data_parallel_shard_degree=2), indexer_loss=QSAIndexerLoss.Config(...)) gives 8 layers, with QSA at layers 3 and 7. Take a rank whose microbatch has no complete 4-token block. Before, its indexer params had grad=None while other ranks had grads. Now raw_sum = scores_TB[..., :0].sum() keeps the indexer in the graph, so every rank reduce-scatters the same params (the 2-GPU test_indexer_gradient_participation covers this).

Earlier must-fix items

  1. PR description: resolved. The human-written summary is present, and the commit titles match "1/n".
  2. QSA training memory: resolved. Dense scoring and gathered SDPA run under per-chunk nonreentrant checkpoints, the code has an Attention Gym TODO with a link, and the README lists the qualified sequence lengths.
  3. FSDP grad=None on empty ranks: resolved, with a CI-run multi-GPU regression test.

The earlier should-consider items are also addressed: the num_heads field is gone, norm.py kwargs and @local_compile are restored, MTP keys are dropped explicitly, the 16-shard order test is in place, the tests moved to their own folder, the 47-line schema digest replaces the 1,635-line asset, the harness no longer patches anything, the embedding docstrings are fixed, and the _ac recipe is removed. The README answers both earlier questions (frozen selector, EOS vs. position resets).

Must fix

  1. attention.py:98-105 -- the accelerator-graph check in QSAIndexMetadata.from_inputs never fires in training, because metadata is built during preprocessing, outside capture. Its test only passes because it mocks the capture state. Delete both (inline).

Should consider

  • attention.py:348 -- .long() makes the checkpoint save an int64 copy of the selected indices instead of the int32 tensor (inline).
  • attention.py:351-352 -- the comment says nested torch_remat.checkpoint is unsupported. That is an upstream gap, and it is the reason this file uses torch.utils.checkpoint instead of torch_remat (which direction.md says to build on). Turn it into a TODO with a torch_remat issue link.
Details
  • Why the check is dead. TrainingEngine._preprocess_microbatch_groups (training_engine.py:684) calls preprocess_inputs before _run_forward_backward. That path reaches QSAInnerAttention.Config.build_attention_metadata, then from_inputs, which is where the check sits. The metadata is None fallback in QSAIndexer.forward is never taken under Decoder. When graphs are on, the actual failure is AcceleratorGraphWrapper._validate_inputs raising on the first metadata shape change. That error is explicit, not silent, so this is dead code rather than a correctness bug.
  • Frozen selector. QSAAttention.__init__ freezes the indexer when indexer_loss=None, and forward runs selection with grad disabled unless the model is training with KL configured. The empty-slice sum is finite even when every score is -inf, so the NaN case described in the PR doesn't arise.
  • Shared changes. These are unchanged since the last review and still fine: every existing HiMidLoLinear router gate is a Linear.Config subclass, and the qwen3_5 renames are mechanical.

Not verified: the GPU and HF parity results, the memory table, and that int32 indexing preserves numerics bitwise (none of these were run here).

Comment on lines +98 to +105
if (
accelerator_graphs_supported()
and torch.get_device_module().is_current_stream_capturing()
):
raise ValueError(
"Flash-Next QSA uses dynamic block selections; set "
"training.disable_accelerator_graphs=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 check never fires during training. The trainer builds attention metadata in preprocess_inputs, and _preprocess_microbatch_groups runs outside capture (training_engine.py:684: "Preprocess all microbatch groups outside CUDA capture"). So is_current_stream_capturing() is always False when QSAInnerAttention.Config.build_attention_metadata calls this. The only in-capture caller is the metadata is None fallback in QSAIndexer.forward, and Decoder always passes metadata.

With the default disable_accelerator_graphs=False, a user gets this error only after warmup, and it is the generic one: the wrapper's _validate_inputs raises "Accelerator graph tensor inputs must keep the same shape" once the block count G changes. The test at test_qwen3_8_flash_next.py:75 mocks both accelerator_graphs_supported and the device module, so it passes even though the trainer never reaches this branch.

Fix: delete this block, its import, and the mocked test. The README already documents the disable_accelerator_graphs=True requirement, and every recipe sets it. A real config-time rejection would need a hook in config/validation.py, and that core change isn't worth making for one model.

raw_sum = scores_TB[..., :0].sum()
for start in range(0, query_THK.shape[0], self.chunk_size):
stop = start + self.chunk_size
indices_QJ = selected_indices_TJ[start:stop].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.

.long() creates an int64 copy of each chunk's indices, and the nonreentrant checkpoint at L353 saves it as an input for backward. The indexer deliberately returns int32 (.int() at L266), and this cast undoes that for the saved state. At the released J = 2,051, that is about 16 KB per token per QSA layer, against 8 KB for an int32 view. That works out to roughly 0.8 GB vs 0.4 GB at 4,096 tokens across 12 QSA layers (arithmetic only).

PyTorch advanced indexing accepts int32 index tensors, so dropping .long() should be enough: key_THK[indices_QJ.clamp_min(0)] in both _selected_attention and the teacher. I haven't run this.

@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-02-model branch from 1232b90 to 3f39d6f Compare November 5, 2026 20:05
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-02-model branch from 3f39d6f to 48314a2 Compare November 6, 2026 00:55
@shuhuayu shuhuayu changed the title [qwen3_8_fn] 1/n Add Flash-Next model, FSDP and checkpoint reference coverage [qwen3_8_fn] 1/n Add Flash-Next model, row-owned PLE and FSDP validation Nov 6, 2026
@shuhuayu shuhuayu changed the title [qwen3_8_fn] 1/n Add Flash-Next model, row-owned PLE and FSDP validation [qwen3_8_fn] 1/n Add Flash-Next model, row-owned PLE, FSDP and EP Nov 6, 2026
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-02-model branch from 0f6481b to 3bb96e0 Compare November 7, 2026 02:07
@shuhuayu shuhuayu changed the title [qwen3_8_fn] 1/n Add Flash-Next model, row-owned PLE, FSDP and EP [qwen3_8_fn] 1/n Add Flash-Next model, DTensor PLE, FSDP and EP Nov 7, 2026
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-02-model branch from 3bb96e0 to 0972e3a Compare November 9, 2026 07:55
@shuhuayu
shuhuayu changed the base branch from main to users/shuhuayu/qwen3-8-fn-04-determinism November 9, 2026 07:55
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-02-model branch from 0972e3a to 06c11e0 Compare November 9, 2026 10:21
@shuhuayu
shuhuayu force-pushed the users/shuhuayu/qwen3-8-fn-04-determinism branch from f521fcb to 28f038a Compare November 9, 2026 10:21
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-02-model branch from 06c11e0 to 2854b18 Compare November 9, 2026 10:46
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-02-model branch 3 times, most recently from 3673607 to 1730599 Compare November 10, 2026 03:57
Use native projections with saved-child remat support, and build optimizer layouts at recipe construction with validation-only post-init. Use public collective and DCP contracts, remove redundant lookup permutations, require one PLE layer, and keep optimizer policy and PLE documentation with their owners.
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-02-model branch from 1730599 to 4e77ce4 Compare November 10, 2026 04:55
@shuhuayu
shuhuayu marked this pull request as ready for review November 10, 2026 04:57
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 10, 2026
@github-actions
github-actions Bot requested a review from ivy-zhou November 10, 2026 04:58
@shuhuayu
shuhuayu requested review from liangel-02 and removed request for ivy-zhou November 10, 2026 04:58
NGramTable already rejects tables whose rows do not divide the DP degree, so
the uneven and empty-owner paths in the row-sharded lookup and HF adapter
could not run. Require divisibility in the helper, drop the empty-owner
placeholder path from the adapter, and type the lookup weight as the Shard(0)
DTensor its only caller passes.

Remove lookup tests for unsupported layouts and the clipping/DCP test that
exercised PyTorch rather than the helper. Bitwise-neutral for supported
configurations.
Replace the per-16-query checkpointed gather + MATH SDPA loop with one
gather_attn call: selected blocks and the incomplete tail are sparse KV
indices into the packed sequence (no sliding window), with separate values
and grouped KV heads. CUDA uses the fused kernel (Triton grouped schedule,
SM100/SM103); CPU uses the reference implementation, as in DeepSeek-V4.
The indexer and the no-grad indexer teacher are unchanged.

Requires the attn-gym pin at 0d0197fb (pytorch#6017) for sparse_v and the grouped
fused kernels.

Numerics (GB300, released 125B-A6B QSA shapes, T=4096, bf16 vs fp64 oracle,
relative error out/dq/dk/dv): fused 3.4e-3/4.4e-3/4.4e-3/3.6e-3, previous
eager 3.1e-3/4.0e-3/9.1e-3/8.2e-3. Fused outputs and gradients are bitwise
identical across processes and cold Triton caches. Forward+backward per QSA
layer: 3.3 ms vs ~10 s. Debug model, 2 GPUs, seed 42, 10 steps: losses match
to ~1e-3 (step 10: 7.49278 vs 7.49127).

Drop the attention test's saved-storage budget, which guarded the removed
checkpoint; keep its dense masked-SDPA output and gradient check.
Replace the per-chunk dense ranking (argsort over every complete block) with
lightning_indexer, as in DeepSeek-V4. It runs over valid tokens only, with
per-document offsets in valid-token space, so its compress_ratio candidates are
exactly QSAIndexMetadata's document-local blocks even with padding inside a
document. Selected blocks are sorted ascending for a backend-independent slot
order. The KL scores of the selected blocks keep the previous math: one dense
GEMM per checkpointed query chunk, then a gather (gathering per-query keys makes
backward a scatter-add, ~30x slower).

Ties: ReLU scores tie exactly (2.2% of selected scores at random init, released
shapes). Under deterministic algorithms the CuTe backend resolves them toward
earlier blocks, as before; otherwise the cutoff choice is backend-defined. The
CPU tie test is removed: on CPU it exercises Attention Gym's reference
torch.topk, which does not order ties.

Released 125B-A6B indexer shapes on GB300 (T=4096, two documents, interior and
trailing padding): with deterministic algorithms all 4096 rows select the same
blocks as the previous ranking and the selected scores are bitwise equal;
without, 132/4096 rows swap blocks with exactly equal cutoff scores. Indexer
forward+backward: 51 ms vs 64 ms. Debug model, 2 GPUs, seed 42, 10 steps: step 1
loss is identical, later steps within 2e-3 of the previous commit.
shuhuayu added a commit that referenced this pull request Nov 11, 2026
## Why
The Qwen3.8-Flash-Next QSA attention (#5782) will use `gather_attn`'s
grouped-KV / separate-V Triton kernels. They first appear in
attention-gym v0.0.19, after attention-gym #678, #701, #702, #713, #714,
#715 and #703. torchtitan pins `26beb363`, which predates all of these.
This PR only bumps the pin; the Flash-Next change stays in #5782.

## What changed (all mechanical)
| | Before | After |
| --- | --- | --- |
| attn-gym pin | `26beb363` (#704 merge) | `0d0197fb` (v0.0.19 tag, #703
merge) |

- `.ci/docker/requirements.txt` (root `requirements.txt` symlinks to
it): new SHA. The TODO now says to switch to the PyPI release once
v0.0.19 is published there (PyPI's newest is 0.0.18). #704, which the
old TODO waited on, is already included in both pins.
- `torchtitan/models/common/attn_gym.py` (install hint) and
`tests/unit_tests/cpu/models/common/test_optional_imports.py` (2
asserts): same SHA.

## Why v0.0.19 rather than attention-gym `main`
`26beb363..0d0197fb` changes only `attn_gym/sparse/gather_attn` (plus
its tests and docs). I diffed the two installed `attn_gym` trees to
confirm this. GDN, KDA, short_conv, the indexer, MLA and the CuTe
backend are byte-identical, so qwen3_5, qwen3_8, kimi and the
deepseek_v4 indexer can't change. `main` would also pull in the
warpdrive rewrite and the indexer/delta-H ports (~28 `_delta_rule`
files).

## Numerics
The only `gather_attn` consumer is
`torchtitan/models/deepseek_v4/attention.py`. Old vs new pin, 10 steps,
seed 42, deterministic, loss and grad_norm read from TensorBoard via
`scripts/loss_compare.py`, on GB300:

| Config | GPUs | Result |
| --- | --- | --- |
| `deepseek_v4_debugmodel_fsdp4_ep4` (DistMuon) | 4 | bitwise identical*
|
| `deepseek_v4_debugmodel_fsdp2_tp2_ep2_pp2` with dp_shard=1 (host has 4
GPUs) | 4 | bitwise identical* |

\* With `gather_attn`'s Triton tuners pinned to the same candidate in
both runs. Without pinning, deepseek_v4 isn't run-to-run reproducible on
**either** pin when the autotune cache is cold. `_FWD_TMA` and
`_BWD_DLOCAL_KV_TMA` choose `num_warps` 4 vs 8 by timing, and the two
give different bits. Ranks and cold-cache runs can pick different
winners, and torch's deterministic flag doesn't control this. This
already happens on main. I filed it upstream as
meta-pytorch/attention-gym#777, with a single-GPU repro. Because of it,
this PR adds no deepseek_v4 golden; see follow-ups.

## Testing
- `pre-commit run --all-files` passes, including `pyrefly-check`.
- `pytest tests/unit_tests/cpu/models/common` plus the deepseek_v4,
qwen3_5, qwen3_8 and kimi_k3 CPU tests: 416 passed. The same 9 tests
fail with both the old and new pin on this aarch64 host
(`test_lora_forward` and 8 qwen3_5 tests). The one I inspected,
`test_lora_forward`, fails with "torch.compile on current platform is
not supported for CPU".

## Known issues / follow-ups
- deepseek_v4 golden numerics: add once attention-gym#777 lets us fix
the tile config. The golden then has to be exported on CI's A10G
runners, not on GB300.
…r chunk

The teacher replicated the gathered keys from 2 KV heads to all 24 query
heads, cast them to fp32 and took the dot products as an elementwise multiply
and sum over a [16, 24, 2051, 256] tensor per 16-query chunk. On the 125B on
16 GB300s (FSDP16 + EP16, 4K tokens/rank) this loop was ~6.4 s of the
~7.9 s of GPU compute in a profiled step; matmuls were 0.39 s.

Group query heads by KV head and compute the logits with one batched
einsum per chunk, gathering each key once. Raise chunk_size from 16 to 128.

At T=4096, H=24, H_kv=2, J=2051 one layer's teacher drops from 269.7 ms to
24.0 ms with peak memory 2.0 -> 1.4 GiB; the block targets match to 3.7e-9
(relative 9e-7). The 2-GPU debug model has identical step-1 loss and
grad_norm, and losses within 2e-3 over 10 steps.
``(valid_U, blocks_UB)``: valid token positions and their selected
global block ids in ascending order, -1 after the valid ones.
"""
valid_U = valid_T.nonzero().flatten()

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.

can we move this into from_inputs to avoid the device to host sync

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.

nice suggestion. we have done this in 2/n pr, moving valid-token compaction, document offsets, block indices into from_inputs, and using fixed shape. #6047

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)

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.

^same here

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.

ditto.

# An empty slice is finite even when all selected scores are -inf.
raw_sum = scores_TB[..., :0].sum()
num_teacher_tokens = query_THK.shape[0] if num_blocks else 0
for start in range(0, num_teacher_tokens, self.chunk_size):

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.

can keep this for now and land #5863 after to better perf

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.

make sense.

…acher GEMMs

The 125B GB300 step was CPU launch bound: ~98k GPU ops per step, the GPU
busy ~35% of it, and the two QSA per-chunk loops (indexer scores, chunk 128;
teacher + block_kl, chunk 128) were the largest launch source.

- Indexer scores: chunk 1024 (4 heads -> 16 MiB fp32 Q x H x G per chunk at
  T=4096, 128 MiB at 32K) and cast query/key once outside the loop.
- Teacher: gather selected keys along dim 0 and run one strided baddbmm per KV
  head (bf16 in, fp32 accumulate/out; scale and mask in the GEMM), chunk 512
  (~1 GiB of gathered bf16 keys, independent of T). CPU casts first.
- One block_kl over all tokens instead of one per chunk.

One 125B QSA layer, fwd+bwd, T=4096, GB300 eager:
  wall 80.0 -> 20.5 ms, GPU kernel 33.6 -> 16.2 ms,
  GPU ops 2893 -> 631, peak 2.07 -> 2.91 GiB.
Numerics: output and input grad bitwise identical on GPU; indexer weight grads
differ only by fp32 summation order (bf16 ulps). Old vs new in float64 on CPU
(with and without padding) agree to 7.7e-16. CPU unit tests pass.
@shuhuayu

Copy link
Copy Markdown
Contributor Author

Superseded by #6046, which moves the Flash-Next stack to upstream branches managed with gh stack. #6046 contains these commits rebased on current main plus the QSA indexer performance commits; the review discussion here remains for reference.

@shuhuayu shuhuayu closed this Nov 12, 2026
@shuhuayu

Copy link
Copy Markdown
Contributor Author

@liangel-02 thanks for the review, i moved this pr to more organized stack here: #6046

shuhuayu added a commit that referenced this pull request Nov 21, 2026
## 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.

```python
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](https://github.com/QwenLM/Qwen3.8-Flash-Next/blob/4f58f4ddd855bedaf7eadcd53bbbb1b3362cecff/tech_report.pdf#page=16)):
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](https://github.com/liangyuwang/FSDP-Canzona/blob/426e8c50363cc3401e64eeb80c9e6e2451ea2ed4/matrix_based_optimizer/optimizers/muon.py),
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.

```bash
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](#5863).
- Resumed vs 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. #6047: QSA with static shapes for accelerator-graph capture.
3. #6052: fixed-capacity PLE row-sharded routing (no host-synchronized
splits).
4. #6053: the released 125B-A6B recipe and an accelerator-graph test.
5. #6054: tensor and sequence parallelism.
6. #6055: pipeline parallelism.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants