Repository navigation
[lora] Merge expert LoRA weights without a full-weight copy - #5893
Conversation
## Summary (human-written) With Dist-MoE + LoRA, we have to materialize W_eff with torch.baddbmm. This is already not optimal. The out-of-place torch.baddbmm also incurs one extra copy (see Why below). This PR uses torch.compile to work around the extra copy, which gives us 2.2% speedup in our settings (measured end to end with CUDA graphs on). ## Why Dist-MoE consumes full expert weights, so LoRA on its w13/w2 builds W_eff = W + scale * (B @ A) with torch.baddbmm(W, B, A) in forward and again in the remat recompute. Out-of-place baddbmm first copies W into its output (TORCH_META_FUNC(baddbmm) runs result.copy_(self) when beta != 0), then the cuBLASLt GEMM reads and writes that output (C == D). So each merge moves the full expert weight twice. In a CUDA graph the copy is a DtoD memcpy node, about 2x slower than eager on GB300 (1 GiB copy_: 321 us eager, 684 us graphed). **Example.** ``` GB300, w13 merge at EP16: W [16, 8192, 4096] bf16 (1 GiB), rank 8 before: memcpy W -> out, then GEMM with C = D = out fwd 697 us eager, 1075 us graphed after: one fused GEMM: reads W, writes W_eff fwd 525 us eager, 520 us graphed ``` ## What changed - `_merge_expert_lora` (torchtitan/models/common/lora.py) computes `W + baddbmm(empty, B, A, beta=0, alpha=scale)`. beta=0 skips the copy. - It is compiled twice through the always-compiled `local_compile.compile` helper: - `_autotuned_merge_expert_lora` (default): `max_autotune_gemm`. Inductor can fuse the add into a Triton GEMM epilogue (triton_tem_fused_add_baddbmm), so W is read once and W_eff written once. It chose that kernel in every H100 and GB300 run, including the end-to-end runs below. If cuBLAS wins the benchmark instead, the add runs as a second kernel. It benchmarks kernels in each process, so the chosen kernel can differ between runs. - `_deterministic_merge_expert_lora`, when `torch.are_deterministic_algorithms_enabled()` (debug.deterministic): Inductor `deterministic=True`, which skips benchmarking. It runs a cuBLAS GEMM and then an in-place add: no copy and no extra full-size buffer, but two passes. - Both keep the default Dynamo recompile_limit of 8. They share one cache for the function, and with fullgraph=True a 9th entry raises. Each new weight shape, dtype, scale value, W requires_grad or deterministic setting adds an entry. A training run needs 2 (w13 and w2 shapes), and so do the unit tests. - `_MergeExpertLoRA` wraps it in an autograd Function. Only the forward is compiled. The backward stays eager and uses the torch.baddbmm derivative formulas, so gradients do not depend on kernel choices. It returns the incoming gradient for W when W requires grad (d W_eff / d W is the identity), and None for a frozen W. - `_LoRADistMoeRoutedExpertsMixin._weight_operands` calls it for w13 and w2 instead of torch.baddbmm. This is the only callsite. The standard MoE path already applies LoRA to activations and never merges weights; MXFP8 Dist-MoE has no LoRA. - test_dist_moe.py: test_lora_dist_moe_weight_operands_backpropagate_only_to_adapters also compares every adapter gradient with a torch.baddbmm reference. - No new config field, flag or env var. ## Alternatives considered - bmm then add: bitwise only for a power-of-2 scale, its backward adds a full-size grad * scale kernel, and it needs a second full-size buffer. - Only the deterministic (cuBLAS + add) path, without autotuning: deterministic everywhere and copy-free, but about 1.9x slower than the fused kernel on H100 (w13 1926 us vs 1016 us). - Hand-written Triton kernel with the same rounding: also bitwise and faster on GB300 (349 us w13 fwd vs 525 us), but it is a kernel to maintain for ~0.2 ms per merge. - A single-rounding fused kernel: slightly more accurate, but changes 0.6-6% of W_eff elements by 1 ulp, which is a computation change. - LoRA on activations inside Dist-MoE: the long-term fix (see follow-ups); it needs dist_moe changes. ## User-facing changes | Case | Before | After | | --- | --- | --- | | Dist-MoE with LoRA on w13/w2 | baddbmm with a full-weight copy | autotuned merge (fused in the tested cases); cuBLAS + in-place add in deterministic mode; same values in the tested cases | | Everything else | unchanged | unchanged | ## Numerics Bitwise equal to torch.baddbmm in every tested case. cuBLAS baddbmm rounds scale * (B @ A) to bf16 before adding W; both compiled versions do the same. Tested cases: - Micro-benchmark, W_eff, a per-expert projection y, and dx, dB, dA against torch.baddbmm, rank 8, scale 2.0 (the recipes: alpha 16 / rank 8) and 1.7, shapes w13 [16, 8192, 4096] and w2 [16, 4096, 4096]: bitwise on H100 and on GB300 (job 2375100), with the autotuned path. - H100, rank 8, 32 and 64, scale 2.0 and 1.7, both shapes: W_eff, dB and dA bitwise in both modes. The profiler shows the kernels that ran: the autotuned path always picked the fused Triton template (triton_tem_fused_add_baddbmm), also when only Triton templates were allowed; deterministic mode ran cuBLAS (nvjet) plus a Triton add. - GB300 end to end: one run, Muse Spark debug model (a recipe not in this PR), BF16 Dist-MoE, decoder LoRA rank 8 including w13 and w2, dp_shard 2 x TP 2, EP 2, activation remat on (ActivationRematConfig saving attention.inner_attention and the Dist-MoE region), CUDA graphs off, seed 42, deterministic, 30 steps: loss and grad_norm bitwise equal to the parent on all 30 steps, no recompiles (jobs 2375102 and 2375104). That run used the autotuned path, before the deterministic-mode switch was added. - GB300 end to end with accelerator graphs on: same debug model, BF16 Dist-MoE, decoder LoRA, dp_shard 2 x TP 2, EP 2, seed 42, deterministic, 30 steps (jobs 2391673 base, 2391675 this PR): loss and grad_norm bitwise equal on all 30 steps. CUDA graphs record during step 3 after 2 eager warmup steps, so the first merge call per shape runs outside capture. No capture errors, no recompiles. Not covered: other ranks, scales and GPUs, and every autotune choice. Outside deterministic mode, a different kernel choice could change bits in another process; no such case was seen. ## Performance End to end, GB300, recipe muse_spark_816b_a42b_ultradata_lora_sft_cp16_128k as shipped: CP16 x EP16 = 16 GPUs, 128K sequence, random init, 20 steps, base = parent commit, one run per cell: | Mode | Base median step | This PR median step | Mean step saved (paired by step) | MFU | | --- | --- | --- | --- | --- | | graphs on (recipe default) | 3.085 s | 2.978 s | 2.2% (SE 0.7%), faster in 12/15 steps | 51.3% -> 53.1% | | eager | 3.395 s | 3.300 s | 0.7% (SE 1.2%), not significant | 46.6% -> 47.9% | Peak memory is unchanged (243.95 / 243.40 GiB). Jobs 2391664/2391666 (graphs), 2391668/2391670 (eager). Profile, graphs on, one replayed step, rank 0 (rank 8 agrees), jobs 2410040 (base) and 2410042 (this PR). There are 248 merges per step: 62 layers x (w13, w2) x (forward, remat recompute). | Merge | Base: copy + cuBLAS baddbmm | This PR: fused Triton GEMM with the add in the epilogue | | --- | --- | --- | | w13 [16, 8192, 4096] bf16 | 775 + 372 = 1147 us | 515 us | | w2 [16, 4096, 4096] bf16 | 385 + 187 = 572 us | 265 us | | merge GPU time per step | 217.8 ms | 97.8 ms | | GPU step time | 3732.8 ms | 3616.1 ms (-3.1%) | The step saving (117 ms) matches the merge saving (120 ms); other kernels are unchanged. Micro-benchmark, GB300, w13 merge [16, 8192, 4096] bf16, rank 8, autotuned path (job 2375100): | | fwd eager | fwd graphed | fwd+bwd graphed | fwd peak extra | | --- | --- | --- | --- | --- | | before (baddbmm) | 697 us | 1075 us | 1386 us | 1.03 GiB | | after | 525 us | 520 us | 830 us | 1.00 GiB | H100, same shapes, rank 8: | | w13 fwd eager / graphed | w13 fwd+bwd graphed | w2 fwd eager / graphed | w2 fwd+bwd graphed | | --- | --- | --- | --- | --- | | before | 2287 / 2383 us | 3371 us | 1144 / 1189 us | 1701 us | | after, autotuned | 1018 / 1010 us | 2001 us | 512 / 510 us | 1020 us | | after, deterministic mode (fwd eager) | 1926 us | - | 976 us | - | What stays alive until backward is unchanged: Dist-MoE still saves W_eff. The first call of each shape compiles and, outside deterministic mode, autotunes. It must not first run inside a CUDA graph capture. AcceleratorGraphWrapper runs eager warmup calls before capture, so the first call is eager there. ## Testing - tests/unit_tests/cpu/models/common/test_lora.py, tests/unit_tests/cpu/config/, tests/unit_tests/cpu/recipes/, tests/unit_tests/cpu/models/common/test_dist_moe.py: 291 passed, 1 skipped. test_dist_moe.py is skipped here because dist_moe is not installed; it runs in the B200 CI. - The extended test's comparison was run standalone against `_MergeExpertLoRA` at the test shapes: CPU fp32 (assert_close) and H100 bf16 (bitwise), in both modes, with W frozen and with W requiring grad. - Dynamo cache entries counted on CPU and H100 by calling `_MergeExpertLoRA` with varied inputs: one entry per (shape, dtype, scale, W requires_grad, deterministic setting); rebuilding the compiled helpers through `LocalCompileConfig.apply()` reuses the entries. A 9th entry raises. - H100 and GB300 micro-benchmarks, and the end-to-end runs above. ## Known issues / follow-ups - Upstream issue not filed yet: out-of-place baddbmm/addmm should pass self to cuBLASLt as C and write D, instead of copying self into the output first. Then this code can call torch.baddbmm directly (TODO in the code). - Long-term fix: LoRA on routed activations inside dist_moe. It removes the merge, the full-size W_eff gradient and its contraction into dA/dB, and the saved W_eff (~1.5 GiB per MoE layer per rank at EP16). dist_moe also computes WGRAD for frozen weights today. - No LoRA end-to-end CI entry. The B200 BF16 Dist-MoE entry tests in-place WGRAD accumulation, which Dist-MoE LoRA rejects. - Untested: spmd_types type checking (fullgraph compile under the checking mode) and graph_trainer tracing through the nested compile. stack-info: PR: #5893, branch: fegin/stack/22
|
@claude review this pr |
|
Claude finished @fegin's task in 4m 35s —— View job Needs discussion -- review posted. No code bugs found; the upstream baddbmm issue needs to be filed and linked, and the speedup needs an end-to-end measurement with accelerator graphs on. |
There was a problem hiding this comment.
Verdict: Needs discussion -- the code looks correct and the backward matches torch.baddbmm's formulas. But this is about 90 LoC of local workaround (two compiled variants and a custom autograd Function) for an upstream baddbmm gap that hasn't been filed. Its end-to-end benefit is estimated, not measured. And the only in-repo consumer runs with accelerator graphs on, which no run covered.
What this PR does. Dist-MoE + LoRA builds W_eff = W + scale * (B @ A) twice per MoE layer per microbatch (forward and remat recompute). Out-of-place torch.baddbmm first copies W into the output. The PR computes the rank-L product with beta=0 and adds W in a compiled region: a fused Triton epilogue when autotuned, or cuBLAS plus an in-place add when deterministic algorithms are on. The backward stays eager and uses baddbmm's derivative formulas.
Example.
w13 merge, W [16, 8192, 4096] bf16 (1 GiB), rank 8, GB300
before: copy_(W -> out); GEMM(C = D = out) -> 2 full-W read+write passes
after: GEMM(B, A) -> delta; fused epilogue W+delta -> 1 pass (autotuned)
GEMM -> delta; delta += W -> 2 passes, no copy (deterministic)
Must fix
torchtitan/models/common/lora.py:264-- the TODO for the upstream baddbmm copy has no issue link. Inline.- Description -- the PR exists for performance, but the only number is "estimated ~2% ... not measured end to end". The target recipe,
muse_spark_816b_a42b_ultradata_lora_sft_cp16_128k(torchtitan_recipes/models/muse_spark.py:748), setsdisable_accelerator_graphs=False. The only end-to-end run had CUDA graphs off, and it ran before the deterministic-mode switch was added. Please report measured step-time/MFU from one run with accelerator graphs on (a debug-size variant of that recipe is enough), plus a bitwise loss check in deterministic mode. That one run covers the value claim, the new deterministic path, and the "first call must not be inside capture" invariant together. Training's graph wrappers warm up 2 iterations (NUM_ACCELERATOR_GRAPH_WARMUP_STEPS), so the invariant should hold, but nothing has run it.
Should consider
torchtitan/models/common/lora.py:279-- the_compiled_/_deterministic_names aren't symmetric; suggest_autotuned_merge_expert_lora. Inline.torchtitan/models/common/lora.py:273-274-- the comment says the default limit of 8 "is too small for a process that sees many weight shapes", but the description says training needs about 2 entries per mode. Please name the case that needs more than 8 (e.g. models with per-layer expert shapes, or test processes) so the value 16 is explained.
Questions
- No CI job exercises Dist-MoE + LoRA end to end. The B200 entries in
tests/integration_tests/b200.pyrun Dist-MoE with accelerator graphs but no LoRA, and the H100qwen3_5_moe_loratest uses standard MoE. Would addingLoRATransform(target_modules=["w13", "w2"])to the existingdeepseek_v3_debugmodel_dist_moe_bf16_fsdp2_ep2entry be cheap enough? It would exercise compile under graph warmup and spmd type checking on every PR.
Details
- Gate: the problem is real (the
TORCH_META_FUNC(baddbmm)copy when beta != 0) and has been measured. The root cause is upstream. With a copy-free out-of-place baddbmm, this code would collapse back to the singletorch.baddbmmcall, so the upstream link decides how long this code lives. - Backward:
grad.bmm(A^T) * scaleandB^T.bmm(grad) * scalematch thebaddbmmentries in derivatives.yaml (maybe_multiplyby alpha). The W gradient is the identity, matching beta=1. The extended unit test checks this against autograd throughtorch.baddbmm, which guards the hand-written backward. It runs in B200 CI (integration_test_b200.yaml:84). - Kernel choice differs across processes: EP ranks own disjoint experts, and DP replicas' adapter gradients are reduced, so a per-rank difference wouldn't diverge parameters. The RL generator has no LoRA, so trainer/generator parity is unaffected.
- Callsites:
_weight_operandsin the LoRA Dist-MoE mixin is the only merge site. MXFP8 Dist-MoE has no LoRA, and the standard MoE path applies LoRA to activations.
Not verified: the claim that cuBLAS baddbmm and the fused epilogue both round scale * (B @ A) to bf16 before the add (needs GPU), and that the Inductor deterministic option and the per-function recompile_limit behave as described on the pinned torch.
| TODO: Call ``torch.baddbmm(W, B, A)`` directly once out-of-place baddbmm | ||
| passes self to cuBLASLt as C and writes D without copying self first. |
There was a problem hiding this comment.
This TODO has no upstream issue link, and the PR description says the issue hasn't been filed. The whole helper works around a PyTorch gap: TORCH_META_FUNC(baddbmm) runs result.copy_(self), and cuBLASLt could take self as C and write D. CLAUDE.md principle 3 asks for a TODO with an issue link here. Without one, nobody can tell when the two compiled variants and _MergeExpertLoRA can be deleted.
Fix: file the pytorch/pytorch issue and put its link here, e.g. TODO(pytorch/pytorch#NNNNN): ....
| # GEMM autotuning can fuse the add into a Triton GEMM epilogue, so W is read | ||
| # once and the result written once. It benchmarks kernels in each process, so | ||
| # the chosen kernel can differ between runs. | ||
| _compiled_merge_expert_lora = compile( |
There was a problem hiding this comment.
Both helpers are compiled, so _compiled_ doesn't say how this one differs from _deterministic_merge_expert_lora. What sets it apart is GEMM autotuning. A symmetric name would make the dispatch at L313-317 clearer:
| _compiled_merge_expert_lora = compile( | |
| _autotuned_merge_expert_lora = compile( |
(then update the reference at L316.)
Stacked PRs: * #5904 * #5895 * #5894 * #5893 * #5892 * #5891 * #5890 * #5889 * #5888 * #5887 * #5885 * #5886 * __->__#5884 --- --- --- ### [lora] Derive adapter sharding from the base weight ## Summary (human-written) The current LoRA adapter assumes the sharding of the base weights to be `{DP: R, CP: R, TP: S(0)}` or ` {DP: R, CP: R, TP: S(1)}`. This is not always true. For example, if we apply LoRA to the vision encoder, the sharding is not the same. This PR fixes the issue by deriving adapter sharding from the base weight ## Why On main, LoRA adapter sharding accepts only a base weight equal to dense_param_placement(tp=S(0)) or dense_param_placement(tp=S(1)). Any other base placement fails at model build. This blocks LoRA on vision linears (CP-invariant, cp=I), TP-invariant vision adapters and projections (tp=I), and TP-replicated router gates (tp=R). **Example.** ``` LoRATransform(target_modules=["vision_encoder.block.mlp.fc1"]) # Muse Spark, base weight {dp: R, cp: I, tp: S(0)} before: AssertionError at build (placement is not dense_param_placement(tp=S(0))) after: lora_a {dp: R, cp: I, tp: R}, lora_b {dp: R, cp: I, tp: S(0)} ``` ## What changed - Adapters copy the base weight placement and change only the TP axis. Other axes, such as cp=I on vision weights, are kept. - Column-wise base: A is TP-replicated, B is sharded like the base. - Row-wise base: A is sharded like the base, B is TP-replicated. - TP-replicated or TP-invariant base (R, I), or no TP axis: both adapters copy the base. - Any other TP type (another Shard, P, V) raises ValueError. - Stacked projections ([num_linears, O, I]) use the same rule, with the output dim at 1. The separate stacked code path is removed. ## Numerics Unchanged for the bases main supports: the adapter placements for dense column-wise and row-wise bases, and for stacked column-wise bases, are the same as on main. No loss comparison was run. ## Testing - 2-rank CPU test with SPMD type checking: LoRA output and adapter grads of a Spark-style vision MLP and vision adapter at TP2 match TP1 (fp32, atol=rtol=1e-4). It catches wrong adapter placements on non-dense bases. - CPU tests at this commit: tests/unit_tests/cpu/models/common/test_lora.py, 32 passed.
…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.
f07a9b2 to
25f416f
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.
| _deterministic_merge_expert_lora | ||
| if torch.are_deterministic_algorithms_enabled() | ||
| else _autotuned_merge_expert_lora |
There was a problem hiding this comment.
I missed that this is for DistMoE and won't hit spmd.I sharding.
Maybe add a NOTE on it. And also a general TODO to remove the condition on if torch.are_deterministic_algorithms_enabled() -- everything should be deterministic.
Stacked PRs:
[lora] Merge expert LoRA weights without a full-weight copy
Summary (human-written)
With Dist-MoE + LoRA, we have to materialize W_eff with torch.baddbmm. This is already not optimal. The out-of-place torch.baddbmm also incurs one extra copy (see Why below). This PR uses torch.compile to work around the extra copy, which gives us 2.2% speedup in our settings (measured end to end with CUDA graphs on).
Why
Dist-MoE consumes full expert weights, so LoRA on its w13/w2 builds W_eff = W + scale * (B @ A) with torch.baddbmm(W, B, A) in forward and again in the remat recompute. Out-of-place baddbmm first copies W into its output (TORCH_META_FUNC(baddbmm) runs result.copy_(self) when beta != 0), then the cuBLASLt GEMM reads and writes that output (C == D). So each merge moves the full expert weight twice. In a CUDA graph the copy is a DtoD memcpy node, about 2x slower than eager on GB300 (1 GiB copy_: 321 us eager, 684 us graphed).
Example.
What changed
_merge_expert_lora(torchtitan/models/common/lora.py) computesW + baddbmm(empty, B, A, beta=0, alpha=scale). beta=0 skips the copy.local_compile.compilehelper:_autotuned_merge_expert_lora(default):max_autotune_gemm. Inductor can fuse the add into a Triton GEMM epilogue (triton_tem_fused_add_baddbmm), so W is read once and W_eff written once. It chose that kernel in every H100 and GB300 run, including the end-to-end runs below. If cuBLAS wins the benchmark instead, the add runs as a second kernel. It benchmarks kernels in each process, so the chosen kernel can differ between runs._deterministic_merge_expert_lora, whentorch.are_deterministic_algorithms_enabled()(debug.deterministic): Inductordeterministic=True, which skips benchmarking. It runs a cuBLAS GEMM and then an in-place add: no copy and no extra full-size buffer, but two passes._MergeExpertLoRAwraps it in an autograd Function. Only the forward is compiled. The backward stays eager and uses the torch.baddbmm derivative formulas, so gradients do not depend on kernel choices. It returns the incoming gradient for W when W requires grad (d W_eff / d W is the identity), and None for a frozen W._LoRADistMoeRoutedExpertsMixin._weight_operandscalls it for w13 and w2 instead of torch.baddbmm. This is the only callsite. The standard MoE path already applies LoRA to activations and never merges weights; MXFP8 Dist-MoE has no LoRA.Alternatives considered
User-facing changes
Numerics
Bitwise equal to torch.baddbmm in every tested case. cuBLAS baddbmm rounds scale * (B @ A) to bf16 before adding W; both compiled versions do the same.
Tested cases:
Not covered: other ranks, scales and GPUs, and every autotune choice. Outside deterministic mode, a different kernel choice could change bits in another process; no such case was seen.
Performance
End to end, GB300, recipe muse_spark_816b_a42b_ultradata_lora_sft_cp16_128k as shipped: CP16 x EP16 = 16 GPUs, 128K sequence, random init, 20 steps, base = parent commit, one run per cell:
Peak memory is unchanged (243.95 / 243.40 GiB). Jobs 2391664/2391666 (graphs), 2391668/2391670 (eager).
Profile, graphs on, one replayed step, rank 0 (rank 8 agrees), jobs 2410040 (base) and 2410042 (this PR). There are 248 merges per step: 62 layers x (w13, w2) x (forward, remat recompute).
The step saving (117 ms) matches the merge saving (120 ms); other kernels are unchanged.
Micro-benchmark, GB300, w13 merge [16, 8192, 4096] bf16, rank 8, autotuned path (job 2375100):
H100, same shapes, rank 8:
What stays alive until backward is unchanged: Dist-MoE still saves W_eff.
The first call of each shape compiles and, outside deterministic mode, autotunes. It must not first run inside a CUDA graph capture. AcceleratorGraphWrapper runs eager warmup calls before capture, so the first call is eager there.
Testing
_MergeExpertLoRAat the test shapes: CPU fp32 (assert_close) and H100 bf16 (bitwise), in both modes, with W frozen and with W requiring grad._MergeExpertLoRAwith varied inputs: one entry per (shape, dtype, scale, W requires_grad, deterministic setting); rebuilding the compiled helpers throughLocalCompileConfig.apply()reuses the entries. A 9th entry raises.Known issues / follow-ups