Repository navigation
[muse_spark] Run NaViT vision attention with a deterministic varlen Flash backward - #5889
Conversation
|
@claude review this pr |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The design is right: a sibling inner attention, chosen by config type, that makes only the vision attention backward deterministic. The remaining items are small, local edits to the new op. A maintainer still needs to review, since this touches models/common/attention.
What this PR does. NaViT vision attention in Muse Spark and Muse Glimmer moves from flex to a custom op, torchtitan::deterministic_varlen_attn. The op wraps torch's private Flash varlen forward and backward ops. Its backward turns on torch.use_deterministic_algorithms(True) only for its own duration. Vision weights that are invariant over CP/TP therefore get bitwise-identical grads on every rank without global deterministic mode. Common VisionAttention now accepts varlen metadata, and its flex_attention attribute is renamed inner_attention (mechanical; every in-repo caller is updated, and nothing in the repo still uses the old name).
Example.
Spark mm, CP2, debug.deterministic=False
before: flex bwd -> per-rank autotuned kernels -> dq/dk differ across CP ranks
-> CP-invariant vision weights (no grad reduction) drift apart
after: Flash varlen bwd with deterministic on locally -> identical grads on every rank
NaViT built with any other inner attention -> ValueError at build time
Must fix
torchtitan/ops/varlen_attn.py:101-- turning on the deterministic flag in a run where global mode is off leavesfill_uninitialized_memory=True. Every allocation in the Flash backward then runs a NaN-fill kernel.distributed/utils.py:145-147says that kernel races with DeepEP comm streams. Set it toFalseand restore it together with the flag.torchtitan/ops/varlen_attn.py:19-20-- this TODO covers private upstream ops (torch_attn::_varlen_attn,_varlen_attn_backward) but has no upstream issue link. File a pytorch/pytorch issue asking for a deterministic-backward option onvarlen_attnand link it.
Should consider
torchtitan/models/common/attention/attention.py:622--num_splits=1is passed on ROCm, which the siblingVarlenInnerAttentionavoids. Add the sametorch.version.hipguard or raise.- Kimi K2.7/K3 and Qwen3.5/3.6/3.8 vision still run flex. The PR's own reasoning says they can drift the same way under CP, and nothing guards against it there. Please open a tracked follow-up (issue) rather than leaving it only in the PR description. Those models already build
create_block_diagonal_maskper image, so the switch is a flavor change plus acu_seqlensbuild, like_segment_attention_metadata.
Details
- Sparse-layer
max_k:min(grid_h, pos_emb_grid_h) * min(grid_w, pos_emb_grid_w)is the exact maximum of_get_sparse_perm_and_slens's per-window counts. Edge windows only get smaller, and padding never makes a window empty. Both maxima are computed on the host fromgrid_thw, so there is no new device sync. - CP:
ContextParallelTransformonly walks decoder layers (context_parallel.py:93-105), so the visionDeterministicVarlenInnerAttentionis never converted to a CP backend, and no map entry is needed. - The golden
muse_glimmer.txtbelongs to the text-onlymuse_glimmer_text_fsdptest, so the claim that no golden file covers the multimodal loss holds. - The compiled-backward check in AOTAutograd reads the global flag before this op runs, and the op restores the flag afterwards, so the two stay consistent. That matches the PR's reasoning for not using
grad_fnhooks.
Not verified: the keyword names in the private op schema and the is_causal = window_size == [-1, 0] convention (no torch install available here; the GPU test covers only (-1, -1)). Also not verified: whether the vision backward overlaps with DeepEP comm.
| TODO: The ``torch_attn::_varlen_attn`` ops are private; switch to a public | ||
| deterministic-backward option once torch varlen_attn has one. |
There was a problem hiding this comment.
This TODO covers two private upstream ops (torch_attn::_varlen_attn and torch_attn::_varlen_attn_backward) plus a missing upstream feature, but it has no issue link. CLAUDE.md principle 3 asks for a TODO with an upstream issue link whenever torchtitan works around a PyTorch gap or calls a private API. The ask upstream is small: a deterministic: bool (or a per-call deterministic-backward option) on torch.nn.attention.varlen.varlen_attn. That would delete most of this file. Please file the issue on pytorch/pytorch and link it here as TODO(pytorch/pytorch#NNNN).
| query_THK = q_THK.to(attn_dtype) | ||
| key_THK = k_THK.to(attn_dtype) | ||
| value_THV = v_THV.to(attn_dtype) | ||
| num_splits = 1 if is_in_batch_invariant_mode() else None |
There was a problem hiding this comment.
VarlenInnerAttention._forward_varlen (lines 511-515) skips num_splits on ROCm because "ROCm's _flash_attention_forward rejects num_splits entirely". This path passes num_splits=1 in batch-invariant mode without that guard, so Spark/Glimmer vision under batch-invariant mode on ROCm would fail inside the kernel, not with a clear error. Either match the existing guard (and torch.version.hip is None) or raise a ValueError for that combination. The PR description already notes that this branch has no test.
…lash backward
## Summary (human-written)
In the vision encoder region, some weights are invariant along the TP and CP axes. The backward must be deterministic; otherwise the gradients can vary across ranks and eventually cause weight drift.
This PR replaces Muse Spark and Muse Glimmer's vision encoder attention with a deterministic varlen attention class.
## Why
Muse Spark and Muse Glimmer vision weights are invariant over TP and CP. Every rank runs the same vision encoder backward and updates its own copy with no gradient reduction, so the copies stay equal only if that backward is bitwise repeatable. On main it is not: the NaViT attention uses flex, which picks autotuned templates and Inductor reduction configs per rank. Under CP the q/k grads differ across ranks and the replicated vision weights drift apart. Switching to Flash varlen alone does not fix it, because the Flash varlen backward is repeatable only under global deterministic mode.
**Example.**
```
Spark debug_mm, 2 x H100, global deterministic mode off, compare the two ranks' copies of each replicated param after every step
before (flex), CP2: vision params differ across ranks
after (this PR), CP2 and TP2: 0 params differ and grad_norm is identical on both ranks at all 60 steps
```
## What changed
- Add torchtitan::deterministic_varlen_attn (torchtitan/ops/varlen_attn.py), a Flash varlen custom op. Its backward turns on deterministic mode only for itself and restores it. It calls torch's varlen forward and backward ops directly, so the backward does not recompute the forward. It passes num_splits=1 in batch-invariant mode.
- The op calls the private torch_attn::_varlen_attn and _varlen_attn_backward ops, with every argument after max_k passed by keyword so a schema change fails loudly. A TODO in code says to switch to a public option once torch varlen_attn has one; no upstream issue is filed.
- Add DeterministicVarlenInnerAttention (common/attention/attention.py), a sibling of VarlenInnerAttention selected by config type. It runs the op on q/k/v and a VarlenAttentionMetadata that the caller builds, as VisionAttention callers do. It always uses Flash, so it has no sdpa_backends. It takes no enable_gqa or out_transform and has no metadata builder, so decoder attention cannot use it as is. The NaViT encoder (Muse Spark and Muse Glimmer) is the current user. NaViT builds cu_seqlens per image (full layers) and per window (sparse layers). Max lengths come from host-side grid sizes, so there is no device sync. NaViT raises ValueError for any other inner attention.
- The attention output takes the query's SPMD type. The vision layout from vision_inner_attention_sharding_config ({DP: V, CP: I, TP: S(1)}) holds under SPMD type checking.
- Common VisionAttention accepts flex or varlen metadata. Mechanical: its attribute flex_attention is renamed inner_attention; callers updated in the remat GPU test and the Kimi and Qwen3.5 checkpoint-conversion scripts.
- Mechanical: the varlen dtype choice moves out of VarlenInnerAttention into a module-private helper in attention.py, shared with DeterministicVarlenInnerAttention. Both classes activate FA3/FA4 with activate_cuda_flash_attention_impl().
## Alternatives considered
- Global deterministic mode: makes the whole model pay for determinism, and it raises on ops without a deterministic CUDA kernel, such as the grid_sample backward.
- Hooks on the grad_fn of the public varlen_attn that toggle the flag: work in eager, but Dynamo cannot trace grad_fn, and a compiled backward raises when the flag differs from the forward.
## Numerics
Vision attention changes from flex to Flash varlen, so Spark and Glimmer multimodal losses change. No golden loss file covers them. Vision attention outputs and grads are bitwise equal to torch Flash varlen in deterministic mode, whether or not global deterministic mode is on. Text-only models are unchanged.
| Config | Hardware | Result |
| --- | --- | --- |
| Spark debug_mm CP2, full FT and LoRA vision + decoder, deterministic off, 60 steps | 2 x H100 | replicated params bitwise equal, grad_norm identical per rank, every step |
| Spark debug_mm TP2, full FT and LoRA vision + decoder, deterministic off, 60 steps | 2 x H100 | same |
| Spark debug_mm CP2 and TP2, SPMD type checking on, 5 steps | 2 x H100 | passes (CP2 raised SpmdTypeError "has V, expected I" before the type fix) |
| muse_spark_debugmodel_mm_fsdp2_tp2_cp2_ep4 (dp_shard 2, TP2, CP2, EP4), type checking on, 10 steps (job 2344774) | 8 x GB300 | passes, identical on all 8 ranks |
| Spark 816B mm CP16 EP16, LoRA vision + decoder, deterministic on, 20 steps (job 2344772 vs 2342345) | GB300 | no deterministic error; loss and grad_norm identical to the run before rebasing at all 20 steps |
## Performance
Spark 816B mm, CP16 EP16, 32K packed, LoRA vision + decoder, median step time over steps 6-20 on GB300:
| Run | Attention | Deterministic mode | Step time | MFU |
| --- | --- | --- | --- | --- |
| 2340824 | flex | off | 5555 ms | 4.84% |
| 2342345 | this op | on | 4731 ms | 5.68% |
| 2344772 | this op (rebased tree) | on | 5003 ms | 5.37% |
MFU uses the text-token FLOPs formula from before #4819; compare the step times.
The runs are noisy (outliers up to 7.3 s) and change both the attention backend and deterministic mode, so read this as not slower than flex, not as a speedup. In isolation on H100, the op's forward + backward costs 0-13% more than the non-deterministic Flash varlen.
## Testing
- GPU test (gpu/ops/test_varlen_attn.py): with deterministic mode off, the out and q/k/v grads of DeterministicVarlenInnerAttention (which runs the op) are bitwise equal over 10 eager runs and one compiled run, and equal to torch Flash varlen with deterministic mode on. It catches a backward that does not turn on deterministic mode, or a schema change in the private ops.
- The Glimmer CPU tests replace the NaViT kernel with a per-segment SDPA stand-in, since varlen has no CPU kernel.
- The vision save-region remat GPU test passes with the renamed attribute.
- CPU tests at this commit: models/common/test_vision_attention.py, models/muse_spark and models/muse_glimmer, 167 passed, 1 skipped, 3 xfailed.
## Known issues / follow-ups
- Kimi K2.7, Kimi K3 and the Qwen3.5 family (qwen3_5, qwen3_6, qwen3_8) vision weights are also trainable and invariant over CP (and over TP for the unsharded ones), and their vision attention is still flex, so they can drift the same way under CP. This PR does not change them; this is from reading the code, not from a run.
- The batch-invariant num_splits=1 path has no test.
stack-info: PR: pytorch/torchtitan#5889, branch: fegin/stack/18
…regions (#5886) Stacked PRs: * #5904 * #5895 * #5894 * #5893 * #5892 * #5891 * #5890 * #5889 * #5888 * #5887 * #5885 * __->__#5886 --- --- --- ### [distributed] Keep grads of async collective inputs to local_compile regions ## Summary (human-written) See the issue: pytorch/pytorch#201700 This is a bug when compiling: AOTAutograd doesn't trace through AsyncCollectiveTensors and loses the requires_grad. This PR works around the problem in general. But the real solution should be fixing pytorch/pytorch#201700. ## Why On main, Muse Spark with TP > 1 and local compile on never trains tok_embeddings: its grad is None, for text-only and multimodal runs, with SP on and off. Module-boundary redistributions return un-awaited AsyncCollectiveTensors (async_op=True). AOTAutograd unwraps such an input with trigger_wait(), which returns the inner tensor without requires_grad (torch/_functorch/_aot_autograd/frontend_utils.py, added by pytorch/pytorch#179849), so the compiled region's output has no grad path back to the input. In Spark, the embedding output redistribution feeds the compiled embedding norm. Tracking issue: pytorch/pytorch#201700 (pytorch/pytorch#191113 is a closed, unmerged PR for the same bug). **Example.** ``` emb = tok_embeddings(tokens) # redistributed at the Module boundary -> AsyncCollectiveTensor h = compiled_norm(emb) # local_compile region loss(h).backward() before: tok_embeddings.weight.grad is None after: tok_embeddings.weight.grad is set ``` ## What changed - Every local_compile region and always-compiled helper is wrapped so an AsyncCollectiveTensor argument is awaited by a small autograd Function before the compiled call. The Function keeps the autograd edge. - Only top-level arguments are awaited. No in-tree region or always-compiled helper takes tensors inside a container (checked every signature; the only container argument is gdn's split_sizes: list[int]). - TODO(pytorch/pytorch#201700) in code: remove once AOTAutograd keeps the requires_grad of an unwrapped AsyncCollectiveTensor input. - The same bug hits the async k_shared all-gather into the mla_kv region in open PRs #5564 and #5682, which work around it with async_op=False. k_shared is a top-level argument of that region, so this fix covers it and they can keep async_op=True. In-tree CP MLA is not affected: in UlyssesMLAAttention only the k_shared all-gather stays async, and it feeds the eager materialize_mla_kv. The Q/KV all-to-all is synchronous in spmd_types 0.3.1, so the compiled flex call gets plain tensors. ## Alternatives considered - Wait inside Module redistribution (async_op=False): gives up the comm overlap for every Module boundary, not only compiled regions. - Fix in each model: the bug is in the local_compile layer and affects any model with a compiled region after a redistribution. ## Numerics Only Muse Spark with TP > 1 and local compile on changes: tok_embeddings gets grads and trains. Configs below were checked; others are unchecked. Setup: 2x H100, BASE = parent commit, TEST = this commit. debug.seed = 42, debug.deterministic = True, 10 steps, c4_test. Loss and grad_norm are read from TensorBoard. **Muse Spark debugmodel, TP2 + EP2 + SP, flex, default local_compile regions.** Changes, as expected. Step 1 loss is equal (same forward); step 1 grad_norm differs by the added tok_embeddings grad. | step | BASE loss | BASE grad_norm | TEST loss | TEST grad_norm | |---|---|---|---|---| | 1 | 7.82727003 | 4.97379541 | 7.82727003 | 4.97423124 | | 2 | 7.03273010 | 3.67558002 | 7.03092051 | 3.66602159 | | 3 | 6.13859034 | 2.72887707 | 6.14003372 | 2.73221183 | | 4 | 5.76145124 | 2.13588810 | 5.76339674 | 2.15090728 | | 5 | 5.83007097 | 2.06997371 | 5.82927275 | 2.06360984 | | 6 | 5.56987143 | 1.85165656 | 5.56976700 | 1.84894443 | | 7 | 5.37956715 | 1.88629401 | 5.37123251 | 1.88281417 | | 8 | 6.01605892 | 1.97213578 | 6.01554680 | 1.95823133 | | 9 | 5.18035460 | 1.96500850 | 5.18841839 | 1.98249125 | | 10 | 5.20351505 | 1.78124106 | 5.20615530 | 1.78476560 | - Step 1 per-parameter grads (local grad norm, both ranks): tok_embeddings.embedding.weight is None in BASE and nonzero in TEST (rank 0: 0.06576, rank 1: 0.00345). The other 225 parameters have bitwise equal grad norms. - Determinism: two TEST runs give bitwise equal loss and grad_norm at all 10 steps and equal step 1 per-parameter grads. So the BASE/TEST difference comes from this change. **DeepSeek V3 debugmodel, CP2, flex, default local_compile regions.** Unchanged: loss, grad_norm, and step 1 per-parameter grads are bitwise equal for both CP MLA backends. - UlyssesMLAAttention (no load balancer): step 10 loss 4.13782024, grad_norm 2.26978993 in BASE and TEST. - AllGatherKVMLAFlexAttention (no load balancer; the CP attention of the deepseek_v3_cp_pp golden): step 10 loss 4.13834953, grad_norm 2.27362609 in BASE and TEST. Not checked: DeepSeek V3 varlen with CP, because FlashAttention 3 supports head dim at most 128 and the debug MLA head dim is 192. ## Testing - CPU test: a compiled region (aot_eager) on an AsyncCollectiveTensor input passes the grad back. It fails without the fix. - CPU tests at this commit: tests/unit_tests/cpu/config/test_compile_config.py, 9 passed.
10582c5 to
d890869
Compare
… processor (#5887) Stacked PRs: * #5904 * #5895 * #5885 * #5894 * #5893 * #5892 * #5891 * #5890 * #5889 * #5981 * #5888 * __->__#5887 --- --- --- ### [muse_spark] Resample multimodal images with LANCZOS, as the released processor ## Summary (human-written) Use the correct resample for Muse Spark ## Why The Muse Spark multimodal dataloader resizes images with VisionProcessor's default interpolation, BICUBIC. The released Muse Spark processor_config.json resamples with LANCZOS (resample=1). So on main, training sees slightly different pixels than the released model's preprocessing. **Example.** ``` MUSE_SPARK_VISION_PROCESSOR_KWARGS before: image_interpolation_mode = "bicubic" (VisionProcessor default) after: image_interpolation_mode = "lanczos" (processor_config.json resample=1) ``` ## What changed - MUSE_SPARK_VISION_PROCESSOR_KWARGS sets image_interpolation_mode="lanczos". It applies to every Muse Spark multimodal recipe, for images and video frames. ## Numerics Image preprocessing changes for every Muse Spark multimodal recipe, including muse_spark_debugmodel_mm, so their multimodal losses change. Muse Spark has no golden loss files. Text-only recipes are unchanged. ## Testing - No new test: this is a single config value. tests/unit_tests/cpu/recipes/test_muse_spark.py builds muse_spark_debugmodel_mm; 6 passed at this commit.
…e_glimmer_30b_mm test recipe (#5888) Stacked PRs: * #5904 * #5895 * #5885 * #5894 * #5893 * #5892 * #5891 * #5890 * #5889 * #5981 * __->__#5888 --- --- --- ### [recipes] Use the released Muse tokens and image processor in the muse_glimmer_30b_mm test recipe ## Summary (human-written) The Muse Glimmer multimodal recipe uses incorrect tokens and image processor. This PR fixes the mismatch. ## Why On main, muse_glimmer_30b_mm does not build. It uses the Qwen-style debug tokens (<|image_pad|>, <|vision_start|>, ...), which the released Muse Glimmer 30B tokenizer does not have, so the tokenizer build raises. It also uses the debug pixel budget (max_pixels=3136, 4 merged tokens per image), not the released image processor. **Example.** ``` before: muse_glimmer_30b_mm -> tokenizer build raises (no <|image_pad|> in the released tokenizer) after: image tokens <|patch|> (200092), <|video|> (200091), <|image_start|> (200080), <|image_end|> (200081), pad <|finetune_right_pad|> (200018) images: closest-aspect grid up to 4096 merged tokens, LANCZOS ``` ## What changed - muse_glimmer_30b_mm uses the released special tokens and image processor. Its output matches the HF MuseGlimmerImageProcessor to 1.2e-7 with identical grids. - The released image processor is MUSE_GLIMMER_30B_VISION_PROCESSOR_KWARGS: the Muse Spark recipe's MuseGlimmerPatchGridResize with max_image_tokens=4096, and LANCZOS. Images only. - Mechanical: the debug token map and image processor settings are renamed MUSE_GLIMMER_DEBUG_SPECIAL_TOKENS and MUSE_GLIMMER_DEBUG_VISION_PROCESSOR_KWARGS. The debug recipe keeps them, because the debug tokenizer asset defines only those tokens. ## Numerics muse_glimmer_30b_mm did not build on main, so there is no baseline. The Muse Glimmer debug recipe and the Muse Spark recipes are unchanged (same tokens, same image processor). ## Testing - CPU test: three resize grids match the HF processor, one on the 4096-token cap path. It catches drift from the released processor. - CPU tests at this commit: recipes/test_muse_spark.py, components/data, models/muse_spark and models/muse_glimmer all pass (3 xfailed). Skips depend on the environment: one test needs a local tokenizer directory, one needs an accelerator.
…lash backward
## Summary (human-written)
In the vision encoder region, some weights are invariant along the TP and CP axes. The backward must be deterministic; otherwise the gradients can vary across ranks and eventually cause weight drift.
This PR replaces Muse Spark and Muse Glimmer's vision encoder attention with a deterministic varlen attention class.
## Why
Muse Spark and Muse Glimmer vision weights are invariant over TP and CP. Every rank runs the same vision encoder backward and updates its own copy with no gradient reduction, so the copies stay equal only if that backward is bitwise repeatable. On main it is not: the NaViT attention uses flex, which picks autotuned templates and Inductor reduction configs per rank. Under CP the q/k grads differ across ranks and the replicated vision weights drift apart. Switching to Flash varlen alone does not fix it, because the Flash varlen backward is repeatable only under global deterministic mode.
**Example.**
```
Spark debug_mm, 2 x H100, global deterministic mode off, compare the two ranks' copies of each replicated param after every step
before (flex), CP2: vision params differ across ranks
after (this PR), CP2 and TP2: 0 params differ and grad_norm is identical on both ranks at all 60 steps
```
## What changed
- Add torchtitan::deterministic_varlen_attn (torchtitan/ops/varlen_attn.py), a Flash varlen custom op. Its backward turns on deterministic mode only for itself, turns off the NaN fill of new tensors (fill_uninitialized_memory, which races with DeepEP comm streams) for that time, and restores both. It calls torch's varlen forward and backward ops directly, so the backward does not recompute the forward. It passes num_splits=1 in batch-invariant mode, except on ROCm, as VarlenInnerAttention does.
- The op calls the private torch_attn::_varlen_attn and _varlen_attn_backward ops, with every argument after max_k passed by keyword so a schema change fails loudly. A TODO in code says to switch to a public option once torch varlen_attn has one; no upstream issue is filed.
- Add DeterministicVarlenInnerAttention (common/attention/attention.py), a sibling of VarlenInnerAttention selected by config type. It runs the op on q/k/v and a VarlenAttentionMetadata that the caller builds, as VisionAttention callers do. It always uses Flash, so it has no sdpa_backends. It takes no enable_gqa or out_transform and has no metadata builder, so decoder attention cannot use it as is. The NaViT encoder (Muse Spark and Muse Glimmer) is the current user. NaViT builds cu_seqlens per image (full layers) and per window (sparse layers). Max lengths come from host-side grid sizes, so there is no device sync. NaViTEncoder.Config raises ValueError at config time for any other inner attention.
- The attention output takes the query's SPMD type. The vision layout from vision_inner_attention_sharding_config ({DP: V, CP: I, TP: S(1)}) holds under SPMD type checking.
- Common VisionAttention accepts flex or varlen metadata. Mechanical: its attribute flex_attention is renamed inner_attention; callers updated in the remat GPU test and the Kimi and Qwen3.5 checkpoint-conversion scripts.
- Mechanical: the varlen dtype choice moves out of VarlenInnerAttention into a module-private helper in attention.py, shared with DeterministicVarlenInnerAttention. Both classes activate FA3/FA4 with activate_cuda_flash_attention_impl().
## Alternatives considered
- Global deterministic mode: makes the whole model pay for determinism, and it raises on ops without a deterministic CUDA kernel, such as the grid_sample backward.
- Hooks on the grad_fn of the public varlen_attn that toggle the flag: work in eager, but Dynamo cannot trace grad_fn, and a compiled backward raises when the flag differs from the forward.
## Numerics
Vision attention changes from flex to Flash varlen, so Spark and Glimmer multimodal losses change. No golden loss file covers them. Vision attention outputs and grads are bitwise equal to torch Flash varlen in deterministic mode, whether or not global deterministic mode is on. Text-only models are unchanged.
| Config | Hardware | Result |
| --- | --- | --- |
| Spark debug_mm CP2, full FT and LoRA vision + decoder, deterministic off, 60 steps | 2 x H100 | replicated params bitwise equal, grad_norm identical per rank, every step |
| Spark debug_mm TP2, full FT and LoRA vision + decoder, deterministic off, 60 steps | 2 x H100 | same |
| Spark debug_mm CP2 and TP2, SPMD type checking on, 5 steps | 2 x H100 | passes (CP2 raised SpmdTypeError "has V, expected I" before the type fix) |
| muse_spark_debugmodel_mm_fsdp2_tp2_cp2_ep4 (dp_shard 2, TP2, CP2, EP4), type checking on, 10 steps (job 2344774) | 8 x GB300 | passes, identical on all 8 ranks |
| Spark 816B mm CP16 EP16, LoRA vision + decoder, deterministic on, 20 steps (job 2344772 vs 2342345) | GB300 | no deterministic error; loss and grad_norm identical to the run before rebasing at all 20 steps |
## Performance
Spark 816B mm, CP16 EP16, 32K packed, LoRA vision + decoder, median step time over steps 6-20 on GB300:
| Run | Attention | Deterministic mode | Step time | MFU |
| --- | --- | --- | --- | --- |
| 2340824 | flex | off | 5555 ms | 4.84% |
| 2342345 | this op | on | 4731 ms | 5.68% |
| 2344772 | this op (rebased tree) | on | 5003 ms | 5.37% |
MFU uses the text-token FLOPs formula from before #4819; compare the step times.
The runs are noisy (outliers up to 7.3 s) and change both the attention backend and deterministic mode, so read this as not slower than flex, not as a speedup. In isolation on H100, the op's forward + backward costs 0-13% more than the non-deterministic Flash varlen.
## Testing
- GPU test (gpu/ops/test_varlen_attn.py): with deterministic mode off, the out and q/k/v grads of DeterministicVarlenInnerAttention (which runs the op) are bitwise equal over 10 eager runs and one compiled run, and equal to torch Flash varlen with deterministic mode on. It also checks that the op restores fill_uninitialized_memory. It catches a backward that does not turn on deterministic mode, a schema change in the private ops, or a flag that is not restored.
- The Glimmer CPU tests replace the NaViT kernel with a per-segment SDPA stand-in, since varlen has no CPU kernel.
- The vision save-region remat GPU test passes with the renamed attribute.
- CPU tests at this commit: models/common/test_vision_attention.py, models/muse_spark and models/muse_glimmer, 167 passed, 1 skipped, 3 xfailed.
## Known issues / follow-ups
- Kimi K2.7, Kimi K3 and the Qwen3.5 family (qwen3_5, qwen3_6, qwen3_8) vision weights are also trainable and invariant over CP (and over TP for the unsharded ones), and their vision attention is still flex, so they can drift the same way under CP. This PR does not change them; this is from reading the code, not from a run.
- The batch-invariant num_splits=1 path has no test.
stack-info: PR: #5889, branch: fegin/stack/18
Stacked PRs:
[muse_spark] Run NaViT vision attention with a deterministic varlen Flash backward
Summary (human-written)
In the vision encoder region, some weights are invariant along the TP and CP axes. The backward must be deterministic; otherwise the gradients can vary across ranks and eventually cause weight drift.
This PR replaces Muse Spark and Muse Glimmer's vision encoder attention with a deterministic varlen attention class.
Why
Muse Spark and Muse Glimmer vision weights are invariant over TP and CP. Every rank runs the same vision encoder backward and updates its own copy with no gradient reduction, so the copies stay equal only if that backward is bitwise repeatable. On main it is not: the NaViT attention uses flex, which picks autotuned templates and Inductor reduction configs per rank. Under CP the q/k grads differ across ranks and the replicated vision weights drift apart. Switching to Flash varlen alone does not fix it, because the Flash varlen backward is repeatable only under global deterministic mode.
Example.
What changed
Alternatives considered
Numerics
Vision attention changes from flex to Flash varlen, so Spark and Glimmer multimodal losses change. No golden loss file covers them. Vision attention outputs and grads are bitwise equal to torch Flash varlen in deterministic mode, whether or not global deterministic mode is on. Text-only models are unchanged.
Performance
Spark 816B mm, CP16 EP16, 32K packed, LoRA vision + decoder, median step time over steps 6-20 on GB300:
MFU uses the text-token FLOPs formula from before #4819; compare the step times.
The runs are noisy (outliers up to 7.3 s) and change both the attention backend and deterministic mode, so read this as not slower than flex, not as a speedup. In isolation on H100, the op's forward + backward costs 0-13% more than the non-deterministic Flash varlen.
Testing
Known issues / follow-ups