Repository navigation
[models][fsdp] preserve_dtype_params: keep selected parameters out of mixed-precision casts - #5774
Conversation
e00e52d to
183d731
Compare
|
@claude review |
There was a problem hiding this comment.
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 bf16Should consider
torchtitan/experiments/graph_trainer/common_utils.py:595: SimpleFSDP buildsMixedPrecisionPolicywithout 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-lineif 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 createsHcHeadparams withdtype=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.dtypemakes buffer and param dtypes match the trainer by construction. The twoset_default_dtypewrappers around the vLLMAttention/MLAAttentionconstructors are needed because the model is now built in the master dtype.VLLMInnerGDNandVLLMInnerKDAread state dtypes fromvllm_config.model_config, not the default dtype.swap_tensorskeeps parameter identity, so tied weights and the preserved-identity set used bymixed_precision_policysurvive. - Quantization raise: no in-repo recipe quantizes DSV4 Linears.
MXFP8LinearConverter()with emptyfqnson DSV4 would now raise atattn_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_decoderandapply_fsdp_to_multimodal_encodercaller passes aModule(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. Nomodel_dtype,generator_dtypeor_fsdp_param_dtype_override_fnreferences remain. - Config transforms: async TP and
lm_head_fp32copy every field, so they keeppreserve_dtype_params. Dist-MoE replaces only experts.
Not verified (needs GPUs):
- the FSDP mixed-dtype all-gather with
fsdp_symm_mem_scopeor CPU offload; - the KDA generator with fp32 masters (the Kimi K3 RL test uses bf16 masters);
- that
param_dtype_override_fnreceives the parameter as it was beforefully_shard, which the identity matching relies on. The CPUtest_fsdptest covers this throughunshard().
183d731 to
520ca06
Compare
|
@claude review again |
There was a problem hiding this comment.
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 aValueError, 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
GraphTrainerModelmixin, before any sharding. All four graph_trainer model classes inherit from it before theirModule-based model, soself.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_shardat every call site (decoder, multimodal encoder, Flux). export_state_dictcanonicalizes FQNs the same way the trainer's_preserve_dtype_keysdoes.- The generator freezes the model, swaps non-preserved params to
param_dtypewithswap_tensors, and raises if vLLM's dtype differs fromprecision.param_dtype. - The quantization converter raises on a
Linearthat lists preserved params.
- The FSDP override matches parameters by identity, and the policy is built before
- The earlier gate notes still hold. The problem is real on main: FSDP rounds fp32
A_log,dt_biasand the DSV4hc_*params to bf16. The fix uses the upstreamparam_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.
520ca06 to
f0e794b
Compare
|
@claude review again |
There was a problem hiding this comment.
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_paramsandnamed_preserve_dtype_params()mixed_precision_policyat the decoder, multimodal encoder and Flux FSDP sitesexport_state_dictin both checkpointers and both converters- the RL generator following
precision _preserve_dtype_keysin the weight sync- the
GraphTrainerModel.parallelizeguard
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 fp32Details
- No references to
model_dtype,generator_dtype,_fsdp_param_dtype_override_fnor_model_buffer_namesremain anywhere in the repo. That includestorchtitan_recipes/tests/rl/alphabet_sort.py, which this commit also updates. rl/generate.pyreadsconfig.precisionboth forregister_to_vllmand for the vLLMdtype. 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_dictcanonicalizes FQNs the same way the trainer's_preserve_dtype_keysdoes.- The quantization converter raises on a
Linearthat lists preserved params. - SimpleFSDP raises in graph_trainer.
- The FSDP override matches parameters by identity, and every call site builds the policy before
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.
f0e794b to
caefd10
Compare
|
@claude review again |
There was a problem hiding this comment.
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_paramsandnamed_preserve_dtype_params()mixed_precision_policyat the decoder, multimodal encoder and Flux FSDP sitesexport_state_dictin both checkpointers and both converters- the RL generator following
precision _preserve_dtype_keysin the weight sync- the
GraphTrainerModel.parallelizeguard 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 fp32Details
- 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(nowprecision.param_dtypewhen it differs fromdtype) andpreserve_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_fnor_model_buffer_namesremain in the repo.vllm_config.model_config.dtypeis read only where expected: the vLLMAttention/MLAAttentionbuilds, the GDN/KDA state dtypes, and the wrapper's check againstprecision.param_dtype. - Identity matching. In the generator, preserved params are skipped by the
swap_tensorsloop. Swapping also keeps parameter identity. So the identity set thatmixed_precision_policybuilds beforefully_shardstill 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.
caefd10 to
0d9f5ad
Compare
0d9f5ad to
f8a364c
Compare
|
@claude review |
There was a problem hiding this comment.
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 bf16Details
- Gate. The problem exists on main: FSDP rounds fp32
A_log,dt_biasand the DSV4hc_*params to bf16, includingHcHead's, which are created withdtype=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 (setspreserve_dtype_params = ()) and graph_trainer (now raises). DSV3/DSV4 MTP goes throughapply_fsdp_to_decoder. MTP layers are attached asmodel.mtp_layers, sonamed_modules()reaches them.apply_fsdp_to_decoderbuilds one policy before anyfully_shard, and after TP, so the identity set holds the right parameters. Nomodel_dtype,generator_dtypeor_fsdp_param_dtype_override_fnreferences 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 underset_default_dtype(precision.dtype)(training_engine.py:375), so buffer dtypes match by construction. The RoPE cache is computed with.float()either way.GatedRMSNormcasts 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,AttentionandMLAAttention, and both are now wrapped inset_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_linearraise covers that. - New since caefd10. The PR is rebased onto #5652:
gpu_fetchfills sharded params directly, and the staging-tensor cast is gone.VLLMInnerGDNnow calls.float()at its kernel call (a no-op with fp32 masters).VLLMInnerKDAalready did, atkda.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.
f8a364c to
d88ea35
Compare
|
@claude review again |
There was a problem hiding this comment.
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 buildmixed_precision_policyat the decoder, multimodal encoder and Flux FSDP sitesexport_state_dictin both checkpointers and both converters, which now cast beforeto_hf- the RL generator follows
precision: it builds inprecision.dtype,swap_tensorsthe non-preserved params toparam_dtype, and raises if vLLM's dtype differs gpu_fetchfills sharded params directly, andVLLMInnerGDNcalls.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 fp32Questions
- @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 inpreserve_dtype_params, it stays fp32, andHiMidLoLineardrops to its slower fp32-matmul fallback (its docstring, case (b)). Also,_validate_quantizable_linearraises on a preservedLinear, so MXFP8/Float8 with emptyfqnswould start raising at the gate. Both points should be part of that follow-up's convergence and perf study.
Details
- Converters.
convert_to_hf.pybuilds the model in fp32 on CPU, and DCP loads into those fp32 tensors. So preserved params stay fp32 whatever dtype the checkpoint stores, andexport_state_dictkeeps them fp32 for a bf16 export. One small difference: the old converter skipped the cast whenexport_dtypewas 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_namesorself._model_dtyperemain.
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.
…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.
d88ea35 to
a1fb91f
Compare
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.
) ## 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.
## 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.
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
Stacked on #5776 (GitHub stack: this PR's base is #5776's branch).
Summary (human-written)
pytorch/pytorch#196626 added
MixedPrecisionPolicy.param_dtype_override_fnso FSDP can leave chosen parameters alone.E.g., for GDN / KDA, the params
A_loganddt_biasshould 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:linear_attn.A_log, GDN gated normlinear_attn.norm.weightA_log,dt_biashc_*_fn/base/scale,attn_sink, compressorapeOn main the kernels then upcast bf16-rounded values (
gdn.py:480,kda.py:128,mhc.py:112). DSV4 even creates its head hc params withdtype=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 addedMixedPrecisionPolicy.param_dtype_override_fnso FSDP can leave chosen parameters alone.Example.
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, likenamed_parameters().A_log,dt_bias), DSV4HcPre/HcHead(hc_*), DSV4Compressor(ape). Flavors set it for single instances of generic modules: Qwen3.5's GDNGatedRMSNorm, DSV4'sattn_sinkLinear.mixed_precision_policy(module, ...)builds the policy withparam_dtype_override_fn(the wider of the parameter's dtype andparam_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, soGraphTrainerModel.parallelizeraises if a model lists preserved params (none does today). RemovesDecoder._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 aLinearthat lists preserved params instead of silently dropping the field.Controller.Config.precisioninstead of its owngenerator.model_dtype(removed). It builds the model inprecision.dtype, so buffers and preserved params get the trainer's dtypes. It holds every other parameter inprecision.param_dtypeand computes in it (vLLMdtype; the wrapper raises if they differ), so its FSDP casts nothing. The generator model is frozen, and parameters are cast withtorch.utils.swap_tensors, sinceparam.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 inparam_dtype(transfer_dtype, when it differs fromdtype), 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), andgpu_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, GDNA_log/dt_biasreach the generator in bf16, soVLLMInnerGDNcasts 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.export_state_dict(state_dict, *, dtype, model_parts)replaces the duplicated cast loops in both checkpointers and bothscripts/checkpoint_conversion/converters. The converters now cast beforeto_hf, like the in-training export.param_dtype_override_fnargument,models/README.mdbullet, reworded KDA TODO.Alternatives considered
GatedRMSNorm, KDA's stays bf16).nn.Parameterobjects: tags are lost throughto_empty,param.data =and DTensor re-wrapping.generator.model_dtypeand 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'sprecisionmakes every dtype match by construction.FlexShard's
param_dtype_overrides(an FQN map) can consumenamed_preserve_dtype_paramsdirectly once it lands; not wired here.User-facing changes
A_log/dt_biasin bf16precision.dtype="bfloat16")generator.model_dtype(every recipe:"bfloat16")precision.param_dtype(default"bfloat16");generator.model_dtyperemovedA_log/dt_biasfp32, values bf16-roundedexport_dtype="bfloat16"convert_to_hf.py --export_dtype bfloat16to_hf, so adapter-created tensors were cast too (DSV4tid2eid: int64 -> fp32 into_hf, then rounded to bf16)to_hf;tid2eidstays fp32Numerics
Deterministic, seed 42, flex attention, 2 GPUs FSDP, GB300; base = main with #5659 (+ #5776, which is bitwise identical to main).
C4 (
allenai/c4) convergence, 600 steps, mean loss over each window: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).
Testing
rl_grpo_kimi_k3_debug_batch_invariant, 4 GPUs, bf16 masters):bit_wise/logprob_diff/max = 0at every step.TestBitwiseParityQwen35DebugVarlen, fp32 masters, asserts every receive dtype equals what the trainer sends): 4 passed.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.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 aSimpleNamespacewithoutnamed_buffersto 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.test_fsdp.py(preserved param unshards in its dtype),test_trainer.py(preserved names inpreserve_dtype_keys),test_torch_checkpointing.py(export keeps a preserved fp32 param),test_bitwise_parity.py(receive dtypes).Known issues / follow-ups
rl_grpo_qwen3_5_debug_tp2_batch_invariantCI config. A 4-GPU variant (trainer DP 1) is not bitwise on base or on this PR.A_log/dt_biasin bf16, the trainer's dtype, soVLLMInnerGDNcasts 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.VarlenInnerAttentiondefaults to cuDNN attention first, whose dQ backward is not deterministic underdebug.deterministic=Trueon SM100+ (flash is). Numerics above use flex attention for that reason.This PR was AI-assisted.