Skip to content

[QSA] sparseindexerloss teacher - #5863

Draft
liangel-02 wants to merge 1 commit into
mainfrom
qsa-indexer-teacher
Draft

liangel-02 wants to merge 1 commit into
mainfrom
qsa-indexer-teacher

Conversation

@liangel-02

Copy link
Copy Markdown
Contributor

No description provided.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 5, 2026
@liangel-02

Copy link
Copy Markdown
Contributor Author

@claude review the changes on this pr for qsa make sure it doesn't break existing dsv4 behaviour

@claude

claude Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @liangel-02's task in 2m 33s —— View job


Needs discussion: the DSV4 math is unchanged (with block_size=1 and one key head it reduces to the old teacher), but nothing in the repo uses the new QSA path yet. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Needs discussion -- DSV4 math is unchanged, but no in-repo code uses the new block/GQA path, and the open QSA stack (#5782/#5783) has its own teacher. Maintainers need to decide whether QSA should reuse DSV4's loss and where that shared code lives.

DSV4 behaviour (what you asked). Not broken, as far as I can tell from reading the code. The only DSV4 caller is attention.py:141, and it passes cmp_k_SD.unsqueeze(1) with block_size=1, so N=1 and B=1. With those values:

  • block_TKB is topk with a trailing size-1 axis.
  • compressed_gather_indices gets the same flattened input as before.
  • q.view(T,1,H,D) / lse.view(T,1,H) just split the head axis, which works on the transposed LSE.
  • The einsum lowers to the same [T,H,D] x [T,D,K] bmm.
  • sum(dim=(1,2)) over [1,H] is the old head sum.
  • The TP all-reduce runs on a tensor of the same size.
  • amax(-1) over a size-1 axis does nothing.

The DSV4 flavor (flavors.py:287) doesn't set block_size, so it gets the default of 1.

What this PR does. It generalizes SparseIndexerLoss._teacher so each selected index covers block_size consecutive key rows across N key heads (query heads grouped contiguously). It sums heads, all-reduces over TP, and then max-pools over the block rows.

Example.

DSV4:  keys [S,1,D], block_size=1 -> p_TK = sum_h exp(q_h.k_s*scale - lse_h)/H   (same as before)
QSA:   keys [T,2,D], block_size=4 -> p_TK = max_{b<4} sum_h exp(q_h.k_{4s+b}*scale - lse_h)/H

Must fix

  1. PR description is empty. Per CLAUDE.md it needs the problem, the consumer, and numerics. In particular, say which PR uses block_size>1 / N>1. Today nothing in the repo does: there is no QSA in models/qwen3_8/, and #5783 keeps its own teacher in qwen3_8_flash_next/attention.py. Without a consumer, the new field, the GQA branch and the new test (~50 lines) are speculative. Land this together with (or inside) the QSA PR that deletes its local teacher.
  2. If QSA is going to reuse this class, it can't import it from models/deepseek_v4/. Model code isn't imported across models. Move SparseIndexerLoss and compressed_gather_indices / compressed_cu_seqlens to models/common/ in that PR.

Should consider

  • compressor.py:406 -- nothing checks that block rows are causal or stay inside the query's document (inline).
  • compressor.py:341 -- the docstring's "as in Qwen3.8's QSA" claim is unverified. #5783's teacher uses a per-head softmax over the selected rows plus the tail, not the kernel LSE (inline).

Questions

  • Does QSA's attention kernel return an LSE that covers exactly the selected blocks plus the causal tail? If it also covers anything else (a window, a sink), this teacher won't match #5783's.

Not verified: I wasn't allowed to run Python in this job, so I couldn't run the CPU test or check that the old and new DSV4 teachers are bitwise identical. On GPU, the permuted einsum operand layout could in principle pick a different cuBLAS path. A 10-step DSV4 debug run with seed=42, deterministic=True before and after would settle it.

Comment on lines 406 to 410
block_TKB = torch.where(
topk_indices_TK[:, :, None] >= 0,
topk_indices_TK[:, :, None] * self.block_size + offsets_B,
-1,
)

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.

Once block_size > 1, idx * block_size + offset is never checked against the query's causal position or the end of its document. Say a query at document-local position 5 selects block 1 with block_size=4. The teacher gathers rows 4..7, which include two future tokens. No mask is applied inside the block, so the teacher puts probability mass on keys the main kernel never attends. If that block is the last one in a packed document, the extra rows come from the next document. At the end of the pool the gather goes out of bounds. The new test only ever picks complete blocks, so this case never runs.

For DSV4 (block_size=1) it can't happen, because the indexer only emits causal compressed slots. Before a QSA consumer uses this, either document the contract ("every selected block must be complete and causal for its query") or mask rows where offset_in_doc > query_pos_in_doc.

Comment on lines +341 to +345
Each selected index covers ``block_size`` consecutive rows of a key pool
with ``len_d // compress_ratio`` rows per document. Query heads share key
heads in contiguous groups. The head-aggregated probabilities are max-pooled
over each block's rows, as in Qwen3.8's QSA (``compress_ratio=1``,
``block_size=4`` over raw token keys).

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 docstring describes the class in terms of a consumer that doesn't exist in this repo. No call site passes block_size != 1 or a key tensor with more than one head. The open Qwen3.8 QSA stack (#5782/#5783) has its own teacher in qwen3_8_flash_next/attention.py. That teacher computes softmax(-1) over the selected rows plus the tail, slices off [:, :num_blocks * R], then sums heads across TP before amax. This class instead computes exp(logit - kernel_lse). The two only match if QSA's kernel LSE covers exactly the selected blocks plus the causal tail. Please either confirm that and land this together with the QSA change that deletes its local teacher, or leave the docstring out until then.

@liangel-02

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @liangel-02's task in 2m 41s —— View job


Needs discussion: the DSV4 math is unchanged, but the new block/GQA path has no consumer on main yet, and QSA can't import it from models/deepseek_v4/. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Needs discussion -- DSV4 math is unchanged. The new [T, K, B] / GQA path still has no consumer on main, and QSA (#6046) can't import it from models/deepseek_v4/. Maintainers need to decide where the shared teacher lives and whether it should land together with the QSA swap.

What this PR does. SparseIndexerLoss now takes explicit key-pool row indices [T, K, B] (-1 = unused) and keys [S, N, D], instead of document-local compressed slots plus cu_seqlens. Query heads share key heads in contiguous groups. Head-summed probabilities are all-reduced over TP and then max-pooled over B. The DSV4 caller now resolves offsets itself through compressed_gather_indices. The compress_ratio field is removed from the loss config.

Example.

DSV4 (attention.py:145): keys [S,1,D], idx = global compressed slot or -1, B=1
  p_TK = sum_h exp(q_h.k_idx*scale - lse_h)/H                      (same as before)
QSA (#6046, not wired):   keys [T,N,D], idx [T,K,4], e.g. [0,2,3,4] with token 1 padded
  p_TK = max_b sum_h exp(q_h.k_idx[b]*scale - lse_h)/H

DSV4 behaviour. I found nothing in the code that breaks it:

  • compressed_gather_indices(...).masked_fill(topk<0, -1) followed by clamp_min(0) reads the same rows as the old gather, with invalid slots still reading row 0.
  • The valid mask is the same.
  • With N=B=1, views split only the head axis. That also works on the transposed LSE.
  • The einsum reduces to the same bmm.
  • sum(dim=(1,2)) runs over [1,H].
  • amax runs over a size-1 axis.

The earlier review's causality/document-boundary concern is resolved: callers now build the rows explicitly, and the docstring states that contract.

Must fix

  1. The PR description is still empty. It should state the problem, the consumer (#6046's TODO points here), and the numerics, i.e. DSV4 loss before and after with seed=42, deterministic=True.
  2. compressor.py:344 -- there is no consumer on main, and the code is placed where its consumer can't import it. Land this with the QSA swap: move to models/common/ and delete QSA's local teacher (inline).

Should consider

  • compressor.py:401 -- the shared teacher's fp32 gather and einsum would regress QSA's tuned bf16 baddbmm teacher. Port those choices or measure before switching (inline).

Not verified: I couldn't run Python in this job. Still open: whether DSV4's teacher is bitwise identical on GPU (einsum operand layout and the two-axis sum). A 10-step DSV4 debug run before and after, comparing loss and grad_norm in TensorBoard, would settle it.

Comment on lines +401 to 406
keys_TKBND = keys_SND[indices_TKB.clamp_min(0)].float()
logits_TNMKB = (
torch.einsum(
"tnmd,tkbnd->tnmkb", q_TNMD[start:stop].float(), keys_TKBND
)
* self.softmax_scale

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.

For DSV4 (N=1, B=1) this is the same [T,H,D] x [T,D,K] bmm as before. For QSA it is slower and uses more memory than the teacher it would replace.

  • It casts the gathered keys to fp32 (.float()), which doubles the [chunk, K, B, N, D] gather.
  • With N>1, einsum has to permute tkbnd to (t n)(k b) d before the bmm, which makes another copy (unverified, from einsum's lowering).

QSA's _teacher in #6046 avoids both. It reads the keys in bf16 with fp32 accumulation, runs one strided baddbmm per KV head, and pads J to a multiple of 8. Its docstring says the padding avoids a cuBLAS path that is about 2x slower at 125B shapes. It also uses chunk_size=512 rather than 128.

If QSA switches to this class, either bring those choices into the shared teacher, or measure QSA's step time and peak memory before and after the switch.

Comment on lines +344 to +348
over compressed keys; QSA uses B=4 over selected raw token keys, e.g.
[0, 2, 3, 4] when token 1 is padding. Query heads share key heads in
contiguous groups. Head-aggregated probabilities are max-pooled over B.
The supplied LSE includes every attended key and any incomplete tail,
window, or sink.

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 docstring describes QSA, which isn't on main. Its only planned consumer, qwen3_8_flash_next (#6046), can't import from models/deepseek_v4/, because model code isn't imported across models.

The fix is to land this together with the swap. Move SparseIndexerLoss to models/common/, change QSA to call it, and delete QSAIndexerLoss._teacher / block_kl in that PR. Until then, the [T, K, B] / GQA generality, this paragraph and the new block test have no caller on main.

Note that QSA's gather_attn call currently doesn't request the LSE, so it would need return_aux=AuxRequest(lse=True) as well.

JavaZeroo added a commit to JavaZeroo/torchtitan that referenced this pull request Nov 19, 2026
kimi_k3_1 now holds only flavors. The DSA layer and its CPU test move to
kimi_k3. TODOs mark the DeepSeek V4 indexer reuse (models/common/ after
pytorch#5722 and pytorch#5863) and the missing golden for the B200 test
(meta-pytorch/attention-gym#795).
JavaZeroo added a commit to JavaZeroo/torchtitan that referenced this pull request Nov 19, 2026
kimi_k3_1 now holds only flavors. The DSA layer and its CPU test move to
kimi_k3. TODOs mark the DeepSeek V4 indexer reuse (models/common/ after
pytorch#5722 and pytorch#5863) and the missing golden for the B200 test
(meta-pytorch/attention-gym#795).
JavaZeroo added a commit to JavaZeroo/torchtitan that referenced this pull request Nov 19, 2026
kimi_k3_1 now holds only flavors. The DSA layer and its CPU test move to
kimi_k3. TODOs mark the DeepSeek V4 indexer reuse (models/common/ after
pytorch#5722 and pytorch#5863) and the missing golden for the B200 test
(meta-pytorch/attention-gym#795).
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.
sdmyzlp added a commit that referenced this pull request Nov 23, 2026
## Summary (human-written)
Transform the previous `Indexer.select` operation to be a dedicated
module inside `class Indexer`, has following benefits:

1. Making `Indexer` more self-contained, and simplify the forward
signature of `inner_attention`.
2. Prepare for DeepSeek-V4.1, which reuse the output of Indexer across
layers. And since the indexer loss (gradient) is linear w.r.t. teacher
distribution, one can also leverage the autograd to accumulate the
gradient for `topk_scores`.

## Why

`Indexer.select` used to be called by `DeepSeekV4Attention` on the
indexer's raw features, so the inner-attention module owned the
selection call and its `return_scores` decision. This PR moves selection
behind the indexer boundary and changes the inner-attention contract to
consume the selection result.

```python
# before
idx_q, idx_k, idx_w = self.indexer(x, qr, positions=..., attention_metadata=md)
cmp_topk, topk_scores = Indexer.select(idx_q, idx_k, idx_w, ..., attention_metadata=md)

# after
topk_indices, topk_scores = self.indexer(
    x, qr, positions=..., attention_metadata=md,
    return_scores=...,
)
self.inner_attention(q, kv, cmp_k, topk_indices, attn_sink, topk_scores=topk_scores)
```

## What changed

One interface-focused commit:

- `compressor.py`: `InnerIndexer` owns selection. `InnerIndexer.Config`
stores the fixed `ratio` / `topk`, so `Indexer.forward` and
`InnerIndexer.forward` no longer pass them per call.
- `attention.py`: `CompressedSparseAttention.forward` takes
`topk_indices` / `topk_scores`; `DeepSeekV4Attention` no longer carries
a separate `index_topk`. `flops_per_token` reads
`indexer.inner_indexer.topk`, so `index_topk` has a single source of
truth.
- `flavors.py`: `_make_indexer_config` receives `index_topk` and builds
`InnerIndexer.Config`.
- `sharding.py`: the inner-attention kernel declares `topk_indices` /
`topk_scores`, and `InnerIndexer` gets its own local-SPMD config.
- Selection width uses `attention_metadata.max_k`, so packed documents
keep the per-document width. The empty-key-pool guard is removed; the
pool is assumed non-empty.
- `return_scores=False` returns `[T, 0]` scores so the inner-attention
boundary always receives tensors.

## Out of scope (follow-up PRs)

SPMD typechecking and TP placement are deliberately not changed here:

- `spmd_typechecking` for DeepSeek-V4 is still not green. The 3-D query
partition spec, compressor metadata typing, HC sharding, and
MoE/debug-router paths are follow-up work.
- `idx_q` / `idx_k` / `idx_w`, `topk_indices` / `topk_scores`, and the
indexer parameters remain `R`. Moving them to `spmd.I` and removing the
`1/TP` aux-loss gradient compensation is a separate change.
- MHC/HC sharding is untouched; aligning it with the Norm SP/non-SP I/R
split is a separate change.

## Numerics and performance

Refactor only; no intended numerics change. The H800 comparison below
was collected on `e87dc0dff`, an earlier revision of this same interface
(base `8592e69c3`). The current commit keeps the same `(R, R)` indexer
boundary and only moves `ratio`/`topk` into config and removes the
duplicate `index_topk`; a fresh H800 run on `63f6a8e14` is still the
cleanest confirmation.

FSDP2 + TP2 (`dp_shard=2, tp=2, ep=2`) and the TP2 control
(`dp_shard=1`), debugmodel with packed documents and the indexer aux
loss on, seed 42, 10 deterministic steps:

| Run | step 1 loss / grad_norm | step 10 loss / grad_norm |
| --- | --- | --- |
| FSDP2 + TP2 | 8.125130653381348 / 3.866826057434082 |
3.6977646350860596 / 1.6038713455200195 |
| TP2 control | 8.079805374145508 / 4.087775230407715 |
3.6074934005737305 / 1.8479396104812622 |

Base and this revision were bit-identical at every step. With
`index_topk=1024`, the width fix used 4.21 GiB vs 6.71 GiB pre-fix and
all revisions stayed bit-identical.

## Testing

```sh
python -m pytest -q tests/unit_tests/cpu/models/deepseek_v4 \
  tests/unit_tests/cpu/test_deepseek_v4_indexer_loss.py \
  tests/unit_tests/gpu/models/deepseek_v4/test_deepseek_v4_attention.py \
  tests/unit_tests/cpu/recipes/test_deepseek_v4_dist_muon.py \
  tests/unit_tests/cpu/models/test_state_dict_adapter.py::DeepSeekV4StateDictAdapterTest
```

36 passed, 3 CUDA cases skipped. Pre-commit passes on the changed files.

## Known issues / follow-ups

- SPMD typechecking, TP-invariant indexer sharding, and MHC/HC sharding
are follow-up PRs, as above.
- #5863 can rebase onto `topk_indices` / `topk_scores` and
`InnerIndexer` after this lands.
- Moving `tests/unit_tests/cpu/test_deepseek_v4_indexer_loss.py` into
the mirrored `models/deepseek_v4/` directory is a separate change.
JavaZeroo added a commit to JavaZeroo/torchtitan that referenced this pull request Nov 23, 2026
kimi_k3_1 now holds only flavors. The DSA layer and its CPU test move to
kimi_k3. TODOs mark the DeepSeek V4 indexer reuse (models/common/ after
pytorch#5722 and pytorch#5863) and the missing golden for the B200 test
(meta-pytorch/attention-gym#795).
shuhuayu pushed a commit that referenced this pull request Nov 24, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

Add Kimi K3.1 Pro. It differs from K3 only in its 24 full-attention
layers, which change from Gated MLA to Gated DSA. So this PR reuses the
K3 backbone, adds the DSA layers with DSV4's existing top-k selection
and indexer loss, and runs the sparse attention with Attention Gym's
gather_attn.

I've already checked the model code, model accuracy, test cases, and the
model README.md

## Why
Kimi K3.1 Pro (RFC #5936) is Kimi K3 with its 24 Gated MLA layers
replaced by Gated DeepSeek Sparse Attention (DSA). torchtitan cannot
build, train or load it today.

```python
from torchtitan.models.kimi_k3_1 import build_model_config

config = build_model_config("Kimi-K3.1-Pro", parallelism=parallelism)
```

## What changed
- New `torchtitan/models/kimi_k3/dsa.py`: the indexer and the sparse
attention. Top-k selection and the indexer loss are imported from
`deepseek_v4/compressor.py`; DSV4 is not changed. Attention over the
selected tokens runs Attention Gym `gather_attn` with `(latent, rope)`
pairs, under `spmd.no_typecheck()` as in DSV4.
`KimiSparseAttention.Config.impl` picks the `gather_attn` implementation
(`"fused"` by default).
- New `torchtitan/models/kimi_k3_1/`, flavors only like `qwen3_6`:
- `flavors.py`: `debugmodel` and `Kimi-K3.1-Pro` (text only), plus
`debugmodel_mm` and `Kimi-K3.1-Pro_mm` with the vision encoder, built
with the K3 config builder like the K3 flavors. `build_model_config`
raises unless each TP rank has 16 to 128 query heads, which the pair
kernel needs.
- Kimi K3:
- The block passes `padding_mask` and `aux_loss_denominator` to Kimi MLA
attention. K3 ignores them; the K3.1 DSA attention uses them.
- `KimiK3Model` registers the aux-loss zero hook, and
`KimiK3StateDictAdapter` maps the five indexer tensors. Both are no-ops
for K3.
  - `kimi_k3_config` takes a `full_attention_config_factory`.
- `mla_attention_config` is split out of `mla_config` so K3.1 reuses the
MLA projections.
- Mechanical: four private helpers become public; two K3 tests are
updated.
- Recipes: a K3.1 debug recipe. The K3 DistMuon builder gets one
optional argument so K3.1 can add the indexer weights.
- Tests: `kimi_k3_1_fsdp2_tp2_ep2_pp2_vpp4` in the B200 integration
suite, the same shape as the K3 cell, without a golden for now.
- README: the supported parallelisms and the parity check.

## Numerics
| Check | Result |
| --- | --- |
| Kimi K3 debug model, main vs this branch, 10 steps, 1 GPU | loss and
grad_norm bitwise equal; configs identical |
| One K3.1 DSA layer (random weights) vs vLLM's K3.1 DSA forward in
plain PyTorch (no HF model code is released) | fp32 (CPU): same top-k,
relative L2 6.6e-7; bf16 (H100): top-k overlap 99.6%, relative L2 7.2e-3
|
| Kimi K3.1 debug model, 20 steps, 2x H100, same seed checkpoint: FSDP 2
+ EP 2, TP 2 + EP 2 (32 heads), PP 2, each vs its 1- or 2-GPU baseline |
step 1 grad_norm equal; loss differs by up to 4.6e-3 to 8.0e-3, while
two runs of the same baseline differ by up to 4.9e-3 to 6.0e-3 (the pair
backward is not deterministic) |

## Testing
```
pytest tests/unit_tests/cpu/models/kimi_k3/ tests/unit_tests/cpu/models/test_build_model_config.py
NGPU=1 MODULE=torchtitan_recipes.tests.models.kimi_k3_1 CONFIG=kimi_k3_1_debugmodel ./run_train.sh
```
The H100 Kimi integration tests (`kimi_k3_mm_allgather_kv_cp`,
`kimi_k3_mm_ulysses_cp`) pass on 2x H100.

## Known issues / follow-ups
- Not verified: parallel combinations larger than 2 GPUs. CP is not
supported; the CP transform raises for the K3.1 sparse attention.
- `gather_attn` has no deterministic backward for `(latent, rope)` pairs
yet, so K3.1 raises with `debug.deterministic = True`, and the
integration test has no golden: meta-pytorch/attention-gym#795.
- K3.1 is the second user of the DSV4 `InnerIndexer` and
`SparseIndexerLoss`. Move them to `models/common/` after #5863 lands.
- `KimiDSAAttention` subclasses `KimiMLAAttention` on purpose: the MLA
weights are the same, so the K3 HF mapping and Muon grouping apply as
is.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

1 participant