Repository navigation
[ops] Deterministic grid_sample backward for the NaViT position embedding - #5892
Conversation
…ding ## Summary (human-written) Add deterministic grid_sample backward. We will switch to pytorch/pytorch#196856 once it lands. However, the wrapper to turn on deterministic mode is still needed. ## Why NaViT samples its position table with F.grid_sample. The CUDA grid_sample backward accumulates with atomic adds, so the input grad changes from run to run. positional_embedding_vlm is invariant over TP and CP, so on main every rank computes a different grad and the copies drift. Deterministic mode does not help: it raises on this op. **Example.** ``` NaViT-sized table [1, 1536, 32, 32], sampled at a 37x37 grid, same inputs, two backward runs before (F.grid_sample): input grads differ between runs after (this op): input grads bitwise equal over 10 eager runs, and over 2 compiled runs ``` ## What changed - Add torchtitan::deterministic_grid_sample (torchtitan/ops/grid_sample.py): bilinear, zeros padding, align_corners=False. The forward is F.grid_sample. The backward builds a dense bilinear weight matrix (P x H*W, 4 nonzeros per row) and computes the input grad as one matmul in at least fp32, with no gather, scatter or atomics. It raises ValueError if the grid needs a gradient. - NaViT samples its position table with the op. - The unused grid_sample_mode config field is removed; only bilinear was used. - TODO in code: switch to the upstream deterministic grid_sample backward once pytorch/pytorch#196856 lands. ## Alternatives considered - A scatter_add backward on corner indices: also deterministic, but needs 528-535 MiB per frame at a 37x37 grid (1554-1578 MiB at 64x64) and is 4-11x slower. ## Numerics The NaViT position-embedding input grad accumulates in fp32 and is deterministic. At a 37x37 grid it differs from native grid_sample by up to 0.64 in bf16 (native accumulates in bf16 with atomics) and by up to 7.2e-7 in fp32. In fp64 the difference is 1.3e-15. The forward is unchanged. | Config | Hardware | Result | | --- | --- | --- | | Spark debug_mm CP2 and TP2, full FT, global deterministic mode off, 60 steps | 2 x H100 | replicated params (including positional_embedding_vlm) bitwise equal, grad_norm identical per rank, every step | ## Performance Peak backward memory for one frame (1536 channels, 32x32 table): 43-51 MiB at a 37x37 grid and 54-78 MiB at 64x64. The matrix is P x H*W, so the cost grows with the table size. ## Testing - CPU tests: fp64 forward equal and backward within 1e-12 of F.grid_sample (with out-of-bounds points), gradcheck, opcheck (fake and autograd registration), and grid-grad rejection. They catch wrong bilinear weights, wrong padding, and a broken fake or autograd registration. - GPU test: the input grad of a NaViT-sized table is bitwise equal over 10 eager runs, and over 2 compiled runs, in fp32 and bf16. Eager and compiled are not compared to each other, since Inductor may round differently. It catches a non-deterministic backward. - CPU tests at this commit: tests/unit_tests/cpu/ops and models/muse_spark, 37 passed, 3 xfailed. stack-info: PR: #5892, branch: fegin/stack/21
|
@claude review this pr |
There was a problem hiding this comment.
Verdict: Approve -- The problem is real: the CUDA grid_sample backward uses atomics, and global deterministic mode raises on it. The fix is small, sits in torchtitan/ops/ next to the other deterministic ops, and has a TODO pointing to the upstream fix (pytorch/pytorch#196856). torchtitan/ops is shared code, so a maintainer still needs to review.
What this PR does. NaViT samples positional_embedding_vlm with F.grid_sample. That parameter is Invariant over TP and CP, so each rank computes its own grad with no all-reduce. Before this PR, the atomic-add backward gave each rank a slightly different grad, and the copies drifted. The new op torchtitan::deterministic_grid_sample keeps the native forward. Its backward builds a dense bilinear weight matrix (P x H*W, 4 nonzeros per row) and computes the input grad as one fp32 matmul. The grid_sample_mode field is removed; it was always "bilinear" and no other caller sets it.
Example.
table [1, 1536, 32, 32] (bf16), grid 37x37, same grad_output, TP2 ranks r0 and r1
before: r0.grad != r1.grad (atomic order differs) -> positional_embedding_vlm drifts per rank
debug.deterministic=True -> grid_sampler_2d_backward_cuda raises
after: r0.grad == r1.grad bitwise, accumulated in fp32 instead of bf16 atomics
Should consider
tests/unit_tests/gpu/ops/test_grid_sample.py:25-31-- the test requires eager and compiled grads to be bitwise equal. Training doesn't need that, and it may only hold because the table side is a power of two. Compare each path against itself instead (inline).
Details
- Bilinear math in
_input_gradmatches the native kernel for align_corners=False and zeros padding. Unnormalization is((g + 1) * size - 1) / 2, followed by floor. The bounds check (0 <= idx <= size - 1) matcheswithin_bounds_2d. An out-of-bounds corner can alias a valid pixel index, but its weight is already 0, so the alias adds nothing. - Numerics: the bf16 grad of
positional_embedding_vlmchanges from bf16 atomic accumulation to fp32 accumulation, which the description explains. The forward is unchanged. Muse Spark has no golden loss files, so nothing needs regenerating. - Cost: the weight matrix is about 5.6 MB per frame in fp32 at 37x37 points on a 32x32 table. It grows linearly with the number of patches per frame, and there is one per call to
_get_pos_emb. That is acceptable for the debug and production table sizes. - Callsites:
grid_sample_modehas no other users in the repo, including recipes and muse_glimmer.
Not verified: GPU tests and the H100 CP2/TP2 run in the description (no GPU here). I also couldn't run the CPU tests, because the pytest command needed permission that wasn't granted.
| grads = [] | ||
| for fn in [deterministic_grid_sample] * 10 + [compiled]: | ||
| table.grad = None | ||
| fn(table, grid).backward(grad_output) | ||
| grads.append(table.grad.clone()) | ||
| for grad in grads[1:]: | ||
| assert torch.equal(grad, grads[0]) |
There was a problem hiding this comment.
This checks that the compiled backward is bitwise equal to the eager one, and training doesn't need that: every TP/CP rank runs the same path, so the property we care about is that a given path repeats itself. Bitwise eager == compiled is also fragile. Inductor can fuse ((g + 1) * W - 1) / 2 and the weight products into FMAs. The test probably only passes because H = W = 32 is a power of two, which makes (g + 1) * W exact (unverified, I couldn't run on GPU). With a non-power-of-two table, or after an Inductor change, this could start failing even though the op is still deterministic.
Suggest checking eager against eager and compiled against compiled separately, e.g. [deterministic_grid_sample] * 10 + [compiled] * 2, and comparing grads[:10] to grads[0] and grads[11] to grads[10].
…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.
8738cd7 to
d3cb854
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.
Stacked PRs:
[ops] Deterministic grid_sample backward for the NaViT position embedding
Summary (human-written)
Add deterministic grid_sample backward. We will switch to pytorch/pytorch#196856 once it lands. However, the wrapper to turn on deterministic mode is still needed.
Why
NaViT samples its position table with F.grid_sample. The CUDA grid_sample backward accumulates with atomic adds, so the input grad changes from run to run. positional_embedding_vlm is invariant over TP and CP, so on main every rank computes a different grad and the copies drift. Deterministic mode does not help: it raises on this op.
Example.
What changed
Alternatives considered
Numerics
The NaViT position-embedding input grad accumulates in fp32 and is deterministic. At a 37x37 grid it differs from native grid_sample by up to 0.64 in bf16 (native accumulates in bf16 with atomics) and by up to 7.2e-7 in fp32. In fp64 the difference is 1.3e-15. The forward is unchanged.
Performance
Peak backward memory for one frame (1536 channels, 32x32 table): 43-51 MiB at a 37x37 grid and 54-78 MiB at 64x64. The matrix is P x H*W, so the cost grows with the table size.
Testing