Repository navigation
Conversation
|
@claude review |
There was a problem hiding this comment.
Verdict: Request changes -- under FSDP the QSA indexer can end up with None grads on some ranks, and the QSA training path's saved activations grow with sequence length times the 2,048-token budget. An attention-gym path for the same pattern already exists in deepseek_v4.
What this PR does. Adds torchtitan/models/qwen3_8_flash_next/, built on Qwen35Model. The model has a four-stream gated residual, a hashed n-gram PLE in layer 1, and QSA every fourth layer (the other layers are Qwen3.5 GDN). QSA is an indexer that picks top-k complete 4-token blocks, plus selected-token SDPA and an optional indexer KL loss. The PR also makes two Qwen3.5 config factories public, widens the shared router gate type to Linear.Config, and turns AttentionMetadata into a Protocol. FSDP only; TP, EP, PP and CP raise.
Example. build_model_config("debugmodel", seq_len=64, parallelism=ParallelismConfig()) builds 8 layers, with QSA at layer_id 3 and 7 and GDN elsewhere. Activations go [T, 256] -> repeat -> [T, 1024]. In each block, a gated read gives [T, 256], then attention or MoE, then a gated write back to [T, 1024]. With token_budget=16, a QSA query at position 38 of one document attends to the 4 best complete earlier blocks (16 tokens) plus its own incomplete tail of up to 3 tokens. Each attended token is gathered per query, then attended with SDPA MATH.
Must fix
- PR description. "Summary (human-written)" is empty. Also, the title says "1/n Add Flash-Next model", but commit e0aceb3 is "2/n Add Flash-Next model" and the body says "TP/SP and EP follow in 2/n".
- Design: the QSA training path doesn't scale (
attention.py:182-209,:282-320). It is a Python loop over 16-query chunks that gathers K/V per query and runs SDPA MATH. The saved activations are about 4 MB per token per QSA layer at the released settings, plus an O(T^2) indexer score term (inline comment).deepseek_v4/compressor.pyanddeepseek_v4/attention.pyalready do indexer top-k, gathered sparse attention and KL distillation on attn_gym'slightning_indexer/gather_attn(meta-pytorch, allowed by core principle 3). Please say whether those kernels can express QSA (4-token blocks plus tail, 2 KV heads). If they can, use them. If not, add a TODO with an attention-gym issue link, and state in the README which sequence lengths are trainable. attention.py:281-299-- indexergrad=Noneon ranks with no complete block, so FSDP2 reduce-scatters may not match (inline comment, with a one-line fix).
Should consider
attention.py:236--QSAInnerAttention.Config.num_headscancels inblock_kl; delete it.norm.py:56-- renamed kwargs force rewriting the sharding config inflavors.py:410-416, and the override drops@local_compile.state_dict_adapter.py:120-- the MTP warning never fires on the DCP path; drop the keys explicitly instead.test_qwen3_8_flash_next.py:488-- the shard-order test can't catch the sort bug it is named for. The file also belongs in aqwen3_8_flash_next/test folder.numerical_tests_qwen3_8_flash_next.py:182-- imports private GPU-test helpers and monkeypatches production code.tests/assets/qwen3_8_flash_next/checkpoint_schema.json(1,635 lines) has one consumer, and no other model keeps such an asset. Replace it with a compact check: key count, one GDN-layer and one QSA-layer key pattern, the shard count, and a hash of the sorted names.embedding.py:67,78-- the "feature-sharded" docstrings are inaccurate:NGramTableis replicated over TP and all-gathered whole by FSDP. For125B-A6Bthat means all-gathering a 51.2B-parameter table in both forward and backward. Either reject that flavor for training or document it.- Tests that don't earn their cost:
test_router_bfloat16_ties_mixing_and_backward[compiled]exercises a path no recipe enables.test_packed_padding_is_excluded_from_moe_auxiliary_gradientsmostly duplicatescommon/test_moe.py, and it swaps out the configuredbatch_wiseloss.test_deltanet_uses_sigmoid_output_gateruns in FP32 with ones-initialized weights, so it can't tellInputDtypeGatedRMSNormapart from the base class.
torchtitan_recipes/tests/models/qwen3_8_flash_next.py:49--qwen38_flash_next_debugmodel_achas no consumer.
Questions
- With
indexer_loss=None(the default), the indexer never gets a gradient, so training from scratch keeps it at random init. Is that intended? If only fine-tuning is supported in that mode, should training withindexer_loss=Noneraise? - N-gram hashing resets history at EOS and at
positions == 0, but the PLE conv and QSA visibility reset only atpositions == 0. Does that match the reference?
Details
- Shared changes. These look fine.
HiMidLoLinearsubclassesLinear, so every existing router config still type-checks, and noisinstancecheck depends on theAttentionMetadataunion. Theqwen3_5/flavors.pyrenames are mechanical. - FSDP2 grad handling.
post_backwardcollects only params whoseunsharded_param.grad is not None. So a rank with zero complete blocks in its microbatch sends a smaller reduce-scatter for that block's FSDP unit. - Memory arithmetic (released config). Per query, the gathered K is 2 KV heads x 2051 tokens x 256 dims x 2 bytes = 2.1 MB, and V is the same. That is about 4.2 MB per token per QSA layer, kept for backward, before any MATH-backend GQA repeat.
- Hidden syncs. The
.nonzero()calls inQSAIndexMetadata.from_inputssync once per step, andmin(block_topk, block_ends_G.numel())makes shapes data-dependent. Accelerator graphs are rejected, so this is acceptable for now, but any compiled region around the indexer would recompile every step.
Not verified: the FSDP2 desync and the memory estimates were not reproduced on GPUs. Whether gather_attn supports multiple KV heads is unverified.
| raw_sum = scores_TB.new_zeros(()) | ||
| for start in range(0, query_THK.shape[0], self.chunk_size): | ||
| stop = start + self.chunk_size | ||
| indices_QJ = selected_indices_TJ[start:stop].long() | ||
| valid_QJ = indices_QJ >= 0 | ||
| query_QH1K = query_THK[start:stop].unsqueeze(2) | ||
| keys_QHJK = key_THK[indices_QJ.clamp_min(0)].transpose(1, 2) | ||
| values_QHJV = value_THV[indices_QJ.clamp_min(0)].transpose(1, 2) | ||
| with sdpa_kernel(SDPBackend.MATH): | ||
| output_QHV = F.scaled_dot_product_attention( | ||
| query_QH1K, | ||
| keys_QHJK, | ||
| values_QHJV, | ||
| attn_mask=valid_QJ[:, None, None], | ||
| scale=scale, | ||
| enable_gqa=enable_gqa, | ||
| ).squeeze(2) | ||
| outputs.append(output_QHV) | ||
| if train_indexer and num_blocks: |
There was a problem hiding this comment.
Indexer params can get grad=None on some ranks, so FSDP2 reduce-scatters may not match. The KL is the indexer's only gradient path: its input is x_TD.detach() (L370) and the selected indices are integers.
When a rank's microbatch has no complete 4-token block (all padding, or every document shorter than 4 valid tokens), num_blocks == 0. Then raw_sum stays the detached new_zeros(()), and index_qk_proj, q_layernorm and k_layernorm get grad=None on that rank while other ranks have grads. FSDP2 only reduces params whose grad is not None, so the ranks would issue different reduce-scatters. The all_padding unit test runs in one process and can't catch this.
Smallest fix: seed the sum from the graph, so the inject always carries a (zero) indexer gradient.
raw_sum = scores_TB.sum() * 0 # keep indexer params in the graph on every rankI haven't reproduced this on multiple GPUs.
| query_QH1K = query_THK[start:stop].unsqueeze(2) | ||
| keys_QHJK = key_THK[indices_QJ.clamp_min(0)].transpose(1, 2) | ||
| values_QHJV = value_THV[indices_QJ.clamp_min(0)].transpose(1, 2) | ||
| with sdpa_kernel(SDPBackend.MATH): | ||
| output_QHV = F.scaled_dot_product_attention( | ||
| query_QH1K, | ||
| keys_QHJK, | ||
| values_QHJV, | ||
| attn_mask=valid_QJ[:, None, None], | ||
| scale=scale, | ||
| enable_gqa=enable_gqa, | ||
| ).squeeze(2) |
There was a problem hiding this comment.
Saved activations here grow as T x J, not with the chunk size. Each 16-query chunk gathers keys_QHJK and values_QHJV with J = 2048 + 3, 2 KV heads and head dim 256. MATH SDPA keeps these inputs for backward. At the released settings that is about 2 MB per token each for K and V, so roughly 17 GB per QSA layer at T=4096, with 12 QSA layers. That is before any GQA expansion inside the math backend (unverified). The indexer's scores_QHG.relu() adds another O(T^2) fp32 term (L184-187).
The README says gathers are "bounded by query chunks". That holds for transient memory only, not for what is saved for training. See the design item in the review body: deepseek_v4 already runs indexer top-k plus gathered sparse attention through attn_gym's lightning_indexer / gather_attn.
| @dataclass(kw_only=True, slots=True) | ||
| class Config(InnerAttention.Config): | ||
| compress_ratio: int | ||
| num_heads: int |
There was a problem hiding this comment.
num_heads has no effect. Its only use is / self.num_heads at L311. teacher_QB is then renormalized in block_kl (L225-226), so the constant cancels. The field also duplicates QSAAttention.Config.n_heads without a consistency check. Delete the field, the attribute and the division.
| class Config(GatedRMSNorm.Config): | ||
| pass | ||
|
|
||
| def forward(self, input_THD: torch.Tensor, gate_THD: torch.Tensor) -> torch.Tensor: |
There was a problem hiding this comment.
The override renames the base kwargs input/gate to input_THD/gate_THD. That rename is the only reason flavors.py:410-416 has to copy and rewrite gated_rms_norm_sharding_config() keys behind an assert. The override also drops the base class's @local_compile("gated_rmsnorm", batch_invariant=False).
Keep the parent's parameter names and the decorator, then pass gated_rms_norm_sharding_config() unchanged in flavors. That removes about 6 lines.
| if any(key.startswith("mtp.") for key in state_dict): | ||
| logger.warning( | ||
| "The Flash-Next Transformers reference excludes the MTP draft head; loading the backbone and vision weights only." | ||
| ) |
There was a problem hiding this comment.
This warning never fires on the HF load path. DCP calls to_hf, loads only those keys, then calls from_hf, so mtp.* never arrives here. In offline conversion the keys are actually dropped by the parent's silent continue on unmapped keys.
Following "explicit over implicit", drop the MTP keys deliberately with a comment saying why (MTP is outside this model), and remove the warning. Related: ple = self.flash_config.layers[layer_id].ple at L108 raises AttributeError rather than ValueError for shards on a layer without PLE.
|
|
||
|
|
||
| def test_adapter_roundtrip_and_numeric_shard_order(config): | ||
| model = config.build() | ||
| model.init_states() | ||
| adapter = Qwen38FlashNextStateDictAdapter(config, None) | ||
| state = model.state_dict() | ||
| hf = adapter.to_hf(state) |
There was a problem hiding this comment.
The name says "numeric_shard_order", but this test can't catch a lexicographic-sort bug. The debug flavor has split_parts=4, and shard_0..shard_3 sort the same either way; the bug needs 11 or more parts (shard_10 before shard_2). Reversing dict order only shows the result doesn't depend on insertion order.
Either build the adapter with split_ngram_parts >= 11 or rename the test.
Separately, this file should live in tests/unit_tests/cpu/models/qwen3_8_flash_next/, matching the sibling qwen3_5/ and qwen3_8/ folders.
| from tests.unit_tests.gpu.models.qwen3_5.test_qwen3_5_deltanet import ( | ||
| _reference_causal_conv1d_varlen, | ||
| ReferenceGatedDeltaKernel, | ||
| ) | ||
| from torchtitan.models.common.attention.gdn import GDN | ||
|
|
||
| for layer in native.layers.values(): | ||
| if isinstance(layer.attention, GDN): | ||
| layer.attention.inner_attention.kernel = ReferenceGatedDeltaKernel() | ||
| reference_stack.enter_context( | ||
| patch( | ||
| "torchtitan.models.common.attention.gdn._causal_conv1d_varlen", | ||
| _reference_causal_conv1d_varlen, | ||
| ) | ||
| ) |
There was a problem hiding this comment.
The script depends on private test internals and monkeypatches:
- It imports
_reference_causal_conv1d_varlenfrom a GPU test module (here and again at L769). - It patches
gdn._causal_conv1d_varlenand replaces the kernel object. - It patches
RoutedExperts.forwardwith an FP32 oracle (L220-222).
Any rename in those tests silently breaks this script, and the parity check no longer runs the production path. _run is also a single ~1000-line function, where sibling scripts (qwen3_5: 447 lines) split into build/run/compare.
Please either promote the reference kernels to a non-test, non-private location that both consumers import, or drop the patched variants. The script is 1,184 lines; the patched variants are a large share of it.
f387642 to
1232b90
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. All three earlier must-fix items are resolved at 1232b90. One small new item remains: a dead runtime check. This PR touches shared code (common/moe/moe.py, qwen3_5/flavors.py, tests/integration_tests/models.py), so a maintainer still needs to review.
What this PR does. It adds torchtitan/models/qwen3_8_flash_next/ on top of Qwen35Model. The model has four gated residual streams, a hashed n-gram PLE in layer 1, and block-selecting QSA every fourth layer; the other layers are Qwen3.5 GDN. The PR also makes two Qwen3.5 config factories public and widens the router gate type to Linear.Config. Only FSDP is supported; TP, EP, PP and CP raise in build_model_config.
Example. build_model_config("debugmodel", seq_len=64, parallelism=ParallelismConfig(data_parallel_shard_degree=2), indexer_loss=QSAIndexerLoss.Config(...)) gives 8 layers, with QSA at layers 3 and 7. Take a rank whose microbatch has no complete 4-token block. Before, its indexer params had grad=None while other ranks had grads. Now raw_sum = scores_TB[..., :0].sum() keeps the indexer in the graph, so every rank reduce-scatters the same params (the 2-GPU test_indexer_gradient_participation covers this).
Earlier must-fix items
- PR description: resolved. The human-written summary is present, and the commit titles match "1/n".
- QSA training memory: resolved. Dense scoring and gathered SDPA run under per-chunk nonreentrant checkpoints, the code has an Attention Gym TODO with a link, and the README lists the qualified sequence lengths.
- FSDP
grad=Noneon empty ranks: resolved, with a CI-run multi-GPU regression test.
The earlier should-consider items are also addressed: the num_heads field is gone, norm.py kwargs and @local_compile are restored, MTP keys are dropped explicitly, the 16-shard order test is in place, the tests moved to their own folder, the 47-line schema digest replaces the 1,635-line asset, the harness no longer patches anything, the embedding docstrings are fixed, and the _ac recipe is removed. The README answers both earlier questions (frozen selector, EOS vs. position resets).
Must fix
attention.py:98-105-- the accelerator-graph check inQSAIndexMetadata.from_inputsnever fires in training, because metadata is built during preprocessing, outside capture. Its test only passes because it mocks the capture state. Delete both (inline).
Should consider
attention.py:348--.long()makes the checkpoint save an int64 copy of the selected indices instead of the int32 tensor (inline).attention.py:351-352-- the comment says nestedtorch_remat.checkpointis unsupported. That is an upstream gap, and it is the reason this file usestorch.utils.checkpointinstead oftorch_remat(whichdirection.mdsays to build on). Turn it into aTODOwith a torch_remat issue link.
Details
- Why the check is dead.
TrainingEngine._preprocess_microbatch_groups(training_engine.py:684) callspreprocess_inputsbefore_run_forward_backward. That path reachesQSAInnerAttention.Config.build_attention_metadata, thenfrom_inputs, which is where the check sits. Themetadata is Nonefallback inQSAIndexer.forwardis never taken underDecoder. When graphs are on, the actual failure isAcceleratorGraphWrapper._validate_inputsraising on the first metadata shape change. That error is explicit, not silent, so this is dead code rather than a correctness bug. - Frozen selector.
QSAAttention.__init__freezes the indexer whenindexer_loss=None, andforwardruns selection with grad disabled unless the model is training with KL configured. The empty-slice sum is finite even when every score is-inf, so the NaN case described in the PR doesn't arise. - Shared changes. These are unchanged since the last review and still fine: every existing
HiMidLoLinearrouter gate is aLinear.Configsubclass, and theqwen3_5renames are mechanical.
Not verified: the GPU and HF parity results, the memory table, and that int32 indexing preserves numerics bitwise (none of these were run here).
| if ( | ||
| accelerator_graphs_supported() | ||
| and torch.get_device_module().is_current_stream_capturing() | ||
| ): | ||
| raise ValueError( | ||
| "Flash-Next QSA uses dynamic block selections; set " | ||
| "training.disable_accelerator_graphs=True" | ||
| ) |
There was a problem hiding this comment.
This check never fires during training. The trainer builds attention metadata in preprocess_inputs, and _preprocess_microbatch_groups runs outside capture (training_engine.py:684: "Preprocess all microbatch groups outside CUDA capture"). So is_current_stream_capturing() is always False when QSAInnerAttention.Config.build_attention_metadata calls this. The only in-capture caller is the metadata is None fallback in QSAIndexer.forward, and Decoder always passes metadata.
With the default disable_accelerator_graphs=False, a user gets this error only after warmup, and it is the generic one: the wrapper's _validate_inputs raises "Accelerator graph tensor inputs must keep the same shape" once the block count G changes. The test at test_qwen3_8_flash_next.py:75 mocks both accelerator_graphs_supported and the device module, so it passes even though the trainer never reaches this branch.
Fix: delete this block, its import, and the mocked test. The README already documents the disable_accelerator_graphs=True requirement, and every recipe sets it. A real config-time rejection would need a hook in config/validation.py, and that core change isn't worth making for one model.
| raw_sum = scores_TB[..., :0].sum() | ||
| for start in range(0, query_THK.shape[0], self.chunk_size): | ||
| stop = start + self.chunk_size | ||
| indices_QJ = selected_indices_TJ[start:stop].long() |
There was a problem hiding this comment.
.long() creates an int64 copy of each chunk's indices, and the nonreentrant checkpoint at L353 saves it as an input for backward. The indexer deliberately returns int32 (.int() at L266), and this cast undoes that for the saved state. At the released J = 2,051, that is about 16 KB per token per QSA layer, against 8 KB for an int32 view. That works out to roughly 0.8 GB vs 0.4 GB at 4,096 tokens across 12 QSA layers (arithmetic only).
PyTorch advanced indexing accepts int32 index tensors, so dropping .long() should be enough: key_THK[indices_QJ.clamp_min(0)] in both _selected_attention and the teacher. I haven't run this.
1232b90 to
3f39d6f
Compare
3f39d6f to
48314a2
Compare
0f6481b to
3bb96e0
Compare
3bb96e0 to
0972e3a
Compare
0972e3a to
06c11e0
Compare
f521fcb to
28f038a
Compare
06c11e0 to
2854b18
Compare
3673607 to
1730599
Compare
Use native projections with saved-child remat support, and build optimizer layouts at recipe construction with validation-only post-init. Use public collective and DCP contracts, remove redundant lookup permutations, require one PLE layer, and keep optimizer policy and PLE documentation with their owners.
1730599 to
4e77ce4
Compare
NGramTable already rejects tables whose rows do not divide the DP degree, so the uneven and empty-owner paths in the row-sharded lookup and HF adapter could not run. Require divisibility in the helper, drop the empty-owner placeholder path from the adapter, and type the lookup weight as the Shard(0) DTensor its only caller passes. Remove lookup tests for unsupported layouts and the clipping/DCP test that exercised PyTorch rather than the helper. Bitwise-neutral for supported configurations.
Replace the per-16-query checkpointed gather + MATH SDPA loop with one gather_attn call: selected blocks and the incomplete tail are sparse KV indices into the packed sequence (no sliding window), with separate values and grouped KV heads. CUDA uses the fused kernel (Triton grouped schedule, SM100/SM103); CPU uses the reference implementation, as in DeepSeek-V4. The indexer and the no-grad indexer teacher are unchanged. Requires the attn-gym pin at 0d0197fb (pytorch#6017) for sparse_v and the grouped fused kernels. Numerics (GB300, released 125B-A6B QSA shapes, T=4096, bf16 vs fp64 oracle, relative error out/dq/dk/dv): fused 3.4e-3/4.4e-3/4.4e-3/3.6e-3, previous eager 3.1e-3/4.0e-3/9.1e-3/8.2e-3. Fused outputs and gradients are bitwise identical across processes and cold Triton caches. Forward+backward per QSA layer: 3.3 ms vs ~10 s. Debug model, 2 GPUs, seed 42, 10 steps: losses match to ~1e-3 (step 10: 7.49278 vs 7.49127). Drop the attention test's saved-storage budget, which guarded the removed checkpoint; keep its dense masked-SDPA output and gradient check.
Replace the per-chunk dense ranking (argsort over every complete block) with lightning_indexer, as in DeepSeek-V4. It runs over valid tokens only, with per-document offsets in valid-token space, so its compress_ratio candidates are exactly QSAIndexMetadata's document-local blocks even with padding inside a document. Selected blocks are sorted ascending for a backend-independent slot order. The KL scores of the selected blocks keep the previous math: one dense GEMM per checkpointed query chunk, then a gather (gathering per-query keys makes backward a scatter-add, ~30x slower). Ties: ReLU scores tie exactly (2.2% of selected scores at random init, released shapes). Under deterministic algorithms the CuTe backend resolves them toward earlier blocks, as before; otherwise the cutoff choice is backend-defined. The CPU tie test is removed: on CPU it exercises Attention Gym's reference torch.topk, which does not order ties. Released 125B-A6B indexer shapes on GB300 (T=4096, two documents, interior and trailing padding): with deterministic algorithms all 4096 rows select the same blocks as the previous ranking and the selected scores are bitwise equal; without, 132/4096 rows swap blocks with exactly equal cutoff scores. Indexer forward+backward: 51 ms vs 64 ms. Debug model, 2 GPUs, seed 42, 10 steps: step 1 loss is identical, later steps within 2e-3 of the previous commit.
## Why The Qwen3.8-Flash-Next QSA attention (#5782) will use `gather_attn`'s grouped-KV / separate-V Triton kernels. They first appear in attention-gym v0.0.19, after attention-gym #678, #701, #702, #713, #714, #715 and #703. torchtitan pins `26beb363`, which predates all of these. This PR only bumps the pin; the Flash-Next change stays in #5782. ## What changed (all mechanical) | | Before | After | | --- | --- | --- | | attn-gym pin | `26beb363` (#704 merge) | `0d0197fb` (v0.0.19 tag, #703 merge) | - `.ci/docker/requirements.txt` (root `requirements.txt` symlinks to it): new SHA. The TODO now says to switch to the PyPI release once v0.0.19 is published there (PyPI's newest is 0.0.18). #704, which the old TODO waited on, is already included in both pins. - `torchtitan/models/common/attn_gym.py` (install hint) and `tests/unit_tests/cpu/models/common/test_optional_imports.py` (2 asserts): same SHA. ## Why v0.0.19 rather than attention-gym `main` `26beb363..0d0197fb` changes only `attn_gym/sparse/gather_attn` (plus its tests and docs). I diffed the two installed `attn_gym` trees to confirm this. GDN, KDA, short_conv, the indexer, MLA and the CuTe backend are byte-identical, so qwen3_5, qwen3_8, kimi and the deepseek_v4 indexer can't change. `main` would also pull in the warpdrive rewrite and the indexer/delta-H ports (~28 `_delta_rule` files). ## Numerics The only `gather_attn` consumer is `torchtitan/models/deepseek_v4/attention.py`. Old vs new pin, 10 steps, seed 42, deterministic, loss and grad_norm read from TensorBoard via `scripts/loss_compare.py`, on GB300: | Config | GPUs | Result | | --- | --- | --- | | `deepseek_v4_debugmodel_fsdp4_ep4` (DistMuon) | 4 | bitwise identical* | | `deepseek_v4_debugmodel_fsdp2_tp2_ep2_pp2` with dp_shard=1 (host has 4 GPUs) | 4 | bitwise identical* | \* With `gather_attn`'s Triton tuners pinned to the same candidate in both runs. Without pinning, deepseek_v4 isn't run-to-run reproducible on **either** pin when the autotune cache is cold. `_FWD_TMA` and `_BWD_DLOCAL_KV_TMA` choose `num_warps` 4 vs 8 by timing, and the two give different bits. Ranks and cold-cache runs can pick different winners, and torch's deterministic flag doesn't control this. This already happens on main. I filed it upstream as meta-pytorch/attention-gym#777, with a single-GPU repro. Because of it, this PR adds no deepseek_v4 golden; see follow-ups. ## Testing - `pre-commit run --all-files` passes, including `pyrefly-check`. - `pytest tests/unit_tests/cpu/models/common` plus the deepseek_v4, qwen3_5, qwen3_8 and kimi_k3 CPU tests: 416 passed. The same 9 tests fail with both the old and new pin on this aarch64 host (`test_lora_forward` and 8 qwen3_5 tests). The one I inspected, `test_lora_forward`, fails with "torch.compile on current platform is not supported for CPU". ## Known issues / follow-ups - deepseek_v4 golden numerics: add once attention-gym#777 lets us fix the tile config. The golden then has to be exported on CI's A10G runners, not on GB300.
…r chunk The teacher replicated the gathered keys from 2 KV heads to all 24 query heads, cast them to fp32 and took the dot products as an elementwise multiply and sum over a [16, 24, 2051, 256] tensor per 16-query chunk. On the 125B on 16 GB300s (FSDP16 + EP16, 4K tokens/rank) this loop was ~6.4 s of the ~7.9 s of GPU compute in a profiled step; matmuls were 0.39 s. Group query heads by KV head and compute the logits with one batched einsum per chunk, gathering each key once. Raise chunk_size from 16 to 128. At T=4096, H=24, H_kv=2, J=2051 one layer's teacher drops from 269.7 ms to 24.0 ms with peak memory 2.0 -> 1.4 GiB; the block targets match to 3.7e-9 (relative 9e-7). The 2-GPU debug model has identical step-1 loss and grad_norm, and losses within 2e-3 over 10 steps.
| ``(valid_U, blocks_UB)``: valid token positions and their selected | ||
| global block ids in ascending order, -1 after the valid ones. | ||
| """ | ||
| valid_U = valid_T.nonzero().flatten() |
There was a problem hiding this comment.
can we move this into from_inputs to avoid the device to host sync
There was a problem hiding this comment.
nice suggestion. we have done this in 2/n pr, moving valid-token compaction, document offsets, block indices into from_inputs, and using fixed shape. #6047
| starts_U = starts_T[valid_U] | ||
| new_document_U = F.pad(starts_U[1:] != starts_U[:-1], (1, 0), value=True) | ||
| document_U = new_document_U.cumsum(0) - 1 | ||
| tokens_N = torch.bincount(document_U) |
| # An empty slice is finite even when all selected scores are -inf. | ||
| raw_sum = scores_TB[..., :0].sum() | ||
| num_teacher_tokens = query_THK.shape[0] if num_blocks else 0 | ||
| for start in range(0, num_teacher_tokens, self.chunk_size): |
There was a problem hiding this comment.
can keep this for now and land #5863 after to better perf
…acher GEMMs The 125B GB300 step was CPU launch bound: ~98k GPU ops per step, the GPU busy ~35% of it, and the two QSA per-chunk loops (indexer scores, chunk 128; teacher + block_kl, chunk 128) were the largest launch source. - Indexer scores: chunk 1024 (4 heads -> 16 MiB fp32 Q x H x G per chunk at T=4096, 128 MiB at 32K) and cast query/key once outside the loop. - Teacher: gather selected keys along dim 0 and run one strided baddbmm per KV head (bf16 in, fp32 accumulate/out; scale and mask in the GEMM), chunk 512 (~1 GiB of gathered bf16 keys, independent of T). CPU casts first. - One block_kl over all tokens instead of one per chunk. One 125B QSA layer, fwd+bwd, T=4096, GB300 eager: wall 80.0 -> 20.5 ms, GPU kernel 33.6 -> 16.2 ms, GPU ops 2893 -> 631, peak 2.07 -> 2.91 GiB. Numerics: output and input grad bitwise identical on GPU; indexer weight grads differ only by fp32 summation order (bf16 ulps). Old vs new in float64 on CPU (with and without padding) agree to 7.7e-16. CPU unit tests pass.
|
@liangel-02 thanks for the review, i moved this pr to more organized stack here: #6046 |
## 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)
Enable qwen 3.8 flash next in torchttian. 1) verfied model definition and numerics. 2) distmuon + adamw optimizer 3) fsdp + ep, row sharded ple table on dp mesh.
Why
Based on
main, which includes the merged GDN determinism prerequisite #5784. Depends on #6017 (Attention Gym pin0d0197fb) forgather_attnseparate values and grouped fused kernels.TorchTitan cannot build or load Qwen3.8-Flash-Next on main. The architecture extends Qwen3.5 with four gated residual streams, QSA and PLE. Ordinary FSDP would all-gather its 51.2B-parameter PLE table: 95.37 GiB in BF16.
Example. Two DP owners retain rows 0-3 and 4-7 of an eight-row table. Requests
[6,1,6]route unique IDs[1,6]to their owners and return[E6,E1,E6]. Backward returns vector gradients to those owners.What changed
distributed/row_sharded_embedding.py: public PyTorch functional collectives route sorted unique IDs, vectors and gradients. The table is aShard(0)DTensor on the dense storage mesh. Existing clipping and native DCP handle it; HF fragments use the publicCheckpointableTensorcoordinate fields. Export gathers no table rows.gather_attn: the selected blocks and the incomplete tail are sparse KV indices into the packed sequence (no sliding window), with separate values and grouped KV heads. CUDA uses the fused Triton grouped kernel (SM100/SM103); CPU uses the reference implementation, as in DeepSeek-V4. The no-grad indexer teacher is unchanged.lightning_indexer, as in DeepSeek-V4, instead of ranking every complete block per query. It runs over valid tokens with per-document offsets in valid-token space, so its candidates are exactly the document-local blocks even with padding inside a document. Selected blocks are sorted ascending; their KL scores keep the previous math (dense GEMM per checkpointed chunk, then a gather).Linearmodules and interleave their outputs per head. This permits separate optimizers without a concatenated weight copy or custom autograd. The output interleave retains saved child outputs for selective remat.torchtitan_recipes/models/qwen3_8_flash_next.py, consumed by the small text/MM fixtures. DistMuon handles decoder linear maps; AdamW handles embeddings, head, router, GR, gates, decay/beta, norms, convolutions and vision; Adam with zero weight decay handles PLE.BlockShardseparates Q/K/V heads; native expert dimensions separate gate/up matrices.Muon uses the existing DistMuon API: Nesterov momentum 0.95, eight Polar Express iterations, epsilon
1e-14and0.2 * sqrt(max(rows, columns))scaling. Assignment follows report section 3.1; coefficients follow the published schedule. Debug learning rates and batches suit the reduced training fixtures.User-facing changes
gather_attn: 3.3 ms per layer on GB300.Numerics
Checkpoint schema revision:
de4b8e4d43b917e7706784d8bb445c9af86a3540; Transformers:494470d677d05d44153d235d795e0d01040307ab. HF parity uses a reduced model initialized by HF and loaded through the adapter.3.35e-7; gradient cosine exceeds 0.999999999999.7.772286415100098 -> 3.0675439834594727; loss and gradient norms finite.7.7723836898803711 -> 3.0521817207336426; loss and gradient norms finite; SPMD typechecking enabled.QSA on
gather_attnReleased 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:
gather_attnFused outputs and gradients are bitwise identical within a process, across processes and from cold Triton caches, with and without deterministic algorithms. The debug model (two GB300s, seed 42, 10 steps) matches the previous implementation to about
1e-3in loss at every step (step 10:7.49278vs7.49127). The CPU test checks output and gradients against dense masked SDPA in FP64.QSA selection on
lightning_indexerReleased 125B-A6B indexer shapes on one GB300 (T=4096, two documents, padding inside a document and at the end), compared with the previous argsort ranking:
ReLU scores tie exactly (2.2% of selected scores at random init). With deterministic algorithms the CuTe backend resolves ties toward earlier blocks, as the previous stable ranking did, independent of later candidates; otherwise the choice among cutoff ties is backend-defined. On CPU, Attention Gym's reference uses
torch.topk, so the former CPU tie-order test is removed. Indexer forward+backward: 51 ms vs 64 ms. Debug model (two GB300s, seed 42, 10 steps): step-1 loss identical, later steps within2e-3(step 10:7.49411vs7.49278).Offline comparisons across parallelisms
These comparisons, the HF parity rows above and the checkpoint-resume qualification below were measured with the previous chunked MATH-SDPA QSA and argsort selection (before
c3d743ff0) and have not been rerun on the Attention Gym kernels.Same native DCP checkpoint, logical inputs, two microbatches and step-global CE/auxiliary normalization. Parameters remain FP32 master tensors; FSDP-managed compute (including vision) is BF16, and gradient reduction is FP32. Each case compares evaluation/training logits, CE, MoE/indexer objectives, all parameter gradients reconstructed through their DTensor placements, token-embedding and image/video input gradients, and the native global gradient norm. Expert IDs and QSA token selections match exactly.
01.0000130800.99999767001.0000130710.99999767600.9999418200.99999648400.9999418150.999996487All four cases pass the existing bounds: logits
atol=1/256, rtol=1/128; parameter/input gradient RMS and maximum errorsatol=1e-4, rtol=1/32; CEatol=rtol=2e-4. Logit probability KL is zero, and top-1/top-5 sets agree exactly. There are 198 text and 239 multimodal logical parameter gradients per case.The inputs contain two real packed documents per logical rank, so both layouts use the same shared GDN varlen path. Text uses one query per QSA chunk to keep MATH SDPA batch shapes identical. With default 16-query chunks, the first text microbatch has maximum logit error
0.0078125and 96/159744 entries exceed the HF script's forward bound. The first difference is two BF16 elements in QSA output, with bitwise-identical Q/K/V and ordered selections; both outputs pass an independent FP64 attention oracle. The default-chunk gradients pass their bounds (norm ratio0.999910545, cosine0.999982893). These diagnostic results are retained, and qualification tolerances are unchanged.Artifacts in the local 1/n worktree:
outputs/test_review_20261109_01a1b222/verification_summary.json,offline_parity_packed/text/comparison_qsa1.json,offline_parity_packed/mm/comparison.json, andoffline_parity_packed/text/qsa_rounding_oracle.json. Matrix-specific harnesses, checkpoints and logs remain generated outputs.Training uses seed 42 and strict determinism. Mixed optimizers and split parameter initialization change the training trajectory. Separate GEMMs can change BF16 gradients relative to fused computation; HF tolerances are unchanged. The 1,627-key HF name/shape inventory, including 128 PLE parts, is unchanged.
Validated model source:
578e9757e72960743e46c368b112c3a5b9491f58plus the current test/recipe/README changes. Rebased revision:35d853ff02f4001821c061129274f0e2ae47c314, based on upstream mainbaf7cf9b01c2d6161909ef839a13f90fe99d7533. The model implementation is unchanged by this revision. Runtime: PyTorch2.16.0.dev20261108+cu132(1392e1f8e4903657d4391f3bd8fcc9ca8a74b758), Attention Gym0.0.19.dev10+g26beb363c. Thegather_attnrevision was validated with Attention Gym0.0.19at0d0197fb.Rebase validation on two GB300s: the ten-step multimodal FSDP2/EP2 recipe (seed 42, strict determinism) reproduces every full-precision TensorBoard loss and gradient norm bitwise versus
62aaef7fa. All six 1/n patches are unchanged ingit range-diff. Lint and all 56 targeted CPU tests pass. Artifacts:outputs/rebase_main_20261110_01a1b222/numerics.jsonandrange_diff.txt.Checkpoint resume qualification uses the same two GB300s, seed 42, strict determinism and SPMD typechecking. At step 5, all model parameters and optimizer tensors, including both owners' PLE rows and Adam moments, restore bitwise; the next inputs match bitwise too. The first resumed backward differs only in vision gradients (maximum
2.98e-8); decoder and PLE gradients match bitwise. Across ten steps, the maximum restart-versus-uninterrupted differences are loss1.8000602722167969e-4and gradient norm5.269050598144531e-4, first visible in scalars at step 9. A fresh uninterrupted control reproduces the prior ten-step loss and gradient norm bitwise. Artifacts:outputs/pr1_checkpoint_resume_01a1b222/verification_summary.json,checkpoint_tensor_comparison.jsonandcontrol_comparison.json.Testing
offset_rmsnormwith the Qwen3.5 decorator settings. CPU FP32/BF16 checks verify bitwise forward/backward results with the region disabled and Inductor execution when enabled; five focused PLE/indexer cases pass. CPU tests cover gradients with no complete blocks, while the multimodal integration does not explicitly force that imbalance across ranks.pre-commit run --all-files, including typechecking: pass. The validation runtime uses isolated stubs for optional dependencies.Limits and alternatives
gather_attnpath with separate values and grouped KV heads requires SM100/SM103; other CUDA GPUs raise in Attention Gym rather than falling back. The indexer teacher stays chunked pending the shared indexer teacher, which can replaceQSAIndexerLoss; the trained indexer's KL scores still use a dense query x block GEMM.F.embedding. DTensor reuses existing clipping, optimizers and DCP; plain local parameters would require additional core contracts. TP/SP, PP and CP are rejected by this configuration.Stack