Repository navigation
[gdn] Honor deterministic GDN normalization - #5784
Conversation
b2aca89 to
71eb967
Compare
b292f9c to
cbe9b3c
Compare
71eb967 to
223be19
Compare
cbe9b3c to
e15a1f6
Compare
223be19 to
51b450b
Compare
e15a1f6 to
b4b0b68
Compare
51b450b to
6608e4e
Compare
c339afc to
ac5a16a
Compare
72d0de7 to
bc22fd5
Compare
ac5a16a to
7bba104
Compare
bc22fd5 to
f72e254
Compare
7bba104 to
ff98eea
Compare
f72e254 to
ba80b84
Compare
ff98eea to
d9413c0
Compare
ba80b84 to
f521fcb
Compare
f521fcb to
28f038a
Compare
28f038a to
54edd65
Compare
|
@claude review |
| 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) |
There was a problem hiding this comment.
why this is not changed in attention-gym?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
sure, but my question is -- why couldn't attn-gym's function check torch.are_deterministic_algorithms_enabled() internally
stamping to unblock anyway
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
sure, but my question is -- why couldn't attn-gym's function check torch.are_deterministic_algorithms_enabled() internally
stamping to unblock anyway
## 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.
Summary (human-written)
this pr is to add
deterministicoption 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_bwdbefore 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.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
Numerics and testing
2.16.0.dev20261030+cu132, revisionbf270c3251d8e84723cedbf5b60eaa60cacaa3f2; seed 42 and strict determinism. No production kernel or runtime patch is used.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
mainatc62c6a7552137d10d4fc3927aa20dcd69925aaf2. 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.2.16.0.dev20261108+cu132, revision1392e1f8e4903657d4391f3bd8fcc9ca8a74b758; Attention Gym0.0.19.dev10+g26beb363c, pinned revision26beb363c6d1328851bfc5c9c8691fa2066bd1fa.test_deterministic_backward_bypasses_normalization_autotunerpasses on a GB300, covering ordinary and batch-invariant GDN forward/backward with finite, nonzero gradients.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.Local all-file hooks pass; Pyrefly uses the pinned validation runtime and isolated optional-dependency stubs. GitHub CI is pending.