Skip to content

[CI deps] Pin attn-gym 0.0.20 from PyPI and follow its kernel_options API - #6063

Merged
drisspg merged 2 commits into
mainfrom
drisspg/attn-gym-kernel-options
Nov 12, 2026
Merged

drisspg merged 2 commits into
mainfrom
drisspg/attn-gym-kernel-options

Conversation

@drisspg

@drisspg drisspg commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

bump the pin and make disable autotune under determ. we made some good changes to kda and need to change
numeric ref

Why

attention-gym v0.0.20 fixes meta-pytorch/attention-gym#777: kernels whose launch configuration is picked by timing (the gather_attn Triton kernels DeepSeek-V4 uses, among others) gave different output bits from run to run, even under torch.use_deterministic_algorithms(True). #6017 could not add a DeepSeek-V4 golden because of it. From v0.0.20, every tuned attn-gym operation launches one fixed configuration in deterministic mode.

The fix came with an API change (meta-pytorch/attention-gym#809): autotune is no longer a keyword argument; it is a key of kernel_options. torchtitan has to follow it to take the release.

Example.

# before (v0.0.19): torchtitan decides whether to tune
autotune = not torch.are_deterministic_algorithms_enabled()
q = l2norm(q, autotune=autotune)
out, _ = chunk_kda(q, k, v, g, beta, cu_seqlens=cu, autotune=autotune, kernel_options=opts)

# after (v0.0.20): attn-gym pins its tuned kernels in deterministic mode itself
q = l2norm(q)
out, _ = chunk_kda(q, k, v, g, beta, cu_seqlens=cu, kernel_options=opts)

What changed

Before After
attn-gym pin git SHA 0d0197fb (v0.0.19 tag) attn-gym[linear,cudnn]==0.0.20 from PyPI (tag 7adfbadb)
  • Pin (mechanical): .ci/docker/requirements.txt (root requirements.txt symlinks to it), the install hint in torchtitan/models/common/attn_gym.py, and 2 asserts in tests/unit_tests/cpu/models/common/test_optional_imports.py. v0.0.20 is on PyPI, so the pin is a version again and the TODO about the git pin is removed; PyPI no longer blocks a torchtitan release on this dependency.
  • l2norm, chunk_kda (models/common/attention/{gdn,kda,cp_gdn}.py): drop autotune= and the autotune = not torch.are_deterministic_algorithms_enabled() lines. attn-gym applies the same rule.
  • recurrent_gdn in batch-invariant mode (models/common/attention/gdn.py, rl/generator/attention/gdn.py): kernel_options={"batch_invariant": True, "autotune": False}, the same request as before.
  • paged_mla_decode (rl/generator/vllm/attention/mla.py): kernel_options={"autotune": True}, the same request as before.
  • Test: test_deterministic_backward_bypasses_normalization_autotuner patched a triton.autotune object that no longer exists. It now fails if any attn-gym Triton kernel takes the tuned launch path in deterministic mode.

User-facing changes

Before After
chunk_gdn, gather_attn, the context-parallel KDA/GDN operations and paged_mla_decode tuned by timing in deterministic mode They launch a fixed configuration in deterministic mode; unchanged otherwise
Tuned winners cached on disk from v0.0.19 Re-tuned once after the upgrade (the cache key changed)

Numerics

v0.0.19 -> v0.0.20 changes chunk_kda bits, so the Kimi K3 golden changes. I bisected the 12 attention-gym commits that touch the kernels torchtitan calls, with tuning off and deterministic mode on (GB200, torchtitan's call pattern: bound_gate, l2norm, chunk_kda forward and all input gradients, BF16 and FP16):

Kernel v0.0.19 -> v0.0.20
l2norm, bound_gate, causal_conv1d, chunk_gdn bitwise identical
chunk_kda BF16 forward and gradients change (forward max abs diff 1.2e-4 on values up to 6e-2)
chunk_kda FP16 only the gate gradient changes

One commit causes all of it, and both changes are intended:

The kernel_options change itself (#809) is bitwise identical to the commit before it on this path.

kimi_k3_mm_muon (B200, 2 GPUs, FSDP=2, EP=2, exact golden): tests/assets/losses/real_pg/kimi_k3_b200.txt is regenerated in this PR. The values come from this branch's first B200 run, and the B200 run on the commit with the new file reproduces them bit for bit.

Step Loss, old golden Loss, attn-gym 0.0.20 Grad norm, old Grad norm, new
1 8.107099533081055 8.107158660888672 2.890625 2.890625
2 7.700622081756592 7.69891357421875 4.09375 4.125
3 7.474788665771484 7.475809574127197 6.25 6.25
4 7.444936752319336 7.446145057678223 5.03125 5.03125
5 7.1190619468688965 7.12349796295166 8.5625 8.5
6 6.984208106994629 6.983041286468506 8.75 8.75
7 5.781412124633789 5.781435012817383 13.4375 13.4375
8 6.867074966430664 6.866772651672363 8.8125 8.8125
9 6.368958950042725 6.368622779846191 11.9375 11.9375
10 5.942665100097656 5.940550804138184 12.3125 12.3125

The largest loss difference is 0.0044 (step 5); the gradient norm differs at steps 2 and 5. Runs: old golden mismatch, new golden passes.

No other golden covers a model that calls KDA.

Testing

On a GB200 with attn-gym at the v0.0.20 tag:

  • tests/unit_tests/gpu/models/common, .../qwen3_5/test_qwen3_5_deltanet.py, .../deepseek_v4, tests/unit_tests/cpu/models/common/test_optional_imports.py: 149 passed. The 2 failures need the cuDNN backend, which that environment lacks; they pass in an environment that has it.
  • The rewritten determinism test fails when l2norm is made to ignore deterministic mode, and passes otherwise.
  • pre-commit passes except pyrefly-check, which is not installed locally.

Not run locally (missing vllm, monarch, openai, transformers): the RL generator tests, the Kimi K3 GPU tests and the integration tests. CI is their first run against the new API.

Known issues / follow-ups

  • A DeepSeek-V4 golden is now possible (attention-gym#777 is fixed); separate PR.

… API

attn-gym v0.0.20 moved every kernel knob into kernel_options and removed the
autotune= keyword (meta-pytorch/attention-gym#809). It also turns tuning off
itself under torch.use_deterministic_algorithms(True), so torchtitan no
longer computes `autotune = not torch.are_deterministic_algorithms_enabled()`
before each call.

- l2norm and chunk_kda: drop the autotune argument; attn-gym pins its tuned
  kernels in deterministic mode.
- recurrent_gdn in batch-invariant mode: pass autotune=False through
  kernel_options next to batch_invariant.
- paged_mla_decode in the vLLM generator: kernel_options={"autotune": True}.
- The GDN test that guards the l2norm backward now fails if any attn-gym
  Triton kernel takes the tuned launch path in deterministic mode, instead
  of patching a Triton autotuner object that no longer exists.

Numerics: chunk_kda BF16 outputs and gradients change bits in v0.0.20
(meta-pytorch/attention-gym#764 rebases the forward intra-chunk kernel,
#767 fixes its backward gate gradient at steep gates), so the Kimi K3 B200
golden needs regenerating.

v0.0.20 is on PyPI, so the pin is a version again and the TODO about the git
pin is gone.
@pytorch-bot pytorch-bot Bot added ciflow/docker ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Nov 12, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 12, 2026
@drisspg drisspg added the ciflow/b200 Trigger B200 CI label Nov 12, 2026
@drisspg

drisspg commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

@claude Please do a deep review focused on subtle correctness bugs and regressions that are easy for human reviewers to miss. Prioritize findings over summary. I dont care about anything that isnt a real bug drop all the noise but that, if you there isnt anything to report just say so with a small comment

@claude

claude Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @drisspg's task in 3m 9s —— View job


No bugs found; the Kimi K3 B200 golden still needs regenerating, as you noted. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

No correctness bugs or regressions found.

I checked each changed call site against the upstream API in meta-pytorch/attention-gym#809:

  • should_autotune(requested) returns requested and not torch.are_deterministic_algorithms_enabled(). That is the same rule torchtitan used to compute itself, so dropping the local autotune = not ... lines keeps the old behavior for l2norm and chunk_kda. The defaults for these, chunk_gdn, paged_chunk_* and gather_attn are True.
  • recurrent_gdn's RECURRENT_OPTION_SPEC accepts both autotune and batch_invariant, so {"batch_invariant": True, "autotune": False} passes validation.
  • paged_mla_decode defaults to autotune=False. The explicit {"autotune": True} is still needed and keeps the old behavior.
  • _L2Norm and _ChunkKDA resolve deterministic mode again in backward, so a forward run before deterministic mode is turned on cannot leave a tuned backward.
  • No other torchtitan call site passes autotune= (trainer, CP, RL vLLM/SGLang generators, DeepSeek-V4 gather_attn/lightning_indexer).
  • The rewritten test works as intended. TritonTuner.__getitem__ calls the module-global run_tunable in attn_gym._backends.triton.tune, so the mock.patch.object does intercept tuned Triton launches. It does not see CuTeDSL tuned launches, but the deterministic GDN path doesn't use those.

The only thing left is the Kimi K3 B200 golden, which you already list as a follow-up. The B200 job will fail until it is regenerated.

attn-gym 0.0.20 changes chunk_kda BF16 bits (meta-pytorch/attention-gym#764,
#767), so kimi_k3_mm_muon no longer matches the old reference. The new
values are from this branch's B200 run:
https://github.com/pytorch/torchtitan/actions/runs/43270645434
# its arithmetic from the batch shape.
autotune=False,
kernel_options={"batch_invariant": True},
kernel_options={"batch_invariant": True, "autotune": False},

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 only this one has explicit "batch_invariant": True?

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.

this is the only impl that has this as an option

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.

where does this change come from?

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 let CI run, grabbed the results and pasted them in here, which afaik is how it's supposed to be done

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.

oh sorry I was asking what caused the change. I guess it was because it's not update to date, since this PR should be bitwise identical to before.

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 mentioned in the summary that this pr is not expected to be bitwise identical to before we made tweaks to kda to improve numerics overall that has some bf16 1ulp rounding differences

@drisspg
drisspg merged commit aa9b8df into main Nov 12, 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/b200 Trigger B200 CI ciflow/docker 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.

gather_attn: autotuned num_warps changes output bits, so results aren't reproducible under torch.use_deterministic_algorithms(True)

3 participants