Skip to content

[config] Move dtypes into a root-owned PrecisionConfig; FSDP CPU offload into ParallelismConfig - #5776

Merged
tianyu-l merged 1 commit into
mainfrom
precision-config
Nov 4, 2026
Merged

tianyu-l merged 1 commit into
mainfrom
precision-config

Conversation

@tianyu-l

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

Copy link
Copy Markdown
Contributor

Summary (human-written)

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.

# 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 [models][fsdp] preserve_dtype_params: keep selected parameters out of mixed-precision casts #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 [rl] generator: keep GDN A_log/dt_bias in float32 (6/7) #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.

@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 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 4m 12s —— View job


Approve, with two things to fix before merging -- 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 -- please address the items below before merging. The move is mechanical and complete: no reads of the old fields are left anywhere in the repo. One new test, though, puts an RL-only import into the core CPU suite.

What this PR does. It moves the three dtype fields out of TrainingConfig into a new PrecisionConfig owned by the root config: Trainer.Config.precision for SFT, Controller.Config.precision for RL. TrainingEngine now takes precision as a constructor argument. It also moves training.enable_cpu_offload to parallelism.fsdp_enable_cpu_offloading. With both moves, model.parallelize / _apply_fsdp take precision= and no longer see the whole TrainingConfig. The Dist-MoE param_dtype == "bfloat16" check moves to the two root configs.

Example.

# before: parallelize gets all of TrainingConfig but reads only 4 fields
model.parallelize(parallelism_context=pc, training=config.training, parallelism=p, ...)
# RL generator invents a TrainingConfig() just to satisfy this signature

# after
model.parallelize(parallelism_context=pc, precision=config.precision, parallelism=p, ...)
# RL: Controller.Config.precision -> spawn_trainer(precision=...) -> Trainer -> TrainingEngine

Must fix

  1. PR description -- the "Summary (human-written)" section is empty. The author has to fill it in (CONTRIBUTING.md, AI-assisted contributions).
  2. tests/unit_tests/cpu/models/common/test_dist_moe.py:966 -- the core CPU test imports torchtitan_recipes.tests.rl.alphabet_sort, which pulls in torchstore (not installed in the core CPU CI image). Move the RL half to tests/rl/unit_tests/cpu/ (inline).

Should consider

  • torchtitan/config/parallelism.py:64 -- rename to fsdp_cpu_offload so the PR doesn't add a new enable_* name, and to match the cpu_offload= kwarg every consumer uses (inline).
  • torchtitan/experiments/graph_trainer/trainer.py:99 -- _parallelize_compile_kwargs now returns training, which is not a compile kwarg, and the pp_enabled branch depends on what core's pipeline call passes (inline).
Details
  • Callsite audit. I grepped for mixed_precision_param, mixed_precision_reduce, enable_cpu_offload and training.dtype across .py/.md/recipes: no hits remain. Every parallelize/_apply_fsdp override is updated: base, decoder, multimodal, deepseek_v3 MTP, deepseek_v4, flux, gpt_oss, kimi_k2_7, kimi_k3, muse_glimmer, qwen3_5, HF backend, GraphTrainer, autoparallel. Every TrainingEngine subclass forwards precision: GraphTrainer, torchft, the integration test engine. RL: spawn_trainer(**kwargs) -> TrainerActor(Trainer), so precision= reaches Trainer.__init__ without changes to actors/.
  • Validation chain. GraphTrainer.Config, FluxTrainer.Config and torchft Trainer.Config all inherit from or call Trainer.Config.__post_init__, so they keep the Dist-MoE check. RL trainers get it only from Controller.Config, which is why item 2 matters.
  • Numerics. The generator still uses PrecisionConfig(), whose defaults (bf16/fp32) equal the old TrainingConfig() defaults. Each recipe's dtypes map 1:1. I found no computation change.

Not verified: core CPU CI import failure (CPU Unit Test was skipped on this run); GPU/PP/CPU-offload numerics. This PR touches trainer.py/training_engine.py, so a maintainer still needs to review.

Comment on lines +966 to +977
from torchtitan_recipes.tests.rl.alphabet_sort import (
rl_grpo_moe_debug_dist_moe_tp2_ep4,
)

config = deepseek_v3_debugmodel()
config.dist_moe_runtime = DistMoeRuntime.Config()
rl_config = rl_grpo_moe_debug_dist_moe_tp2_ep4()
assert rl_config.trainer.dist_moe_runtime is not None
for root_config in (config, rl_config):
root_config.precision = PrecisionConfig(param_dtype="float32")
with pytest.raises(ValueError, match="param_dtype='bfloat16'"):
root_config.__post_init__()

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.

This core CPU test now imports the RL stack: torchtitan_recipes.tests.rl.alphabet_sort -> torchtitan.rl.controller.controller -> torchtitan.rl.trainer.trainer, which does import torchstore at module level. unit_test_cpu.yaml runs tests/unit_tests/cpu in the non-:rl image. That image is built without INSTALL_RL_DEPS, and torchstore only comes from scripts/install_rl_env.sh. So this test should hit ModuleNotFoundError in core CPU CI (unverified: CPU Unit Test was skipped on this run). It also breaks tests.md, which says RL tests go in tests/rl/.

Fix: keep only the deepseek_v3_debugmodel half here, and move the Controller.Config half to tests/rl/unit_tests/cpu/ (e.g. test_alphabet_sort.py, which already builds these recipes). That copy of the check is the only guard for RL trainers, so it's worth keeping in the RL suite.

fsdp_defer_gradient_reduction: bool = False
"""Defer FSDP gradient reduction until the last accumulation step."""

fsdp_enable_cpu_offloading: bool = False

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.

Since this field is being renamed anyway, consider fsdp_cpu_offload: bool instead of adding a new enable_* name (direction.md calls the remaining enable_* booleans legacy). Every consumer already takes this value as cpu_offload= (apply_fsdp_to_decoder, apply_fsdp_to_mtp_decoder, apply_fsdp_to_multimodal_encoder, Flux _parallelize_encoders), and upstream says "offload" (CPUOffloadPolicy, offload_policy), not "offloading".

@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 35s —— View job


Approve, but the human-written summary still needs filling in before merging -- 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 -- please address the item below before merging. The force-push at 7fe5d76 fixes the RL import in the core CPU suite and renames the hook. The only blocker left is the empty human-written summary.

What this PR does. It moves training.{dtype, mixed_precision_param, mixed_precision_reduce} into a root-owned PrecisionConfig (Trainer.Config.precision for SFT, Controller.Config.precision for RL) and passes it to TrainingEngine as a constructor argument. It also moves training.enable_cpu_offload to parallelism.fsdp_enable_cpu_offloading. After both moves, parallelize/_apply_fsdp take precision= instead of the whole TrainingConfig.

Example.

# before
model.parallelize(parallelism_context=pc, training=config.training, parallelism=p, ...)
# after
model.parallelize(parallelism_context=pc, precision=config.precision, parallelism=p, ...)
# RL: Controller.Config.precision -> spawn_trainer(precision=...) -> Trainer -> TrainingEngine

Status of earlier items

  • Resolved: tests/unit_tests/cpu/models/common/test_dist_moe.py no longer imports the RL stack. The Controller.Config half of the check now lives in tests/rl/unit_tests/cpu/test_rl_dist_moe_recipe.py:45, which the B200 RL workflow runs with dist_moe installed.
  • Resolved: _parallelize_compile_kwargs is renamed to _parallelize_kwargs in core and in GraphTrainer, and its docstrings now say it returns training too.
  • Still open (must fix): the "Summary (human-written)" section of the PR description is still the template placeholder. The author has to write it (CONTRIBUTING.md, AI-assisted contributions).
  • Still open (should consider, author's call): torchtitan/config/parallelism.py:64 keeps the name fsdp_enable_cpu_offloading. fsdp_cpu_offload would avoid a new enable_* name and would match the cpu_offload= kwarg every consumer takes.

No new problems in the force-pushed commit.

Details
  • Leftover reads. I grepped mixed_precision_param, mixed_precision_reduce, enable_cpu_offload, training.dtype and _parallelize_compile_kwargs across the tree. Nothing is left in the PR's files.
  • Constructors. Every TrainingEngine construction passes precision: core Trainer, RL Trainer, torchft, GraphTrainer, the SDC integration engine, and the unit tests. The RL Trainer gets it through spawn_trainer(**kwargs), so actors/ needs no change.
  • Validation chain. Core trainers get the Dist-MoE param_dtype check from Trainer.Config.__post_init__, RL trainers from Controller.Config.__post_init__. Both are covered by a CPU test.

Not verified: GPU, PP and CPU-offload numerics (the PR says these rely on CI). This PR touches trainer.py/training_engine.py, so a maintainer still needs to review.

@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 42s —— View job


Approve -- please fill in the human-written summary before merging -- 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 -- please address the item below before merging. The force-push at 6fa943a rebases onto #5659 (411ce5b) and adapts to it correctly. Nothing new needs fixing; the empty human-written summary is still the one blocker.

What this PR does. It moves training.{dtype, mixed_precision_param, mixed_precision_reduce} into a root-owned PrecisionConfig (Trainer.Config.precision for SFT, Controller.Config.precision for RL), which is passed to TrainingEngine as a constructor argument. It also moves training.enable_cpu_offload to parallelism.fsdp_enable_cpu_offloading, so parallelize/_apply_fsdp take precision= instead of the whole TrainingConfig.

Example.

# before
model.parallelize(parallelism_context=pc, training=config.training, parallelism=p, ...)
# after
model.parallelize(parallelism_context=pc, precision=config.precision, parallelism=p, ...)
# RL: Controller.Config.precision -> spawn_trainer(precision=...) -> Trainer -> TrainingEngine

Status of earlier items

  • Still open (must fix): the "Summary (human-written)" section of the PR description is still the template placeholder. The author has to write it (CONTRIBUTING.md, AI-assisted contributions).
  • Still open (should consider, author's call): torchtitan/config/parallelism.py:64 keeps the name fsdp_enable_cpu_offloading. fsdp_cpu_offload would avoid adding a new enable_* name and would match the cpu_offload= kwarg that every consumer takes.
  • The two items fixed in 7fe5d76 are still fixed at HEAD: the RL import is out of the core CPU suite, and the hook is now named _parallelize_kwargs.

Rebase onto #5659

  • torchtitan/rl/trainer/trainer.py:137: _transfer_dtype (added in #5659) now compares the generator dtype against precision.dtype, which replaces config.training.dtype. That is the same value, so push_model_state_dict behaves the same.
Details
  • Leftover reads at HEAD. I grepped the tree for mixed_precision_param, mixed_precision_reduce, enable_cpu_offload, training.dtype and _parallelize_compile_kwargs. Nothing is left, including in the code #5659 added. (The CI checkout overwrites .claude/ with main's copy, so a hit in numerics_debugging/SKILL.md there is an artifact. The PR's commit has config.precision.param_dtype.)
  • Constructors. Every TrainingEngine / GraphTrainingEngine / FaultTolerantTrainingEngine construction in source and tests passes precision. The new #5659 test in tests/rl/unit_tests/cpu/test_trainer.py sets _transfer_dtype directly and doesn't build an engine.

Not verified: GPU, PP and CPU-offload numerics (the PR says these rely on CI). I couldn't run unit tests in this job. This PR touches trainer.py/training_engine.py, so a maintainer still needs to review.

@tianyu-l
tianyu-l marked this pull request as ready for review November 3, 2026 18:00
@pytorch-bot pytorch-bot Bot added ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests labels Nov 3, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 3, 2026 18:00
@tianyu-l
tianyu-l force-pushed the precision-config branch 2 times, most recently from 87cc530 to f2ceae6 Compare 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 3m 31s —— View job


Approve -- please fill in the human-written summary before merging -- 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 -- please address the item below before merging. At f2ceae6 the move is mechanical and complete. Nothing in the repo still reads the old fields, and every parallelize / _apply_fsdp / pipeline / TrainingEngine callsite passes precision. The empty human-written summary is the only blocker.

What this PR does. It moves training.{dtype, mixed_precision_param, mixed_precision_reduce} into a new PrecisionConfig(dtype, param_dtype, reduce_dtype), owned by the root config: Trainer.Config.precision for SFT and Controller.Config.precision for RL. TrainingEngine now takes it as a constructor argument. training.enable_cpu_offload becomes parallelism.fsdp_enable_cpu_offloading. After both moves, parallelize / _apply_fsdp take precision= instead of the whole TrainingConfig. The Dist-MoE param_dtype == "bfloat16" check moves out of TrainingEngine.Config and into the two root configs.

Example.

# before
config.training.mixed_precision_param = "bfloat16"
model.parallelize(parallelism_context=pc, training=config.training, parallelism=p, ...)
# RL generator: model.parallelize(..., training=TrainingConfig(), ...)

# after
config.precision.param_dtype = "bfloat16"
model.parallelize(parallelism_context=pc, precision=config.precision, parallelism=p, ...)
# RL: Controller.Config.precision -> spawn_trainer(precision=...) -> Trainer -> TrainingEngine
# RL generator: model.parallelize(..., precision=PrecisionConfig(), ...)

Must fix

  1. PR description: the "Summary (human-written)" section is still the empty template placeholder. The author has to write it (CONTRIBUTING.md, AI-assisted contributions).

Should consider

  • torchtitan/config/parallelism.py:64: this is still open from the first review and is the author's call. fsdp_cpu_offload would avoid adding a new enable_* name (direction.md treats those as legacy). It would also match the cpu_offload= kwarg that every consumer takes and upstream's CPUOffloadPolicy / offload_policy naming.
Details
  • Leftover reads. I grepped the tree, including .github/, scripts/ and docs/, for mixed_precision_param, mixed_precision_reduce, enable_cpu_offload, training.dtype and _parallelize_compile_kwargs. The only hit is in .claude/skills/numerics_debugging/SKILL.md, and it is an artifact: the CI checkout restores main's .claude/, while the PR's commit has config.precision.param_dtype.
  • Callsites.
    • Every parallelize / _apply_fsdp override and caller passes precision: base, decoder, multimodal, deepseek_v3 MTP, deepseek_v4, flux (model and encoders), gpt_oss, kimi_k2_7, kimi_k3, muse_glimmer, qwen3_5, the HF backend, GraphTrainer (simple_fsdp, AutoParallel, GraphPP, precompile), the vLLM generator wrapper, the qwen3_5 shard script and the GPU bitwise-parity test.
    • pipeline_kimi_k3 and pipeline_with_first_last_stage_modules forward **kwargs, so precision reaches pipeline_llm.
    • Every TrainingEngine subclass forwards precision: GraphTrainer, torchft and the SDC integration engine.
  • Validation chain.
    • Core: GraphTrainer.Config, FluxTrainer.Config and torchft go through Trainer.Config.__post_init__.
    • RL: the trainers get the check only from Controller.Config.__post_init__. That copy is tested in tests/rl/unit_tests/cpu/test_rl_dist_moe_recipe.py, which skips without dist_moe and so only runs in the B200 RL job.
    • RL Trainer.Config inherits TrainingEngine.Config, not core Trainer.Config, so it doesn't carry a second, ignored precision field.
  • Numerics.
    • Every recipe maps its dtypes 1:1. dapo_math keeps the default reduce_dtype="float32"; the batch-invariant recipes keep the dtype="float32" override, now through dataclasses.replace(config.precision, ...).
    • The generator's PrecisionConfig() defaults equal the old TrainingConfig() defaults.
    • Its ParallelismConfig defaults fsdp_enable_cpu_offloading=False, as before.
    • _transfer_dtype in the RL trainer reads precision.dtype, which holds the same value as before.

Not verified: GPU, PP and CPU-offload numerics (the PR says these rely on CI). I didn't run the unit tests in this job. This PR touches trainer.py and training_engine.py, so a maintainer still needs to review it.

…oad into ParallelismConfig

training.dtype / mixed_precision_param / mixed_precision_reduce become
PrecisionConfig.dtype / param_dtype / reduce_dtype, owned by the core
Trainer.Config and the RL Controller.Config instead of TrainingEngine.Config.
The engine receives it as a constructor argument, like model_config, and
model.parallelize takes precision= instead of training=.
training.enable_cpu_offload becomes parallelism.fsdp_enable_cpu_offloading.

No numerics change.
@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 2m 11s —— View job


Approve -- please fill in the human-written summary before merging -- 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 -- please address the item below before merging. The force-push at 880cdc7 rebases onto #5572 (0f34815), and the new launcher code works with Controller.Config.precision unchanged. The empty human-written summary is still the one blocker.

What this PR does. It moves training.{dtype, mixed_precision_param, mixed_precision_reduce} into a root-owned PrecisionConfig (Trainer.Config.precision for SFT, Controller.Config.precision for RL), which is passed to TrainingEngine as a constructor argument. It also moves training.enable_cpu_offload to parallelism.fsdp_enable_cpu_offloading, so parallelize / _apply_fsdp take precision= instead of the whole TrainingConfig.

Example.

# before
config.trainer.training.dtype = "bfloat16"                     # RL recipe
model.parallelize(parallelism_context=pc, training=config.training, parallelism=p, ...)
# after
config.precision = PrecisionConfig(dtype="bfloat16")           # on Controller.Config
model.parallelize(parallelism_context=pc, precision=config.precision, parallelism=p, ...)
# SLURM launch recipe (#5572): from_controller_config(config, launcher=...) carries precision over

Must fix

  1. PR description: the "Summary (human-written)" section is still the template placeholder. The author has to write it (CONTRIBUTING.md, AI-assisted contributions).

Should consider

  • torchtitan/config/parallelism.py:64: still open, author's call. fsdp_cpu_offload would avoid adding a new enable_* name and would match the cpu_offload= kwarg every consumer takes.
  • tests/rl/unit_tests/gpu/test_generator_dist_moe_mxfp8.py:127: an unrelated fix for a #5691 test breakage; better as its own PR (inline).
Details
  • Interaction with #5572.
    • MonarchControllerWithLauncher.Config.from_controller_config (torchtitan/rl/actors/monarch/launcher/base.py:264) copies every field with dataclasses.fields(config), so the new precision field reaches the launcher config.
    • rl_grpo_qwen3_0_6b_flex_slurm wraps rl_grpo_qwen3_0_6b_flex(), so it inherits PrecisionConfig(dtype="bfloat16").
    • Its __post_init__ calls Controller.Config.__post_init__, so it keeps the Dist-MoE param_dtype check.
    • The Monarch spawn_trainer still forwards **kwargs to TrainerActor, so precision= reaches Trainer.__init__.
    • test_launcher.py and test_shutdown.py never construct a real Trainer, so they need no precision.
  • Leftover reads at HEAD. I grepped for mixed_precision_param, mixed_precision_reduce, enable_cpu_offload, training.dtype and _parallelize_compile_kwargs. The only hit is .claude/skills/numerics_debugging/SKILL.md, which is the CI-checkout artifact from earlier reviews; the PR's commit has config.precision.param_dtype.
  • Constructors. Every TrainingEngine / GraphTrainingEngine / FaultTolerantTrainingEngine / RL Trainer construction in source and tests passes precision.

Not verified: GPU, PP and CPU-offload numerics (the PR says these rely on CI). This PR touches trainer.py and training_engine.py, so a maintainer still needs to review it.

Comment on lines +127 to +132
def _trainer_model(wrapper, state_dict: dict[str, torch.Tensor]) -> SimpleNamespace:
"""Stand in for the trainer model: ``state_dict`` under the generator model's
buffer names, which match the trainer's."""
return SimpleNamespace(
state_dict=lambda: state_dict, named_buffers=wrapper.model.named_buffers
)

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.

The fix is correct: _sync_trainer_weights_to_vllm (tests/rl/unit_tests/gpu/test_bitwise_parity.py:281) now calls trainer_model.named_buffers(), and a bare SimpleNamespace(state_dict=...) doesn't have it. But this breakage comes from #5691 and has nothing to do with the precision move. CLAUDE.md asks for one concern per PR, so it would be cleaner as its own small PR that can land first. If it stays here to keep rl-b200 green, that's the author's call, and the description already says so.

@tianyu-l
tianyu-l merged commit e6ca6d8 into main Nov 4, 2026
@tianyu-l
tianyu-l deleted the precision-config branch November 4, 2026 00:22
tianyu-l added a commit that referenced this pull request Nov 4, 2026
… mixed-precision casts (#5774)

Stacked on #5776 (GitHub stack: this PR's base is #5776'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. -->

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.**
```python
# 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 #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 #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` (#5652) fetches straight into the
sharded parameters, so #5652's cast of float32 parameters through
model-dtype staging tensors is removed. This generalizes #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 #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 #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 #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.
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
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.
felipemello1 pushed a commit that referenced this pull request Nov 5, 2026
…config, Trainer takes precision

Main moved max_context_length from TrainingConfig to the model config (#5779) and dtypes into a
root-owned PrecisionConfig (#5776). The test now passes the recipe's precision to Trainer.
2 GPUs: 1 passed (87 s).
SherlockNoMad added a commit that referenced this pull request Nov 9, 2026
Stacked on #5835.

## 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
GraphTrainer already runs Muse Glimmer in its integration tests, but
nothing
checks its numerics against eager, so a GraphTrainer change could
silently
alter Muse Glimmer's loss. The vision flavor (`debugmodel_mm`) also
fails deep
in tracing with a data-dependent-shape error instead of a clear message.

**Example.**
```python
to_graph_trainer_config(muse_glimmer_debugmodel_mm(), GraphTrainerMuseGlimmerModel.Config)
# Before: fails during make_fx with a data-dependent-shape error
# After:  ValueError at config time: GraphTrainer MuseGlimmer supports
#         text-only flavors; got a vision encoder.
```

## What changed
- `graph_trainer/muse_glimmer/model.py`: the config rejects a vision
encoder
with `ValueError`, like Kimi K3, Kimi K2.7, and Qwen3.5 earlier in this
stack.
- Bitwise harness classes for Varlen and FlexAttention; a FlexAttention
test
  recipe; 4-GPU numerics configs (FSDP2 + TP2); README row.

## Numerics
Eager FSDP2 vs GraphTrainer, seed 42, deterministic,
`scripts/loss_compare.py --assert-equal`. Measured on base `0f3481537`.
Rebasing onto `d0ab95e46` changed only recipe field names in this diff
(#5776, #5779); re-verification on the new base is in progress.

| Config | GPUs | Result |
| --- | --- | --- |
| `debugmodel`, FlexAttention, FSDP2 + TP2, 20 steps | 4x GB300 | loss
and grad_norm bitwise identical |
| `debugmodel`, PP2 Interleaved1F1B, 10 steps | 2x GB300 | loss and
grad_norm bitwise identical |

The 4-GPU comparison uses FlexAttention. FA4's Varlen backward is not
deterministic for full causal attention on Blackwell, so two Varlen
eager runs
with FSDP2 + TP2 already differ in grad_norm at step 1.

## Testing
- `test_bitwise_deterministic.py::TestMuseGlimmerBitwiseDeterministic`
and
  `TestMuseGlimmerFlexAttnBitwiseDeterministic` (1 GPU): eager vs
aot_fx_trace, trace vs precompile, and `numerics_changing_optim`
run-to-run
  produce bitwise identical loss, model hash, and gradient hash.
- `test_numerics.py::test_dense_muse_glimmer_aot_fx_trace_vs_eager` (4
GPUs):
  the FSDP2 + TP2 row above.
- The PP row was run locally; it is not a CI test.

## Known issues / follow-ups
- CP is not covered.
- Next in the stack: Muse Spark (in progress).
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.

2 participants