Repository navigation
[attention] Skip cuDNN varlen attention in deterministic mode - #5890
Conversation
## Summary (human-written) VarlenInnerAttention always tries the cuDNN backend first, but the cuDNN backend ignores the use_deterministic_algorithms flag. So VarlenInnerAttention shouldn't use it when the flag is True. This PR fixes the issue. ## Why VarlenInnerAttention tries cuDNN first. The cuDNN varlen backward ignores torch.use_deterministic_algorithms: it neither raises nor runs deterministically. So on main, deterministic runs of any varlen model on SM90/SM100 silently differ, which breaks the bitwise loss comparisons that deterministic mode exists for. **Example.** ``` llama3 debugmodel, varlen, 2 x H100, debug.deterministic=True, seed 42, two identical runs before: losses differ from step 2 (7.72474479675293 vs 7.724735260009766) after: loss and grad_norm bitwise equal for 30 steps ``` ## What changed - In deterministic mode, VarlenInnerAttention.forward drops cuDNN from the backend priority list, so FlashAttention runs. The FA2/FA3/FA4 varlen backward is deterministic in that mode. - If cuDNN is the only configured backend, deterministic mode raises ValueError. - The check runs in forward, not at config time. Deterministic mode comes from the debug config, and loss_compare.py turns it on for every config, so a config-time error would break every varlen config under loss_compare, including the CI golden tests. - TODO in code: remove once the cuDNN varlen backward honors deterministic mode. No upstream issue is filed yet. ## Alternatives considered - torch.backends.cuda.enable_cudnn_sdp(False): has no effect here, because sdpa_kernel(backends) re-enables exactly the listed backends. ## Numerics Unchanged with deterministic mode off. With it on, varlen runs on SM90/SM100 use Flash instead of cuDNN. No golden loss file changes: the only real_pg golden (kimi_k3_b200, test kimi_k3_mm_muon) uses flex attention, and B200 CI passed with this change (run 42707592570). ## Testing - CPU test: the backend list passed to sdpa_kernel in both modes, and a cuDNN-only config raises in deterministic mode. It catches cuDNN coming back in deterministic mode. - CPU tests at this commit: tests/unit_tests/cpu/models/common/test_varlen_attention.py, 31 passed. ## Known issues / follow-ups - File the upstream cuDNN issue and link it in the TODO. stack-info: PR: #5890, branch: fegin/stack/19
|
@claude review this pr |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The fix is small and sits in the right place for a real silent-nondeterminism bug. The B200 golden still needs regenerating, and the TODO needs an upstream issue link. This touches a shared attention module, so a maintainer still needs to review.
What this PR does. In deterministic mode, VarlenInnerAttention._forward_varlen now drops CUDNN_ATTENTION from the sdpa_kernel priority list, so varlen runs on Flash, whose backward honors use_deterministic_algorithms. If cuDNN is the only configured backend, it raises ValueError. The CP path also goes through _forward_varlen (cp_attention.py:385), so CP is covered too.
Example.
VarlenInnerAttention.Config() # default sdpa_backends = [CUDNN_ATTENTION, FLASH_ATTENTION]
SM90/SM100, debug.deterministic=True, two identical runs
before: sdpa_kernel([CUDNN, FLASH]) -> cuDNN fwd/bwd -> losses differ from step 2
after: sdpa_kernel([FLASH]) -> Flash fwd/bwd -> bitwise-equal loss/grad_norm
Config(sdpa_backends=["CUDNN_ATTENTION"]) + deterministic -> ValueError on first forward
Must fix
tests/assets/losses/real_pg/kimi_k3_b200.txt-- In deterministic mode on B200, the kimi_k3 varlen forward now also switches from cuDNN to Flash, so thekimi_k3_mm_muongolden (tests/integration_tests/b200.py:150) will diverge, andciflow/b200will fail after this lands. None of the later PRs in the stack (#5891-#5895) regenerates it. Please regenerate it on B200 in this PR, per CLAUDE.md principle 6. A10G (SM86) and MI350X goldens should be unaffected, since cuDNN varlen was never selected there.torchtitan/models/common/attention/attention.py:529-- The TODO has no upstream issue link (see inline comment).
Questions
- Was the old B200 golden reproducible at all? If cuDNN's varlen backward is nondeterministic, the current golden was recorded from a run that two identical runs can't reproduce. That would mean
kimi_k3_mm_muonwas flaky (or tolerance-masked) on main. Worth one line in the PR description.
Details
- Gate: the problem is real and has a concrete repro in the description. The root cause is upstream:
torch.nn.attention.varlenbackend selection doesn't skip cuDNN underdeterministicAlgorithms(), unlike regular SDPA. A local filter in torchtitan is the smallest workaround, and the call site is the only one in the repo that selects backends. - Doing the check in forward instead of
__init__: the engine callsset_determinism(training_engine.py:336) beforemodel_config.build()(:391), so__init__would also work for the trainer. Forward stays correct when the flag is toggled after the model is built (graph_trainer numerics tests do that). It costs a few Python ops per layer, and other attention modules already query the flag in forward (linear_attention.py:67,kda.py:106). Fine as is. - RL parity: per
torchtitan/rl/BITWISE_PARITY.md, the generator runs the sameVarlenInnerAttentionthrough vLLMCUSTOM, and the generator also sets the deterministic flag (generator.py:333). Both sides should therefore filter the same way. - Tests: the parametrized test guards cuDNN silently coming back in deterministic mode, which is an invariant worth a CPU test. The raise test is small.
Not verified: that cuDNN varlen backward ignores the deterministic flag in the pinned torch, and that FA2/FA3/FA4 varlen backward is deterministic under the flag. Both need a GPU run.
| # TODO: Remove once the cuDNN varlen backward honors | ||
| # use_deterministic_algorithms (upstream issue not filed yet). It | ||
| # neither raises nor runs deterministically, so repeated runs differ. |
There was a problem hiding this comment.
This TODO works around a PyTorch gap: the varlen backend selection doesn't apply the deterministic check that regular SDPA uses to skip cuDNN. Per CLAUDE.md principle 3, a TODO like this needs an upstream issue link. Without one, nothing tells us when it is safe to remove, and the right fix (varlen dispatch skips cuDNN when deterministicAlgorithms() is on, or the cuDNN backward honors the flag) never gets requested. Please file the pytorch/pytorch issue and write it as # TODO(pytorch/pytorch#NNNNN): ....
…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.
1fb64e6 to
930ba5b
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.
|
@tianyu-l I'll propose another diff stack to guard the spmd.I + deterministic and fix vision encoder. I don't want to complicated this diff stack. |
drisspg
left a comment
There was a problem hiding this comment.
@liangel-02 can you figure out why its not respecting this flag in pytorch this is a high pri bug
|
@liangel-02 Just created an issue and assigned it to you: pytorch/pytorch#204310 |
Stacked PRs:
[attention] Skip cuDNN varlen attention in deterministic mode
Summary (human-written)
VarlenInnerAttention always tries the cuDNN backend first, but the cuDNN backend ignores the use_deterministic_algorithms flag. So VarlenInnerAttention shouldn't use it when the flag is True.
This PR fixes the issue.
Why
VarlenInnerAttention tries cuDNN first. The cuDNN varlen backward ignores torch.use_deterministic_algorithms: it neither raises nor runs deterministically. So on main, deterministic runs of any varlen model on SM90/SM100 silently differ, which breaks the bitwise loss comparisons that deterministic mode exists for.
Example.
What changed
Alternatives considered
Numerics
Unchanged with deterministic mode off. With it on, varlen runs on SM90/SM100 use Flash instead of cuDNN. No golden loss file changes: the only real_pg golden (kimi_k3_b200, test kimi_k3_mm_muon) uses flex attention, and B200 CI passed with this change (run 42707592570).
Testing
Known issues / follow-ups