Skip to content

[models][fsdp] preserve_dtype_params: keep selected parameters out of mixed-precision casts - #5774

Merged
tianyu-l merged 1 commit into
mainfrom
preserve-dtype-params
Nov 4, 2026
Merged

tianyu-l merged 1 commit into
mainfrom
preserve-dtype-params

Conversation

@tianyu-l

@tianyu-l tianyu-l commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #5776 (GitHub stack: this PR's base is #5776's branch).

Summary (human-written)

pytorch/pytorch#196626 added MixedPrecisionPolicy.param_dtype_override_fn so FSDP can leave chosen parameters alone.

E.g., for GDN / KDA, the params A_log and dt_bias should never go through down-casting, during FSDP's pre-all-gather.

This PR is making it configurable.

Why

FSDP2 mixed precision (precision.param_dtype="bfloat16") casts every fp32 master parameter to bf16 at all-gather. Some parameters are numerically sensitive, and their reference checkpoints store them in float32 on HF:

Model Stored as F32 on HF
Qwen3.5 (0.8B, 27B, 35B-A3B) GDN linear_attn.A_log, GDN gated norm linear_attn.norm.weight
Kimi-Linear-48B-A3B (KDA) A_log, dt_bias
DeepSeek-V4-Flash hc_*_fn/base/scale, attn_sink, compressor ape

On main the kernels then upcast bf16-rounded values (gdn.py:480, kda.py:128, mhc.py:112). DSV4 even creates its head hc params with dtype=torch.float32, and FSDP still rounds them. The same rounding happens when RL publishes weights to generators (transfer_dtype) and when a final checkpoint is exported (export_dtype). pytorch/pytorch#196626 added MixedPrecisionPolicy.param_dtype_override_fn so FSDP can leave chosen parameters alone.

Example.

# GDN.Config (component default)
preserve_dtype_params: tuple[str, ...] = ("A_log", "dt_bias")

# fp32 masters, precision.param_dtype="bfloat16"
# before: FSDP all-gathers A_log in bf16; kernel computes exp(A_log.bf16().float())
# after:  A_log is all-gathered and used in fp32; RL sends and the generator uses it in fp32;
#         export_dtype="bfloat16" keeps it fp32, as in the HF release

What changed

  • Module.Config.preserve_dtype_params: tuple[str, ...]: names of a module's own parameters that bulk casts never lower in precision. Validated at build. Module.named_preserve_dtype_params() yields (fqn, param) for a module tree, like named_parameters().
  • Components whose math always needs it set the default: GDN and KDA (A_log, dt_bias), DSV4 HcPre/HcHead (hc_*), DSV4 Compressor (ape). Flavors set it for single instances of generic modules: Qwen3.5's GDN GatedRMSNorm, DSV4's attn_sink Linear.
  • FSDP: mixed_precision_policy(module, ...) builds the policy with param_dtype_override_fn (the wider of the parameter's dtype and param_dtype). Every core FSDP site that shards TorchTitan modules uses it (decoder, multimodal encoder, Flux model). Flux's HF T5/CLIP encoders keep their own policy (no TorchTitan modules). The graph_trainer experiment's SimpleFSDP has no per-parameter override, so GraphTrainerModel.parallelize raises if a model lists preserved params (none does today). Removes Decoder._fsdp_param_dtype_override_fn, added in [rl] generator: keep GDN A_log/dt_bias in float32 (6/7) #5691 with a TODO asking for this. Quantization converters raise on a Linear that lists preserved params instead of silently dropping the field.
  • RL (on [config] Move dtypes into a root-owned PrecisionConfig; FSDP CPU offload into ParallelismConfig #5776): the generator mirrors the trainer's Controller.Config.precision instead of its own generator.model_dtype (removed). It builds the model in precision.dtype, so buffers and preserved params get the trainer's dtypes. It holds every other parameter in precision.param_dtype and computes in it (vLLM dtype; the wrapper raises if they differ), so its FSDP casts nothing. The generator model is frozen, and parameters are cast with torch.utils.swap_tensors, since param.data = leaves a quantized tensor subclass's (MXFP8/NVFP4) inner tensor in the old dtype. vLLM's attention layers are still built in vLLM's model dtype, because vLLM picks their backend from the default dtype. The trainer sends parameters in param_dtype (transfer_dtype, when it differs from dtype), and buffers and preserved params in their own dtype (preserve_dtype_keys). The generator's receive buffers are its sharded state dict as is (cpu_prefetch), and gpu_fetch ([rl] Fetch generator weights from the StorageVolume into GPU #5652) fetches straight into the sharded parameters, so [rl] Fetch generator weights from the StorageVolume into GPU #5652's cast of float32 parameters through model-dtype staging tensors is removed. This generalizes [rl] generator: keep GDN A_log/dt_bias in float32 (6/7) #5691's GDN-only handling. With bf16 masters, GDN A_log/dt_bias reach the generator in bf16, so VLLMInnerGDN casts them at its kernel call on every forward (.float(), a no-op for fp32 tensors), as the trainer's GDN does. With fp32 masters this keeps [rl] generator: keep GDN A_log/dt_bias in float32 (6/7) #5691's saving.
  • Checkpoint export: export_state_dict(state_dict, *, dtype, model_parts) replaces the duplicated cast loops in both checkpointers and both scripts/checkpoint_conversion/ converters. The converters now cast before to_hf, like the in-training export.
  • Mechanical, skimmable: test updates for the removed param_dtype_override_fn argument, models/README.md bullet, reworded KDA TODO.

Alternatives considered

  • Run-level FQN regex list in the training config: puts an architecture property into every recipe, and patterns break across PP splits and renames.
  • Class attribute only: can't vary per instance (Qwen3.5 preserves one GatedRMSNorm, KDA's stays bf16).
  • Tagging nn.Parameter objects: tags are lost through to_empty, param.data = and DTensor re-wrapping.
  • Requiring fp32 masters for RL: several GDN/KDA RL recipes train with bf16 masters.
  • Keeping generator.model_dtype and upcasting preserved params to at least fp32 on the wire and in the generator: a heuristic that guesses the trainer's dtypes. Mirroring the trainer's precision makes every dtype match by construction.

FlexShard's param_dtype_overrides (an FQN map) can consume named_preserve_dtype_params directly once it lands; not wired here.

User-facing changes

Before After
Qwen3.5 / DSV4 training, fp32 masters listed params all-gathered in bf16 all-gathered and computed in fp32
Kimi K3 training, fp32 masters KDA A_log/dt_bias in bf16 fp32
bf16 masters (precision.dtype="bfloat16") unchanged unchanged (params stay bf16)
RL generator dtype generator.model_dtype (every recipe: "bfloat16") precision.param_dtype (default "bfloat16"); generator.model_dtype removed
RL generator, fp32 masters GDN A_log/dt_bias fp32, values bf16-rounded all listed params fp32 and unrounded
export_dtype="bfloat16" every float tensor bf16 listed params stay fp32
convert_to_hf.py --export_dtype bfloat16 cast after to_hf, so adapter-created tensors were cast too (DSV4 tid2eid: int64 -> fp32 in to_hf, then rounded to bf16) cast before to_hf; tid2eid stays fp32

Numerics

Deterministic, seed 42, flex attention, 2 GPUs FSDP, GB300; base = main with #5659 (+ #5776, which is bitwise identical to main).

Config Masters Result
llama3 debugmodel (no preserved params), 20 steps fp32 loss and grad_norm bitwise identical
kimi_k3 debugmodel, 20 steps bf16 bitwise identical (params stay bf16)
qwen3_5 / deepseek_v4 debugmodel fp32 change from step 1, as expected

C4 (allenai/c4) convergence, 600 steps, mean loss over each window:

Steps qwen3_5 base qwen3_5 this PR deepseek_v4 base deepseek_v4 this PR
90-100 2.4372 2.4361 2.5241 2.5236
290-300 2.0829 2.0805 2.0742 2.0712
490-500 1.9237 1.9231 1.9038 1.9006
551-600 1.9489 1.9467 1.8937 1.8909

No golden loss file covers an affected config: the only one, kimi_k3_b200.txt, uses bf16 masters.

Performance

Every FSDP group holding a preserved param now all-gathers mixed dtypes (FSDP's byte path).

  • Qwen3.5-0.8B, fp32 masters, FSDP 2, seq 4096, GB300, median tokens/s over steps 5-20, three runs each alternating on the same GPUs: base 24.1k / 24.1k / 22.3k, this PR 25.1k / 23.0k / 23.6k (run-to-run noise about 5%). Peak active memory 28.66 GiB in both.
  • DeepSeek-V4 debugmodel: 63.6k vs 63.0k tokens/s (concurrent runs on separate GPU pairs, within noise); peak memory identical.

Testing

  • CPU unit suites (checkpointer, scripts, distributed, config, models, quantization, RL): pass, except 6 failures that also fail on main on aarch64 (dist-MoE x2, LoRA, Qwen3.5 MRoPE x3).
  • Kimi K3 RL batch-invariant integration test (rl_grpo_kimi_k3_debug_batch_invariant, 4 GPUs, bf16 masters): bit_wise/logprob_diff/max = 0 at every step.
  • Qwen3.5 trainer-vs-generator bitwise parity GPU test (TestBitwiseParityQwen35DebugVarlen, fp32 masters, asserts every receive dtype equals what the trainer sends): 4 passed.
  • DeepSeek V3 RL integration test (rl_grpo_deepseek_v3_debug, 4 GPUs, fp32 masters, weight sync over Monarch/TorchStore): runs all steps. This also covers building vLLM MLA attention inside an fp32-master generator model.
  • MXFP8 Dist-MoE generator test (test_generator_dist_moe_mxfp8.py, fp32 masters, quantized tensor-subclass experts cast to bf16 on meta): passes. Since [rl] generator: keep GDN A_log/dt_bias in float32 (6/7) #5691 it had passed a SimpleNamespace without named_buffers to the shared weight-sync helper; it now passes a stand-in with the generator's buffer and preserved-param names, so the helper's receive-dtype assertion covers MXFP8 experts.
  • Extended tests: test_fsdp.py (preserved param unshards in its dtype), test_trainer.py (preserved names in preserve_dtype_keys), test_torch_checkpointing.py (export keeps a preserved fp32 param), test_bitwise_parity.py (receive dtypes).

Known issues / follow-ups

  • Not run here: the 8-GPU rl_grpo_qwen3_5_debug_tp2_batch_invariant CI config. A 4-GPU variant (trainer DP 1) is not bitwise on base or on this PR.
  • Norm weights in general (beyond Qwen3.5's GDN gated norm) are a follow-up after convergence studies.
  • RL with bf16 masters: the generator now receives GDN A_log/dt_bias in bf16, the trainer's dtype, so VLLMInnerGDN casts them each step again. That costs the 3-6 us per GDN layer per step that [rl] generator: keep GDN A_log/dt_bias in float32 (6/7) #5691 saved (Qwen3.5-27B / 35B-A3B measurements there); fp32 masters keep the saving.
  • Separate issue found while validating: VarlenInnerAttention defaults to cuDNN attention first, whose dQ backward is not deterministic under debug.deterministic=True on SM100+ (flash is). Numerics above use flex attention for that reason.

This PR was AI-assisted.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 3, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 3, 2026
@tianyu-l
tianyu-l requested a review from drisspg November 3, 2026 09:29
@tianyu-l
tianyu-l force-pushed the preserve-dtype-params branch from e00e52d to 183d731 Compare November 3, 2026 11:31
@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 7m 16s —— View job


Approve (last commit 183d731 only) -- review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- I reviewed the last commit (183d731) only, as asked, and found no correctness bug. The design is sound: the module config owns which parameters to preserve, and FSDP, export and the RL sync all read that one list. The stacked commits are reviewed in #5659 and #5776, and a maintainer still needs to review the core changes (Module, distributed/fsdp.py, checkpointer).

What this PR does. It adds Module.Config.preserve_dtype_params, a per-instance list of a module's own parameters whose precision bulk casts never lower. Three places read it through named_preserve_dtype_params(): FSDP (through upstream param_dtype_override_fn), checkpoint export (export_state_dict), and RL weight sync (preserve_dtype_keys). The RL generator now follows the trainer's precision instead of generator.model_dtype. That removes the GDN-only code from #5691: Decoder._fsdp_param_dtype_override_fn, the GDN fp32 loop, the Dist-MoE requires_grad_ loop, and the receive-dtype rewrite.

Example.

# qwen3_5, precision.dtype="float32", param_dtype="bfloat16"
GDN.Config.preserve_dtype_params == ("A_log", "dt_bias")
# FSDP override: promote_types(fp32, bf16) -> fp32
#   before: A_log unshards as bf16; gate computes exp(A_log.bf16().float())
#   after:  A_log unshards as fp32; .float() is a no-op
# RL: trainer sends A_log in fp32 (preserve_dtype_keys) and other params in bf16;
#     generator builds in fp32 and swaps non-preserved params to bf16, so the receive dtypes match
# export_dtype="bfloat16": A_log stays fp32, other float tensors become bf16

Should consider

  • torchtitan/experiments/graph_trainer/common_utils.py:595: SimpleFSDP builds MixedPrecisionPolicy without the override, so preserved params are ignored there. No graph_trainer model (llama3, deepseek_v3, qwen3, muse_glimmer) lists any today. But if qwen3_5, deepseek_v4 or kimi_k3 is added to graph_trainer, their preserved params would be rounded to bf16 without any error. A one-line if any(model.named_preserve_dtype_params()): raise ValueError(...) would make that limit explicit (rule 8).
Details
  • Necessity: the problem exists on main. FSDP rounds A_log, dt_bias and the DSV4 hc_* params to bf16, even though DSV4 creates HcHead params with dtype=torch.float32. The fix reads the upstream API (pytorch/pytorch#196626) and adds no torchtitan-side workaround.
  • RL coupling: the generator rework belongs in this PR. Without it, the generator could not receive unrounded preserved params for every model, only GDN's. Building in precision.dtype makes buffer and param dtypes match the trainer by construction. The two set_default_dtype wrappers around the vLLM Attention/MLAAttention constructors are needed because the model is now built in the master dtype. VLLMInnerGDN and VLLMInnerKDA read state dtypes from vllm_config.model_config, not the default dtype. swap_tensors keeps parameter identity, so tied weights and the preserved-identity set used by mixed_precision_policy survive.
  • Quantization raise: no in-repo recipe quantizes DSV4 Linears. MXFP8LinearConverter() with empty fqns on DSV4 would now raise at attn_sink. Before, it converted a (n_heads, 1) Linear that is never called as a linear. Raising is the right outcome.
  • Callsites: every apply_fsdp_to_decoder and apply_fsdp_to_multimodal_encoder caller passes a Module (decoder, DSV3 MTP, multimodal encoders). In the multimodal path, the decoder's policy is built after the encoders are sharded. The root group never holds encoder params, so identity matching is unaffected. No model_dtype, generator_dtype or _fsdp_param_dtype_override_fn references remain.
  • Config transforms: async TP and lm_head_fp32 copy every field, so they keep preserve_dtype_params. Dist-MoE replaces only experts.

Not verified (needs GPUs):

  • the FSDP mixed-dtype all-gather with fsdp_symm_mem_scope or CPU offload;
  • the KDA generator with fp32 masters (the Kimi K3 RL test uses bf16 masters);
  • that param_dtype_override_fn receives the parameter as it was before fully_shard, which the identity matching relies on. The CPU test_fsdp test covers this through unshard().

@tianyu-l
tianyu-l force-pushed the preserve-dtype-params branch from 183d731 to 520ca06 Compare November 3, 2026 11:40
@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 7s —— View job


Approve (re-review of the last commit, 520ca06) -- review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- I re-reviewed the last commit (520ca06, which replaces 183d731) and found no new problems. The one item from the earlier review is fixed. A maintainer still needs to review the core changes (Module, distributed/fsdp.py, checkpointer).

What changed since the last review. I couldn't fetch the old commit to diff the two, so I re-read the whole last commit. The only behavior change I found is a new guard in GraphTrainerModel.parallelize. The rest matches what the earlier review covered: Module.Config.preserve_dtype_params, mixed_precision_policy, export_state_dict, the RL generator now following precision, and preserve_dtype_keys in the weight sync.

Example.

# A graph_trainer model whose decoder includes GDN (A_log, dt_bias preserved)
GraphTrainerModel.parallelize(...)
#   183d731: SimpleFSDP silently all-gathers A_log/dt_bias in bf16
#   520ca06: ValueError("GraphTrainer's SimpleFSDP ... does not support preserve_dtype_params.")

Resolved from the earlier review

  • torchtitan/experiments/graph_trainer/model.py:44 -- SimpleFSDP ignoring preserved params now raises a ValueError, with a TODO to pass them to SimpleFSDP's mixed precision. No current graph_trainer model (llama3, qwen3, deepseek_v3, muse_glimmer) lists preserved params, so nothing breaks today.
Details
  • The guard is in the shared GraphTrainerModel mixin, before any sharding. All four graph_trainer model classes inherit from it before their Module-based model, so self.named_preserve_dtype_params() resolves for each of them.
  • I re-checked the rest of the commit at HEAD:
    • The FSDP override matches parameters by identity, and the policy is built before fully_shard at every call site (decoder, multimodal encoder, Flux).
    • export_state_dict canonicalizes FQNs the same way the trainer's _preserve_dtype_keys does.
    • The generator freezes the model, swaps non-preserved params to param_dtype with swap_tensors, and raises if vLLM's dtype differs from precision.param_dtype.
    • The quantization converter raises on a Linear that lists preserved params.
  • The earlier gate notes still hold. The problem is real on main: FSDP rounds fp32 A_log, dt_bias and the DSV4 hc_* params to bf16. The fix uses the upstream param_dtype_override_fn (pytorch/pytorch#196626), and the RL generator changes are needed for preserved params to reach the generator unrounded.

Not verified (needs GPUs): the mixed-dtype FSDP all-gather with fsdp_symm_mem_scope or CPU offload, and the KDA generator with fp32 masters.

@tianyu-l
tianyu-l force-pushed the preserve-dtype-params branch from 520ca06 to f0e794b Compare November 3, 2026 11:45
@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 16s —— View job


Approve (re-review of the last commit, f0e794b, a rebase of 520ca06 with no new problems) -- review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- I re-reviewed the last commit (f0e794b, pushed after my review of 520ca06) and found no new problems. A maintainer still needs to review the core changes (Module, distributed/fsdp.py, checkpointer).

What changed since the last review. The last commit was pushed together with the two stacked commits, so it looks like a rebase onto the updated #5659 / #5776. I couldn't fetch 520ca06 to diff against it, so I re-read the whole last commit at HEAD. Its content matches what the earlier review covered:

  • Module.Config.preserve_dtype_params and named_preserve_dtype_params()
  • mixed_precision_policy at the decoder, multimodal encoder and Flux FSDP sites
  • export_state_dict in both checkpointers and both converters
  • the RL generator following precision
  • _preserve_dtype_keys in the weight sync
  • the GraphTrainerModel.parallelize guard

Example.

# qwen3_5, precision.dtype="float32", param_dtype="bfloat16"
GDN.Config.preserve_dtype_params == ("A_log", "dt_bias")
# FSDP: param_dtype_override_fn -> promote_types(fp32, bf16) = fp32
# RL:   trainer sends A_log in fp32 (preserve_dtype_keys), other params in bf16;
#       generator builds in fp32, swaps the rest to bf16, so receive dtypes match
# export_dtype="bfloat16": A_log stays fp32
Details
  • No references to model_dtype, generator_dtype, _fsdp_param_dtype_override_fn or _model_buffer_names remain anywhere in the repo. That includes torchtitan_recipes/tests/rl/alphabet_sort.py, which this commit also updates.
  • rl/generate.py reads config.precision both for register_to_vllm and for the vLLM dtype. The wrapper raises if the two differ.
  • From the earlier review, still true at HEAD:
    • The FSDP override matches parameters by identity, and every call site builds the policy before fully_shard.
    • export_state_dict canonicalizes FQNs the same way the trainer's _preserve_dtype_keys does.
    • The quantization converter raises on a Linear that lists preserved params.
    • SimpleFSDP raises in graph_trainer.

Not verified (needs GPUs): the mixed-dtype FSDP all-gather with fsdp_symm_mem_scope or CPU offload, and the KDA generator with fp32 masters.

@tianyu-l
tianyu-l force-pushed the preserve-dtype-params branch from f0e794b to caefd10 Compare November 3, 2026 17:29
@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 18s —— View job


Approve (re-review of the last commit, caefd10: a rebase of f0e794b onto main after #5659 merged, with no new problems) -- review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- I re-reviewed the last commit (caefd10), which rebases f0e794b onto main now that #5659 has merged, and found no new problems. A maintainer still needs to review the core changes (Module, distributed/fsdp.py, checkpointer).

What changed since the last review. The PR now has two commits: #5776's (6fa943a) and this one. I couldn't fetch f0e794b to diff the two, so I re-read the whole last commit at HEAD (48 files, +375/-268). It has the same content as before:

  • Module.Config.preserve_dtype_params and named_preserve_dtype_params()
  • mixed_precision_policy at the decoder, multimodal encoder and Flux FSDP sites
  • export_state_dict in both checkpointers and both converters
  • the RL generator following precision
  • _preserve_dtype_keys in the weight sync
  • the GraphTrainerModel.parallelize guard and the quantization-converter raise

Example.

# qwen3_5, precision.dtype="float32", param_dtype="bfloat16"
GDN.Config.preserve_dtype_params == ("A_log", "dt_bias")
# FSDP: param_dtype_override_fn -> promote_types(fp32, bf16) = fp32
# RL:   trainer sends A_log in fp32 (preserve_dtype_keys), other params in bf16 (transfer_dtype);
#       generator builds in fp32, swaps the rest to bf16, so its sharded state dict matches
# export_dtype="bfloat16": A_log stays fp32
Details
  • Fit with merged #5659. #5659 sends GPU tensors straight to TorchStore with no trainer staging buffers. This commit only changes what goes into transfer_dtype (now precision.param_dtype when it differs from dtype) and preserve_dtype_keys (buffers plus preserved params). The generator's receive buffers are _create_cpu_state_dict(self.model.state_dict()), so they have the dtypes the trainer sends by construction.
  • No stale references. No references to model_dtype, generator_dtype, _fsdp_param_dtype_override_fn or _model_buffer_names remain in the repo. vllm_config.model_config.dtype is read only where expected: the vLLM Attention/MLAAttention builds, the GDN/KDA state dtypes, and the wrapper's check against precision.param_dtype.
  • Identity matching. In the generator, preserved params are skipped by the swap_tensors loop. Swapping also keeps parameter identity. So the identity set that mixed_precision_policy builds before fully_shard still matches.

Not verified (needs GPUs): the mixed-dtype FSDP all-gather with fsdp_symm_mem_scope or CPU offload, and the KDA generator with fp32 masters.

@tianyu-l tianyu-l added the ciflow/b200 Trigger B200 CI label Nov 3, 2026
@tianyu-l
tianyu-l force-pushed the preserve-dtype-params branch from caefd10 to 0d9f5ad Compare November 3, 2026 18:41
@tianyu-l
tianyu-l requested a review from weifengpy November 3, 2026 18:49
@tianyu-l
tianyu-l force-pushed the preserve-dtype-params branch from 0d9f5ad to f8a364c Compare November 3, 2026 19:18
@tianyu-l
tianyu-l changed the base branch from main to precision-config November 3, 2026 19:18
@tianyu-l
tianyu-l added this pull request to stack #5780 November 3, 2026 19:18
@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 5m 26s —— View job


Approve (full review of f8a364c against precision-config, no correctness issues found; a maintainer still needs to review the core changes) -- review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- I fully reviewed this PR's commit (f8a364c) against its base precision-config (#5776) and found no correctness bug. The dtype rule now lives in one place, so FSDP, checkpoint export and the RL weight sync can't disagree about it. A maintainer still needs to review the core changes (Module, distributed/fsdp.py, checkpointer).

What this PR does. It adds Module.Config.preserve_dtype_params, a per-instance list of a module's own parameters that bulk casts never lower in precision. named_preserve_dtype_params() exposes that list to three consumers:

  • FSDP, through upstream param_dtype_override_fn
  • export_state_dict, which both checkpointers and both converters now use
  • the RL trainer's preserve_dtype_keys

The RL generator now follows the trainer's precision, and generator.model_dtype is removed. That deletes the GDN-only workarounds from #5691 and #5652: Decoder._fsdp_param_dtype_override_fn, the GDN fp32 loop, the Dist-MoE requires_grad_ loop, and the receive-dtype and staging-tensor casts.

Example.

# qwen3_5, precision.dtype="float32", param_dtype="bfloat16"
GDN.Config.preserve_dtype_params == ("A_log", "dt_bias")
# trainer FSDP: promote_types(fp32, bf16) -> A_log all-gathered in fp32
#   (before: bf16, and the gate computed exp(A_log.bf16().float()))
# RL: the trainer sends A_log in fp32 (preserve_dtype_keys) and the rest in bf16 (transfer_dtype).
#     The generator builds in fp32 and swap_tensors the rest to bf16, so the sharded
#     state dict and the gpu_fetch targets have the dtypes that are sent.
# export_dtype="bfloat16": A_log stays fp32, every other float tensor is bf16
Details
  • Gate. The problem exists on main: FSDP rounds fp32 A_log, dt_bias and the DSV4 hc_* params to bf16, including HcHead's, which are created with dtype=torch.float32. The fix uses the upstream API (pytorch/pytorch#196626), and the module config owns the property, so there is no FQN regex in recipes. Trainer and generator share the same field (no one-sided design).
  • Callsites. The only MixedPrecisionPolicy( constructions left are in Flux's HF T5/CLIP encoders (they hold no TorchTitan modules), the transformers backend (sets preserve_dtype_params = ()) and graph_trainer (now raises). DSV3/DSV4 MTP goes through apply_fsdp_to_decoder. MTP layers are attached as model.mtp_layers, so named_modules() reaches them. apply_fsdp_to_decoder builds one policy before any fully_shard, and after TP, so the identity set holds the right parameters. No model_dtype, generator_dtype or _fsdp_param_dtype_override_fn references remain anywhere.
  • Explicit-dtype params. The only parameters created with an explicit dtype are DSV4 HcHead.hc_base/hc_scale, and they are preserved. So with bf16 masters (transfer_dtype=None), no non-preserved parameter is sent in a dtype other than the one the generator swaps to.
  • Generator build in precision.dtype. The trainer also builds under set_default_dtype(precision.dtype) (training_engine.py:375), so buffer dtypes match by construction. The RoPE cache is computed with .float() either way. GatedRMSNorm casts its output back to the input dtype, so the fp32 Qwen3.5 gated-norm weight doesn't spread fp32 activations. Only two vLLM layers are built inside the model, Attention and MLAAttention, and both are now wrapped in set_default_dtype(model_config.dtype).
  • Config transforms. LoRA copies every dataclass field, so it keeps the list. The MXFP8/Float8 rebuild drops it, and the new _validate_quantizable_linear raise covers that.
  • New since caefd10. The PR is rebased onto #5652: gpu_fetch fills sharded params directly, and the staging-tensor cast is gone. VLLMInnerGDN now calls .float() at its kernel call (a no-op with fp32 masters). VLLMInnerKDA already did, at kda.py:240. Both are fine under CUDA graphs.

Not verified (needs GPUs): the mixed-dtype FSDP all-gather with fsdp_symm_mem_scope or CPU offload, and the KDA generator with fp32 masters.

@tianyu-l
tianyu-l force-pushed the preserve-dtype-params branch from f8a364c to d88ea35 Compare November 3, 2026 21:44
@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 51s —— View job


Approve (re-review of the last commit, d88ea35: no new problems; noted the open router-gate question) -- review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- I re-reviewed the last commit (d88ea35, pushed after my review of f8a364c) and found no new problems. A maintainer still needs to review the core changes (Module, distributed/fsdp.py, checkpointer).

What changed since the last review. I couldn't fetch f8a364c to diff against it, so I re-read the whole commit against precision-config (50 files, +381/-296). Its content matches what the last review covered:

  • Module.Config.preserve_dtype_params, validated at build
  • mixed_precision_policy at the decoder, multimodal encoder and Flux FSDP sites
  • export_state_dict in both checkpointers and both converters, which now cast before to_hf
  • the RL generator follows precision: it builds in precision.dtype, swap_tensors the non-preserved params to param_dtype, and raises if vLLM's dtype differs
  • gpu_fetch fills sharded params directly, and VLLMInnerGDN calls .float() at the kernel
  • the raises in graph_trainer and in the quantization converter

Example.

# qwen3_5, precision.dtype="float32", param_dtype="bfloat16"
GDN.Config.preserve_dtype_params == ("A_log", "dt_bias")
# FSDP:   promote_types(fp32, bf16) -> A_log all-gathered in fp32
# RL:     the trainer sends A_log in fp32 (preserve_dtype_keys) and the rest in bf16;
#         the generator's sharded state dict has the same dtypes
# export: export_dtype="bfloat16" keeps A_log in fp32

Questions

  • @weifengpy asked whether the MoE router gate should be fp32 too. That question is still open. One thing that bears on it: every in-repo router gate is a HiMidLoLinear (models/common/config_utils.py:447, and the gpt_oss, deepseek_v3/v4 and kimi_k3 flavors). By design, that layer takes a bf16 weight, accumulates in fp32 and returns fp32 output. If the gate weight is listed in preserve_dtype_params, it stays fp32, and HiMidLoLinear drops to its slower fp32-matmul fallback (its docstring, case (b)). Also, _validate_quantizable_linear raises on a preserved Linear, so MXFP8/Float8 with empty fqns would start raising at the gate. Both points should be part of that follow-up's convergence and perf study.
Details
  • Converters. convert_to_hf.py builds the model in fp32 on CPU, and DCP loads into those fp32 tensors. So preserved params stay fp32 whatever dtype the checkpoint stores, and export_state_dict keeps them fp32 for a bf16 export. One small difference: the old converter skipped the cast when export_dtype was fp32, and the new one always casts. The model state dict here is already fp32, so this changes nothing.
  • No stale references. No references to model_dtype, generator_dtype, _fsdp_param_dtype_override_fn, _model_buffer_names or self._model_dtype remain.

Not verified (needs GPUs): the mixed-dtype FSDP all-gather with fsdp_symm_mem_scope or CPU offload, and the KDA generator with fp32 masters.

@tianyu-l
tianyu-l marked this pull request as ready for review November 3, 2026 23:04
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 3, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 3, 2026 23:04
Base automatically changed from precision-config to main November 4, 2026 00:21
@tianyu-l
tianyu-l requested a review from d4l3k as a code owner November 4, 2026 00:21
tianyu-l added a commit that referenced this pull request Nov 4, 2026
…oad into ParallelismConfig (#5776)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

Apparently not only trainer cares about precision; generator also cares.
This PR moves it out from `TrainingConfig` as a standalone config, owned
by core trainer and RL controller, preparing for the next PR.

## Why
The model's dtypes (`training.dtype`, `training.mixed_precision_param`,
`training.mixed_precision_reduce`) live on `TrainingConfig`, owned by
`TrainingEngine.Config`. In RL they describe the model that both the
trainer and the generators run, but only the trainer can see them:
- The generator builds its model with its own `generator.model_dtype`
and fabricates a `TrainingConfig()` just to call
`model.parallelize(training=...)`.
- `model.parallelize` takes the whole `TrainingConfig`, but reads only
those three fields plus `enable_cpu_offload`.

This PR is a mechanical move. #5774 (stacked on top) then makes the
generator mirror the trainer's precision from this one config and
deletes `generator.model_dtype`.

**Example.**
```python
# before
config.training.dtype = "float32"
config.training.mixed_precision_param = "bfloat16"
config.training.enable_cpu_offload = True
model.parallelize(parallelism_context=..., training=config.training, parallelism=..., ...)

# after
config.precision.dtype = "float32"          # Trainer.Config.precision / Controller.Config.precision
config.precision.param_dtype = "bfloat16"
config.parallelism.fsdp_enable_cpu_offloading = True
model.parallelize(parallelism_context=..., precision=config.precision, parallelism=..., ...)
```

## What changed
- `PrecisionConfig(dtype, param_dtype, reduce_dtype)` in
`torchtitan/config/configs.py`. `param_dtype`/`reduce_dtype` match
FSDP's `MixedPrecisionPolicy` names.
- Ownership: core `Trainer.Config.precision` and RL
`Controller.Config.precision`, not `TrainingEngine.Config`.
`TrainingEngine` receives it as a constructor argument, like
`model_config`. In RL the controller passes the same object to the
trainer (and, in #5774, to the generators).
- `training.enable_cpu_offload` ->
`parallelism.fsdp_enable_cpu_offloading`, next to the other `fsdp_*`
options, so `model.parallelize` / `_apply_fsdp` take `precision=` and no
longer need `training`.
- The Dist-MoE `param_dtype == "bfloat16"` check moves from
`TrainingEngine.Config.__post_init__` to `Trainer.Config` and
`Controller.Config`, where `precision` is visible (two 5-line copies,
both at config time).
- GraphTrainer (experiment): its models read the token budget in
`parallelize`, so `GraphTrainingEngine` passes `training` there through
its existing kwargs hook.
- Mechanical, skimmable: every `parallelize`/`_apply_fsdp`/`pipeline`
signature, recipes, tests, docs (`BF16_OPTIMIZER_STATES.md`,
`dist_moe/README.md`, `BITWISE_PARITY.md`, `numerics_debugging` skill).

## Alternatives considered
- Keep the fields in `TrainingConfig` and have the RL controller forward
them to the generator: the generator would read the trainer's config,
and `parallelize` would still take the whole `TrainingConfig`.
- Put precision on the model config: duplicated on `trainer.model` and
`generator.model` with an equality check, and dtype is a per-run choice,
not architecture.

## User-facing changes
| Before | After |
| --- | --- |
| `training.dtype` | `precision.dtype` |
| `training.mixed_precision_param` | `precision.param_dtype` |
| `training.mixed_precision_reduce` | `precision.reduce_dtype` |
| `training.enable_cpu_offload` |
`parallelism.fsdp_enable_cpu_offloading` |
| RL: `trainer.training.dtype` | `precision.dtype` (on
`Controller.Config`) |

## Numerics
No computation change. Loss and grad_norm bitwise identical to main
(01586df), 20 steps, seed 42, deterministic, flex attention, 2 GPUs,
GB300, read from TensorBoard:

| Config | Result |
| --- | --- |
| llama3 debugmodel, FSDP 2 (fp32 masters) | bitwise identical |
| llama3 debugmodel, FSDP 2, `reduce_dtype="bfloat16"` | bitwise
identical |
| kimi_k3 debugmodel, FSDP 2 (bf16 masters, `dtype="bfloat16"`) |
bitwise identical |

PP, `param_dtype="float32"` and FSDP CPU offload configs could not run
on this host for main or this PR (a torch nightly pipelining API
mismatch, an fp32 backward kernel limit, and a hang in CPU offload), so
they rely on CI.

## Testing
- CPU unit suites (`tests/unit_tests/cpu`, `tests/rl/unit_tests/cpu`,
graph_trainer and torchft tests touched here): same results as main. The
remaining failures also fail on main on this aarch64 host (LoRA, Qwen3.5
MRoPE x3, graph_trainer Dist-MoE recipe tests, autoparallel not
installed).
- `test_rl_dist_moe_recipe.py` now also covers the RL
`Controller.Config` copy of the Dist-MoE check, the only guard for RL
trainers; the core copy stays covered by
`test_runtime_config_requires_bfloat16_unsharded_parameters`.
`test_cpu_offload_requires_distinct_dp_shard_seeds` covers the renamed
offload field.

- `test_generator_dist_moe_mxfp8.py` (CI `rl-b200`) has failed on main
since #5691: its fake trainer model is a `SimpleNamespace` without the
`named_buffers` the weight-sync helper now reads. This PR gives the fake
`named_buffers` so `rl-b200` is green (test-only).

This PR was AI-assisted.
… mixed-precision casts

Add Module.Config.preserve_dtype_params: parameters that bulk casts never
lower in precision. FSDP mixed precision (via param_dtype_override_fn) and
checkpoint export keep the wider of the parameter's own dtype and the target;
the RL weight sync sends them in their own dtype.

The RL generator now mirrors the trainer's Controller.Config.precision instead
of generator.model_dtype (removed): it builds the model in precision.dtype,
holds the other parameters in precision.param_dtype, and computes in it.

Defaults on GDN/KDA (A_log, dt_bias), DeepSeek-V4 HcPre/HcHead (hc_*) and
Compressor (ape); flavors set Qwen3.5's GDN gated norm and DeepSeek-V4's
attn_sink. Removes Decoder._fsdp_param_dtype_override_fn.

Stacked on #5659 and the PrecisionConfig PR.
@tianyu-l
tianyu-l force-pushed the preserve-dtype-params branch from d88ea35 to a1fb91f Compare November 4, 2026 00:22
@tianyu-l
tianyu-l merged commit a3e458c into main Nov 4, 2026
@tianyu-l
tianyu-l deleted the preserve-dtype-params branch November 4, 2026 00:25
tianyu-l added a commit that referenced this pull request Nov 4, 2026
Stacked on #5774, which is stacked on #5776 (GitHub stack: this PR's
base is #5774's branch).

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

Right now we have both `model.max_context_length` and
`training.max_context_length`. The latter is redundant. This PR
consolidates them.

## Why
The context length is set twice: once on the model config
(`build_model_config(..., seq_len=...)`) and once as
`training.max_context_length`. `validate_model_training_config` then
requires the two to be equal, so every recipe repeats the model's value:

```python
model_config = build_model_config("debugmodel", seq_len=2048, parallelism=parallelism)
Trainer.Config(
    model=model_config,
    training=TrainingConfig(
        max_context_length=model_config.max_context_length,  # must equal the model's
        ...
    ),
)
```

The model owns its context length: it sizes the RoPE cache and attention
metadata, and RL serves it with vLLM `max_model_len =
model.max_context_length`. A second copy in `TrainingConfig` adds
nothing but a way to get it wrong.

## What changed
- `max_context_length: int` is declared on `BaseModel.Config` (it was on
`Decoder.Config`). `TrainingConfig.max_context_length` and the equality
check in `validate_model_training_config` are deleted.
- The trainer, training engine, validator, RL controller (batcher and SP
divisibility check), torchft and GraphTrainer read
`model.max_context_length`.
- `preprocess_inputs` no longer takes `max_context_length`: the decoder
reads `self.config.max_context_length` when it builds attention
metadata. The engine, validator and GraphTrainer stop passing it.
- Flux: `MODEL_FLAVORS` entries become `(factory, default_len)`, like
the decoders, and `build_model_config` takes `seq_len`. The defaults
(768 / 512 / 512) are the `_flux_seq_len(img_size, t5_len)` of the
shipped recipes, which still pass it explicitly.
- HF backend (experiment): `load_hf_config` also sets
`max_context_length`; its `max_seq_len` (aliased to HF
`max_position_embeddings`) is unchanged.
- Two RL recipes set different model and training lengths, so they
already failed at RL trainer startup on main (the equality check). They
now take the length the deleted training value recorded, and their token
budgets are multiples of it:
- `search_r1.rl_grpo_muse_glimmer_30b_search_r1`: the model is built
with `seq_len=4096` (it defaulted to 16384; training was 4096).
- `alphabet_sort.rl_grpo_qwen3_6_27b_varlen_perf`:
`num_tokens_per_microbatch_per_dp_rank = seq_len` (65536). Its 2048 came
from the 9B base recipe, while the recipe builds a 65536-length model.
- Mechanical, skimmable: `max_context_length=` removed from every
`TrainingConfig(...)` in recipes and tests;
`config.training.max_context_length` reads become
`config.model.max_context_length`.

## User-facing changes
| Before | After |
| --- | --- |
| `training.max_context_length` | removed; set the model length with
`build_model_config(..., seq_len=...)` and read
`model.max_context_length` |
| RL: `trainer.training.max_context_length` |
`trainer.model.max_context_length` |
| `model.preprocess_inputs(..., max_context_length=...)` | argument
removed |
| Flux `build_model_config(flavor, parallelism=...)` | also takes
`seq_len` (defaults per flavor) |

## Numerics
No computation change: every value the training path reads is the same
number as before. I built every zero-argument recipe in
`torchtitan_recipes` (220) on the base commit and on this branch:
`model.max_context_length` here equals the old
`training.max_context_length` for all of them except the two RL recipes
above, which could not run on main.

## Testing
- CPU suites (`tests/unit_tests/cpu`, `tests/rl/unit_tests/cpu`,
GraphTrainer, torchft and HF-backend tests): same results as the base
commit. The remaining failures also fail there on this aarch64 host
(LoRA, Qwen3.5 MRoPE x3).
- Tests that asserted the old field or kwarg are updated; the
`TrainingConfig(max_context_length=0)` validation case is deleted with
the field. No new tests: the recipe build check above covers the move.

This PR was AI-assisted.
tianyu-l added a commit that referenced this pull request Nov 4, 2026
)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why
GPU unit tests have failed on main since #5774 (`a3e458c73`).
`apply_fsdp_to_multimodal_encoder` and `apply_fsdp_to_decoder` now build
the mixed-precision policy from `Module.named_preserve_dtype_params()`.
`tests/unit_tests/gpu/distributed/test_fsdp_cpu_offload.py` passes plain
`nn.Module` fakes, so all three `TestVisionEncoderCPUOffload` tests
fail:

```
AttributeError: '_VisionEncoder' object has no attribute 'named_preserve_dtype_params'
```

The real encoders and decoders are torchtitan `Module`s (the helpers'
declared type), so the fix belongs in the test.

## What changed
- `_VisionEncoder`, `_Block` and `_TinyVLM` in the test subclass
`torchtitan.models.base.module.Module` instead of `nn.Module`, like
other test fakes (`test_aux_loss.py`, `test_remat_all_to_all.py`).
Test-only.

## Testing
- `pytest tests/unit_tests/gpu/distributed/test_fsdp_cpu_offload.py` on
2 GPUs: 6 passed (3 failed on main).

This PR was AI-assisted.
tianyu-l added a commit that referenced this pull request Nov 4, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why
The Real PG integration suite (`8 GPU Integration (Real PG - full suite
- features)`) and the ROCm integration suite have failed the `sft` loss
check on main since #5757 (`899480301`; `a87db08ea` before it passed):

```
[sft] AssertionError: 7.889825820922852 != 7.887711524963379 : loss mismatch at step 1   # A10G
[sft] AssertionError: 7.890093803405762 != 7.887524604797363 : loss mismatch at step 1   # MI350X
```

#5757 renders `bos_token`/`eos_token` in Hugging Face chat templates, an
intended change to the SFT token stream. It regenerated
`tests/assets/losses/fake_pg/a10g/sft.txt` but not the real-PG A10G and
MI350X goldens.

## What changed
- `tests/assets/losses/real_pg/a10g/sft.txt` and
`tests/assets/losses/real_pg/mi350x/sft.txt`: steps 1-10 regenerated;
headers unchanged.

## Numerics
The new values are the full-precision TensorBoard metrics of the failing
main runs' baseline training (the same values `loss_compare.py
--export-result` writes), read with `scripts/loss_compare.py`'s own
extraction from the uploaded `integration-8gpu-features-outputs`
artifacts:
- A10G: run 41746280593 (`e6ca6d861`). Step 1 matches the log's baseline
(7.889825820922852, grad_norm 4.189799785614014).
- MI350X: the ROCm run on `73c4ebdac`. Step 1 matches the log's baseline
(7.890093803405762, grad_norm 4.189815998077393).

The commits between #5757 and those runs (#5572, #5787, #5776, #5774,
#5779, #5741, #5786) do not change SFT numerics.

## Testing
- CI: Real PG (`ciflow/real-pg`) and ROCm (`ciflow/rocm`) integration
suites.
- A manual `export_results` run of the integration workflow for `sft` on
main (run 41760303504) exported a real-PG A10G golden identical to this
one.
- `Multi-GPU Unit Tests` fails here with the `_VisionEncoder ...
named_preserve_dtype_params` error that is also on main; #5795 fixes it.

This PR was AI-assisted.
submartingales pushed a commit to botcanlearn/torchtitan-npu-upstream that referenced this pull request Nov 19, 2026
Co-authored-by: mystri<[email protected]>



# message auto-generated for no-merge-commit merge:
!1290 merge refactor/dsv4-cleanup-precision into dev_0.4.0

[refactor] 统一 DeepSeek-V4 主干与 MTP 参数精度策略

Created-by: mystri
Commit-by: mystri
Merged-by: cann-robot
Description: ## 描述

删除 DeepSeek-V4 的全局 FQN 精度列表和复制的 MTP 分片流程,改由模块声明参数精度,通过共享 decoder FSDP 入口读取,并复用原生 MTP helper。共享部分回移上游 [#5774](pytorch/torchtitan#5774) 的运行期机制,保留显式 callback 优先级、V4.1 使用方和既有 Config 类型。

### 旧精度设置如何由新 API 复现

旧 V4 默认配置是 FP32 主参数、BF16 默认参数计算、FP32 梯度归约:

```python
training.dtype = "float32"
training.mixed_precision_param = "bfloat16"
training.mixed_precision_reduce = "float32"
```

旧 `_dsv4_param_dtypes()` 对以下参数请求 FP32 override;新实现将相同选择放到直接拥有参数的模块上,覆盖主干、MTP 和根模块:

| 保护对象 | 模块自身的 `_preserve_dtype_params` |
| --- | --- |
| `HcPre` / `HcHead` | `("hc_fn", "hc_base", "hc_scale")` |
| compressor APE,包括 `compressor_128` 和 indexer compressor | `("ape",)` |
| attention sink | 原生 `Linear` 上为 `("weight",)`;直接参数布局在 attention 上声明 `("attn_sink",)` |
| router 及其子模块 | 各模块自身的全部参数名,保留旧策略递归选择 router 的范围 |

共享 policy 对已声明参数使用 `promote_types(parameter.dtype, param_dtype)`。这些参数原本存为 FP32、默认计算为 BF16 时,结果仍为 FP32;其余参数按 BF16 计算,主参数存储、optimizer 的主参数 dtype 和配置的归约 dtype 均不改写。decoder 的 `cast_forward_inputs=False` 保持不变:这里保留的是 FSDP all-gather 及前反向使用的参数精度,不代表所有 activation 或算子均改为 FP32。

声明只含模块自身参数名,不含全局 FQN;共享入口递归读取声明,原生 MTP 复用同一 decoder FSDP 路径。当前 0.4.0 回移使用运行期 `_preserve_dtype_params`,不新增上游完整 `Module.Config.preserve_dtype_params` 配置字段。

「保留」不会把 BF16 存储强制改成 FP32。受保护参数与默认计算 dtype 都为 BF16 时,旧 FP32 override 请求本就被原生 policy 拒绝;V4 继续明确拒绝该组合,通用 preserve 语义保持不变。以上是已支持配置的策略映射说明,完整训练是否比特一致仍按下方数值验收记录判定。

## 类型

- [ ] Bug 修复
- [ ] 新功能
- [x] 重构(即不是新增功能,也不是修改bug的代码变动)
- [ ] 构建过程或辅助工具的变动
- [ ] 文档内容更新

## Checklist:

- [x] 我的代码遵循这个项目的代码风格
- [x] 我已经自己测试过我的代码
- [x] 我已经更新了相应的文档
- [x] 我已经在标题中正确使用了类型标签(例如:`feat`, `fix`, `refactor`, `docs`, `test`)

## 如何测试

当前基线 `562c53cf`,候选 `2bacc466`,目标分支 `dev_0.4.0`。合并保留目标分支的原生注意力配置、GraphTrainer EP overlap 和本 PR 的 FSDP 精度声明。

本地完整 `pre-commit run --all-files` 与 **41 项相关 CPU 单测通过**。覆盖声明与 FSDP 前反向、原生 attention、GraphTrainer 并行化和模型 recipe。

```bash
TORCH_DEVICE_BACKEND_AUTOLOAD=0 OMP_NUM_THREADS=1 python -m pytest -v --tb=short \
  tests/unit_tests/models/common/test_fsdp.py \
  tests/unit_tests/models/deepseek_v4/{test_parallelize_policy,test_graph_trainer_parallelize}.py \
  tests/unit_tests/models/deepseek_v4_1/test_parallelize_policy.py \
  tests/unit_tests/override/deepseek_v4/test_native_sparse_attn.py \
  tests/unit_tests/recipes/test_deepseek_v4_examples.py
```

[当前提交 CI #2858](https://gitcode.com/cann/torchtitan-npu/actions/runs/2e50c827442f47a6b3ac183d1cfbcefc)。旧基线与 `2f25cb09` 的 CPU、CI 和历史数值材料见[验证归档](https://raw.gitcode.com/cann/torchtitan-npu/attachment/uploads/759dff90-b638-4102-aaa8-25bcef44451e/pr1290-2f25cb09-verification.zip)。测试精简保留 12 项核心策略用例,较精简前净删 80 行。

### 精度和性能验证结果

两组均测试 `562c53cf` → `2bacc466`,基线和候选各完成 100 步且退出码为 0。两侧使用同一 checkpoint、输入顺序、初始随机状态和确定性设置。逐 rank 比较未舍入记录的比特,并核对 TensorBoard 标量。
PR 随后追加 `2d2bd56`,只修改 `AGENTS.md`。43 层候选的训练进程退出码为 0,8 个 rank 正常结束。外层脚本因检测到文档提交将退出码记为 1,原始退出记录和独立核对均在验证包内。

| 场景 | loss | grad_norm | 额外状态检查 |
| --- | --- | --- | --- |
| 43 层、8 卡、16 专家 | **90/100**,第 91 步首次不同(最大绝对差 `0.00015807152`) | **89/100**,第 90 步首次不同(最大绝对差 `0.0085924864`) | 采样的模型参数/梯度与完整本地 indexer 状态未通过,decoder hidden-state 采样未通过,整体严格比较未通过 |
| 4 主干层+1 MTP 层、2 卡、4 专家 | **100/100 步比特一致** | **100/100 步比特一致** | 采集的完整本地参数、梯度及优化器状态通过,采集的词表 logits通过,整体严格比较通过 |

环境为 TorchTitan 0.4.0、Torch 2.15、Torch NPU 2.15.0.dev20261105、CANN 9.3,FP32 主参数、BF16 默认计算、FP32 归约,关闭 HF32。43 层使用 FSDP8/EP8、seq2048、GA2,在 8–15 卡使用 16 MiB HCCL 缓冲区。MTP 使用 FSDP2/EP2、seq256、GA1,在 0–1 卡使用 64 MiB。

43 层首次尝试在 0–7 卡使用 64 MiB 缓冲区,候选第 2 步反向显存不足。完整对照采用上述 8–15 卡配置重跑两侧。性能未单独测量。

逐步指标、运行命令、源码版本、退出记录、完整比较报告和曲线见[验证包](https://raw.gitcode.com/cann/torchtitan-npu/attachment/uploads/84eb551a-6460-4ce9-9817-8cf24889d66b/numerical-evidence.zip)(SHA-256 `4e48288befbb92e8ab4b194fc3a6283238397502ae90967db90b708bfb5afa17`)。

历史 `6e3c9320` → `fccf7d1a` 的 43 层记录中,grad_norm 第 68 步、loss 第 69 步首次不一致。同一历史基线复跑的逐步标量一致,严格状态仍有 indexer 差异。[历史比较记录](https://raw.gitcode.com/cann/torchtitan-npu/attachment/uploads/0862f1f9-0a08-4b83-b90d-ac0090697755/numerical-evidence.zip)。

## 其他信息

不回移完整 Config/build、checkpoint 导出或 RL 精度传播,不改变 GraphTrainer SimpleFSDP。普通 decoder 和 MTP 共用原生分片流程;本 PR 为 #1257 的独立精度功能拆分。



See merge request: cann/torchtitan-npu!1290
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants