Repository navigation
[distributed] Store frozen parameters in param_dtype - #5894
Merged
Merged
Conversation
## Summary (human-written) When doing LoRA, most parameters do not need to be in float32 because they are not trained. By storing them in the compute dtype (param_dtype), we can fit Muse Spark Open LoRA into 8 GB300 with a bf16 compute dtype. ## Why TorchTitan stores every parameter, grad and optimizer state in precision.dtype. Frozen parameters (LoRA base weights, a frozen MoE router gate) get no grad and no update, and FSDP computes them in precision.param_dtype. So fp32 storage holds no extra information and doubles their memory. Today LoRA recipes must choose: dtype=float32 (the PrecisionConfig default, used by the llama3 and Qwen3.5 debug LoRA recipes) keeps the frozen base in fp32 (2x memory), or dtype=bfloat16 puts the adapters and AdamW state in bf16 (the Muse Spark UltraData LoRA recipe). **Example.** ``` Llama 3 8B, LoRA rank 8 on wqkv/wo, dtype=float32, param_dtype=bfloat16, 1 x H100, 2048 tokens before: frozen base stored in fp32 -> peak reserved 39.27 GiB after: frozen base stored in bf16 -> peak reserved 22.50 GiB LoRA adapters, their grads and AdamW state stay in fp32 in both runs. ``` ## What changed - Add maybe_store_frozen_params_in_param_dtype_(module, precision) (torchtitan/distributed/fsdp.py). When param_dtype is narrower than dtype, it swaps each frozen parameter to param_dtype with torch.utils.swap_tensors. Otherwise it does nothing, because a wider copy of a value that never changes only costs memory. preserve_dtype_params keep their dtype. Parameter identity (tied weights) and attributes (e.g. the SPMD type) are kept. - TrainingEngine._initialize_model calls it on the meta model right after build, before pipeline()/parallelize() (FSDP records dtypes at fully_shard; PP copies the meta model) and before init_weights. - The RL generator (build_inference_model in torchtitan/rl/generator/model.py) calls the helper instead of its own copy of the loop. All its parameters are frozen. Behavior is unchanged in every allowed config: the old loop also cast when param_dtype was wider, but the only such pair is dtype=bfloat16, param_dtype=float32, which PrecisionConfig now rejects. - graph_trainer precompile_main.py builds its own model and applies the same rule as the trainer, so its graphs match. This is untested: graph_trainer with frozen params already fails at the parent commit (chunked_loss.py:98 calls p.grad.detach() on the frozen lm_head). - PrecisionConfig rejects dtype=bfloat16 with param_dtype=float32 (fp32 compute on bf16 storage). Nothing in the repo uses it, and the RL trainer sends weights in param_dtype there, so a generator that kept bf16 storage would not match the weight sync dtype. - The numerics_debugging skill snippet that sets param_dtype=float32 also sets dtype=float32, so it works on bf16 recipes. - PrecisionConfig.dtype docstring states the rule. - No new config field, env var or flag. Other model builds were checked: torchft and the RL trainer go through TrainingEngine._initialize_model; the rest are tests. ## Alternatives considered - A config flag: the rule saves memory with no numerics cost when a checkpoint is loaded, so there is no reason to turn it off. - Casting after parallelize(): FSDP has already recorded the dtypes and PP has already copied the model. - dtype=bfloat16 for LoRA: it also lowers the adapters, their grads and AdamW state. ## User-facing changes | Case | Before | After | | --- | --- | --- | | Frozen param, dtype=float32, param_dtype=bfloat16 | stored in fp32 | stored in bf16 | | Frozen param in preserve_dtype_params | its own dtype | unchanged | | Trainable param, or param_dtype not narrower than dtype | stored in dtype | unchanged | | dtype=bfloat16, param_dtype=float32 | allowed | ValueError | ## Numerics With a loaded checkpoint, loss and grad_norm are bitwise equal to the parent commit when both runs use the same l2norm backward config (see the table below). FSDP all-gathers a frozen fp32 parameter in bf16 before compute, so it computes with the same bf16 values. Loading casts into each parameter's own dtype (DCP copy_, HF load through dcp.load). Random init without a checkpoint changes numerics: init ops such as uniform_ and kaiming_uniform_ run in bf16 for frozen params, which differs from fp32 init followed by rounding. The configs with golden losses have no frozen parameters, so no golden changes. scripts/loss_compare.py, seed 42, deterministic, seed checkpoint created at the parent commit (fp32 frozen values), 20 steps, values read from TensorBoard, --assert-equal on loss and grad_norm: | Config | GPUs | Result | Peak reserved before -> after | | --- | --- | --- | --- | | llama3_debugmodel_lora | 1 x H100 | loss and grad_norm bitwise equal, 20/20 steps | 0.75 -> 0.73 GiB | | qwen35_debugmodel_moe_lora (seq_len 512, no parallelism) | 1 x H100 | see the determinism table below | 0.80 -> 0.53 GiB | | Llama 3 8B LoRA (random init, memory only) | 1 x H100 | - | 39.27 -> 22.50 GiB | qwen35_debugmodel_moe_lora is not deterministic at the parent commit (base below) across processes. One base-vs-commit compare failed: grad_norm differed from step 1 (0.048898667 vs 0.048898663), and loss differed from step 3. The base run was the outlier. Determinism runs, same config: | Compare | Triton/Inductor caches | Passed / runs | First differing step | | --- | --- | --- | --- | | base vs base | shared | 4 / 4 | - | | commit vs commit | shared | 3 / 3 | - | | base vs commit | shared | 4 / 5 | step 1 (grad_norm) in the failing run | | base vs base | empty | 1 / 1 | - | | commit vs commit | empty | 1 / 1 | - | | base vs commit | empty | 1 / 1 | - | The cause is the GDN l2norm backward (attn_gym l2norm_bwd_kernel). torchtitan calls attn_gym l2norm with the default autotune=True. The kernel autotunes num_warps and BT, and the choice changes the order of its row reduction (tl.sum over head_dim). The timings are within noise, so the choice depends on the process and on which autotune cache it reads. attn_gym's l2norm docstring says autotune=False is needed for an input grad that is reproducible across processes and cache states. Each run produces one of two results. With empty caches, the base-vs-base pair got one result, and the commit-vs-commit and base-vs-commit pairs both got the other. The failing compare was the first run of this config: its base run tuned the kernel cold (step 1 took 5 minutes) and chose num_warps=4, while later runs read cache entries with num_warps=8 or 16. The forward does not use the kernel, which is why the step-1 loss matched. The runs in this section were measured with a parent that also contained the Muse Spark SLAKE recipe commit, which these configs do not use; the patch of this commit is byte-identical. On 1 GPU, FSDP is still applied, so the mixed-dtype FSDP groups are exercised: frozen bf16 next to trainable fp32 in decoder blocks, plus preserved fp32 GDN params in qwen3.5, and all-frozen bf16 vision encoder groups. GB300 fake-PG sizing with a recipe not in this PR (Muse Spark 816B multimodal, LoRA on vision and decoder, 4K tokens, BF16 Dist-MoE, dp_shard=EP=8, dtype=float32, job 2368236): 8 logical GPUs fit with this rule (steady 254 GiB allocated / 261 GiB reserved of 276.6 GiB); without it, OOM at init. ## Testing - New CPU test test_maybe_store_frozen_params_in_param_dtype (tests/unit_tests/cpu/distributed/test_fsdp.py): with fp32/bf16, frozen params become bf16 with exact values; trainable and preserve_dtype params keep fp32; tied weights stay one object; parameter attributes survive. With fp32/fp32 nothing changes. It catches a silent memory regression (frozen params left in fp32) and a silent numerics bug (a lowered preserve_dtype param). - test_precision_rejects_bf16_storage_with_fp32_compute (tests/unit_tests/cpu/config/test_config_validation.py) checks the new ValueError. - All runs used GPU 3 only. During the determinism runs, a sampler confirmed that no other process used it. - CPU tests: tests/unit_tests/cpu/distributed/test_fsdp.py, cpu/config, cpu/models/common/test_dist_moe.py and test_lora.py: 260 passed, 1 skipped. tests/rl/unit_tests/cpu in the titan-rl env: 534 passed, 9 skipped (test_vllm_wrapper.py and test_dapo_math.py were left out: they fail to import attn_gym.mla in this env, also at the parent commit). - Existing integration entries already cover the change with no new entry: "lora" (llama3_debugmodel_lora_tp2_pp2, 8 GPUs) and "qwen3_5_moe_lora" (h100). Neither has a golden loss file. ## Known issues / follow-ups - GDN l2norm backward autotuning makes Qwen3.5 and other GDN models non-deterministic across processes, also on main. Passing autotune=False to l2norm in deterministic mode is a separate fix. - Checkpoint saves write frozen params in bf16. If the source checkpoint has fp32 frozen weights (preserve_dtype_params excepted), a saved full model keeps only their bf16 values. Training numerics are not affected, since FSDP computes them in bf16 anyway. - The 8-GPU LoRA integration configs (TP2+PP2, DP2+PP2+TP2+EP4) were not rerun for this commit; only one H100 was free. - GB300 bitwise check with Dist-MoE from the HF checkpoint (Dist-MoE needs SM100, so it was not tested on H100). - RL smoke run to check weight sync. - Switch the Ultradata LoRA recipe to dtype=float32 in a separate PR. stack-info: PR: #5894, branch: fegin/stack/23
fegin
requested review from
IvanKobzarev,
SherlockNoMad,
acisseJZhong,
aditvenk,
felipemello1,
sanketpurandare,
shuhuayu,
tianyu-l,
wwwjn and
ydwu4
as code owners
November 6, 2026 01:51
This was referenced Nov 6, 2026
fegin
marked this pull request as draft
November 9, 2026 17:24
fegin
marked this pull request as ready for review
November 9, 2026 17:25
fegin
added a commit
that referenced
this pull request
Nov 9, 2026
…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.
fegin
marked this pull request as draft
November 9, 2026 20:45
fegin
force-pushed
the
fegin/stack/23
branch
2 times, most recently
from
November 9, 2026 20:46
426c687 to
13ac618
Compare
fegin
marked this pull request as ready for review
November 9, 2026 20:46
fegin
added a commit
that referenced
this pull request
Nov 9, 2026
… 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.
fegin
marked this pull request as draft
November 9, 2026 21:57
fegin
marked this pull request as ready for review
November 9, 2026 21:58
This was referenced Nov 10, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stacked PRs:
[distributed] Store frozen parameters in param_dtype
Summary (human-written)
When doing LoRA, most parameters do not need to be in float32 because they are not trained. By storing them in the compute dtype (param_dtype), we can fit Muse Spark Open LoRA into 8 GB300 with a bf16 compute dtype.
Why
TorchTitan stores every parameter, grad and optimizer state in precision.dtype. Frozen parameters (LoRA base weights, a frozen MoE router gate) get no grad and no update, and FSDP computes them in precision.param_dtype. So fp32 storage holds no extra information and doubles their memory. Today LoRA recipes must choose: dtype=float32 (the PrecisionConfig default, used by the llama3 and Qwen3.5 debug LoRA recipes) keeps the frozen base in fp32 (2x memory), or dtype=bfloat16 puts the adapters and AdamW state in bf16 (the Muse Spark UltraData LoRA recipe).
Example.
What changed
Alternatives considered
User-facing changes
Numerics
With a loaded checkpoint, loss and grad_norm are bitwise equal to the parent commit when both runs use the same l2norm backward config (see the table below). FSDP all-gathers a frozen fp32 parameter in bf16 before compute, so it computes with the same bf16 values. Loading casts into each parameter's own dtype (DCP copy_, HF load through dcp.load).
Random init without a checkpoint changes numerics: init ops such as uniform_ and kaiming_uniform_ run in bf16 for frozen params, which differs from fp32 init followed by rounding. The configs with golden losses have no frozen parameters, so no golden changes.
scripts/loss_compare.py, seed 42, deterministic, seed checkpoint created at the parent commit (fp32 frozen values), 20 steps, values read from TensorBoard, --assert-equal on loss and grad_norm:
qwen35_debugmodel_moe_lora is not deterministic at the parent commit (base below) across processes. One base-vs-commit compare failed: grad_norm differed from step 1 (0.048898667 vs 0.048898663), and loss differed from step 3. The base run was the outlier. Determinism runs, same config:
The cause is the GDN l2norm backward (attn_gym l2norm_bwd_kernel). torchtitan calls attn_gym l2norm with the default autotune=True. The kernel autotunes num_warps and BT, and the choice changes the order of its row reduction (tl.sum over head_dim). The timings are within noise, so the choice depends on the process and on which autotune cache it reads. attn_gym's l2norm docstring says autotune=False is needed for an input grad that is reproducible across processes and cache states. Each run produces one of two results. With empty caches, the base-vs-base pair got one result, and the commit-vs-commit and base-vs-commit pairs both got the other. The failing compare was the first run of this config: its base run tuned the kernel cold (step 1 took 5 minutes) and chose num_warps=4, while later runs read cache entries with num_warps=8 or 16. The forward does not use the kernel, which is why the step-1 loss matched.
The runs in this section were measured with a parent that also contained the Muse Spark SLAKE recipe commit, which these configs do not use; the patch of this commit is byte-identical.
On 1 GPU, FSDP is still applied, so the mixed-dtype FSDP groups are exercised: frozen bf16 next to trainable fp32 in decoder blocks, plus preserved fp32 GDN params in qwen3.5, and all-frozen bf16 vision encoder groups.
GB300 fake-PG sizing with a recipe not in this PR (Muse Spark 816B multimodal, LoRA on vision and decoder, 4K tokens, BF16 Dist-MoE, dp_shard=EP=8, dtype=float32, job 2368236): 8 logical GPUs fit with this rule (steady 254 GiB allocated / 261 GiB reserved of 276.6 GiB); without it, OOM at init.
Testing
Known issues / follow-ups