Skip to content

[gdn] Honor deterministic GDN normalization - #5784

Merged
shuhuayu merged 1 commit into
pytorch:mainfrom
shuhuayu:qwen3-8-fn-04-determinism
Nov 10, 2026
Merged

shuhuayu merged 1 commit into
pytorch:mainfrom
shuhuayu:qwen3-8-fn-04-determinism

Conversation

@shuhuayu

@shuhuayu shuhuayu commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

this pr is to add deterministic option to gdn backend (an existing bug) so gdn has reproducible numerics.

Why

Independent prerequisite based on main. Merge this before #5782; the model stack is based on this branch.

torch.use_deterministic_algorithms(True) does not reach Attention Gym's GDN L2 normalization policy. Its forward schedule is fixed, but backward autotuning benchmarks different tile schedules. Two strict-deterministic runs can therefore choose different backward schedules and train differently.

Example. The eight-GB300 Flash-Next first-step diagnostic observes a difference in kda_l2norm_bwd before the PLE output gradient or any lookup-gradient exchange. Hash IDs and selected vectors are identical. Disabling normalization autotuning under PyTorch's existing deterministic flag pins the schedule.

autotune = not torch.are_deterministic_algorithms_enabled()
normalized_q = l2norm(q, cu_seqlens=cu_seqlens, autotune=autotune)

What changed

Pass that policy through all shared GDN normalization callsites: ordinary chunk/recurrent forward, recurrent backward's chunk-gradient recomputation, and CP GDN. Nondeterministic runs retain autotuning. No model flag or alternate kernel is added.

User-facing changes

Before After
Strict determinism still allows GDN backward normalization autotuning The existing PyTorch deterministic flag selects a fixed schedule.

Numerics and testing

  • The CUDA regression checks that deterministic backward bypasses the L2 autotuner and produces finite, nonzero gradients in ordinary and batch-invariant GDN modes. It does not assert how many times upstream internals run in nondeterministic mode.
  • The shared GDN computation in this PR is unchanged by the PLE storage refactor. Both native DTensor and plain-owned-row qualification sources include this same committed policy.
  • Two-GB300 controlled A/B runs match first-step logits and 190 gradient shards per rank, all twenty ten-step loss/norm values, and all 763 final model/optimizer tensors bitwise. Full remat and checkpoint resume preserve the result.
  • The restacked TP2/SP/EP2 registered GB300 regression matches all twenty unchanged golden values bitwise. Runtime: PyTorch 2.16.0.dev20261030+cu132, revision bf270c3251d8e84723cedbf5b60eaa60cacaa3f2; seed 42 and strict determinism. No production kernel or runtime patch is used.
  • Existing GDN integration coverage exercises the default path; all-file lint/typechecking pass.
python -m pytest -q tests/unit_tests/gpu/models/qwen3_5/test_qwen3_5_deltanet.py

The fix intentionally chooses a fixed backward schedule in deterministic mode; it does not claim bitwise equivalence to every autotuned schedule. #5785 carries the registered strict numerical integration. EP remains in #5782 and TP/SP in #5783.

Rebase validation

Rebased onto main at c62c6a7552137d10d4fc3927aa20dcd69925aaf2. This includes #5909's upstream RL golden-reference fix. All ten losses from the old failing RL job exactly match that corrected reference; this PR does not edit the RL golden.

  • Runtime: PyTorch 2.16.0.dev20261108+cu132, revision 1392e1f8e4903657d4391f3bd8fcc9ca8a74b758; Attention Gym 0.0.19.dev10+g26beb363c, pinned revision 26beb363c6d1328851bfc5c9c8691fa2066bd1fa.
  • The retained test_deterministic_backward_bypasses_normalization_autotuner passes on a GB300, covering ordinary and batch-invariant GDN forward/backward with finite, nonzero gradients.
  • All-file pre-commit, including typechecking, passes on this PR and the complete rebased stack. Typechecking uses this runtime and isolated stubs for optional dependencies.
  • The complete stack's targeted CPU suite passes 123 tests.

The earlier multi-GPU model qualification results above apply to their recorded pre-rebase sources and October 30 runtime. They have not been repeated after this rebase. GitHub CI for the new head is pending.

Stack

Prerequisite: #5784, shared GDN deterministic normalization, independently based on main. Merge it first.

  1. [qwen3_8_fn] 1/n Add Flash-Next model, DTensor PLE, FSDP and EP #5782: Flash-Next model, native DTensor PLE, FSDP and EP, based on the prerequisite.
  2. [qwen3_8_fn] 2/n Add tensor and sequence parallelism #5783: TP/SP and PLE feature-column sharding, based on [qwen3_8_fn] 1/n Add Flash-Next model, DTensor PLE, FSDP and EP #5782.
  3. [qwen3_8_fn] 3/n Add pipeline stages, remat and numerical integration coverage #5785: PP, remat and registered numerical integration, based on [qwen3_8_fn] 2/n Add tensor and sequence parallelism #5783.

Local all-file hooks pass; Pyrefly uses the pinned validation runtime and isolated optional-dependency stubs. GitHub CI is pending.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 3, 2026
@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] 4/n Honor deterministic GDN normalization [qwen3_8_fn] 3/n Honor deterministic GDN normalization Nov 3, 2026
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-04-determinism branch from b2aca89 to 71eb967 Compare November 4, 2026 01:54
@shuhuayu
shuhuayu force-pushed the users/shuhuayu/qwen3-8-fn-03-tp-ep branch from b292f9c to cbe9b3c Compare November 4, 2026 01:54
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-04-determinism branch from 71eb967 to 223be19 Compare November 4, 2026 21:15
@shuhuayu
shuhuayu force-pushed the users/shuhuayu/qwen3-8-fn-03-tp-ep branch from cbe9b3c to e15a1f6 Compare November 4, 2026 21:15
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-04-determinism branch from 223be19 to 51b450b Compare November 5, 2026 08:21
@shuhuayu
shuhuayu force-pushed the users/shuhuayu/qwen3-8-fn-03-tp-ep branch from e15a1f6 to b4b0b68 Compare November 5, 2026 08:21
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-04-determinism branch from 51b450b to 6608e4e Compare November 5, 2026 20:05
@shuhuayu
shuhuayu force-pushed the users/shuhuayu/qwen3-8-fn-03-tp-ep branch 2 times, most recently from c339afc to ac5a16a Compare November 5, 2026 20:14
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-04-determinism branch 2 times, most recently from 72d0de7 to bc22fd5 Compare November 6, 2026 00:55
@shuhuayu
shuhuayu force-pushed the users/shuhuayu/qwen3-8-fn-03-tp-ep branch from ac5a16a to 7bba104 Compare November 6, 2026 00:55
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-04-determinism branch from bc22fd5 to f72e254 Compare November 6, 2026 03:39
@shuhuayu
shuhuayu force-pushed the users/shuhuayu/qwen3-8-fn-03-tp-ep branch from 7bba104 to ff98eea Compare November 6, 2026 03:40
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-04-determinism branch from f72e254 to ba80b84 Compare November 7, 2026 02:07
@shuhuayu
shuhuayu force-pushed the users/shuhuayu/qwen3-8-fn-03-tp-ep branch from ff98eea to d9413c0 Compare November 7, 2026 02:07
@shuhuayu shuhuayu changed the title [qwen3_8_fn] 3/n Honor deterministic GDN normalization [qwen3_8_fn] Prerequisite: Honor deterministic GDN normalization Nov 9, 2026
@shuhuayu
shuhuayu changed the base branch from users/shuhuayu/qwen3-8-fn-03-tp-ep to main November 9, 2026 07:55
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-04-determinism branch from ba80b84 to f521fcb Compare November 9, 2026 07:55
@shuhuayu shuhuayu changed the title [qwen3_8_fn] Prerequisite: Honor deterministic GDN normalization [qwen3_8_fn] 0/n Honor deterministic GDN normalization Nov 9, 2026
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-04-determinism branch from f521fcb to 28f038a Compare November 9, 2026 10:21
@shuhuayu
shuhuayu force-pushed the qwen3-8-fn-04-determinism branch from 28f038a to 54edd65 Compare November 9, 2026 10:46
@shuhuayu
shuhuayu marked this pull request as ready for review November 9, 2026 10:47
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 9, 2026
@github-actions
github-actions Bot requested a review from drisspg November 9, 2026 10:47
@shuhuayu

shuhuayu commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

Comment on lines +124 to +126
autotune = not torch.are_deterministic_algorithms_enabled()
normalized_q_BTHK = l2norm(q_BTHK, cu_seqlens=cu_seqlens, autotune=autotune)
normalized_k_BTHK = l2norm(k_BTHK, cu_seqlens=cu_seqlens, autotune=autotune)

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.

why this is not changed in attention-gym?

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.

the change in attn-gym is here: meta-pytorch/attention-gym#632, and is available after 0.0.17, we did a similar change for kimi models for ci reproducibility, #5358

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.

sure, but my question is -- why couldn't attn-gym's function check torch.are_deterministic_algorithms_enabled() internally

stamping to unblock anyway

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 see your point now. i think this maybe related to whether the knob autotune is equivalent to are_deterministic_algorithms_enabled. maybe @liangel-02 has some ideas on this api exposure.

Comment on lines +124 to +126
autotune = not torch.are_deterministic_algorithms_enabled()
normalized_q_BTHK = l2norm(q_BTHK, cu_seqlens=cu_seqlens, autotune=autotune)
normalized_k_BTHK = l2norm(k_BTHK, cu_seqlens=cu_seqlens, autotune=autotune)

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.

sure, but my question is -- why couldn't attn-gym's function check torch.are_deterministic_algorithms_enabled() internally

stamping to unblock anyway

@shuhuayu shuhuayu changed the title [qwen3_8_fn] 0/n Honor deterministic GDN normalization [gdn] Honor deterministic GDN normalization Nov 10, 2026
@shuhuayu
shuhuayu merged commit baf7cf9 into pytorch:main Nov 10, 2026
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