Skip to content

[train] Require one device for a seed checkpoint - #5313

Merged
tianyu-l merged 11 commits into
pytorch:mainfrom
YeonwooSung:pr/validate-seed-checkpoint
Nov 3, 2026
Merged

tianyu-l merged 11 commits into
pytorch:mainfrom
YeonwooSung:pr/validate-seed-checkpoint

Conversation

@YeonwooSung

@YeonwooSung YeonwooSung commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

A seed checkpoint has to be written from one rank, but main() asserted int(os.environ["WORLD_SIZE"]) == 1. Pure fake mode never sets that variable, so the assert raises KeyError, and python -O removes it, so an 8-rank launch can save a sharded init and still log "Created seed checkpoint". checkpointer=None and load_only=True also skip the write and log success. The launch check now raises ValueError from trainer.engine.parallelism_context.world_size, and Trainer.Config.__post_init__ rejects a checkpointer that will not save. Seed recipes set create_seed_checkpoint after the config is built and leave override.imports empty, so ConfigLoader.load runs __post_init__ again after launch options and apply_overrides runs it again after replacements.

Why

A seed checkpoint has to be written from one rank. main() used to assert int(os.environ["WORLD_SIZE"]) == 1. Pure fake never sets WORLD_SIZE, so that assert raises KeyError. Under python -O the assert is removed, so an 8-rank launch can save a sharded init and still log "Created seed checkpoint". checkpointer=None and checkpointer.load_only=True also skip the write (_should_save returns false) and still log success.

Example.

# torchrun --nproc_per_node=8, python -O, create_seed_checkpoint=True
# before: assert removed, sharded checkpoint, "Created seed checkpoint"
# after:  ValueError: ... Got world size 8.

# create_seed_checkpoint=True, checkpointer.load_only=True
# before: nothing saved, "Created seed checkpoint"
# after:  ValueError: create_seed_checkpoint requires a checkpointer with load_only=False.

What changed

  • main() reads trainer.engine.parallelism_context.world_size and raises ValueError unless it is 1. The helper and the is_initialized() branch are gone. World size 1 already means every parallelism degree is 1.
  • Trainer.Config.__post_init__ rejects a missing checkpointer and load_only=True when create_seed_checkpoint is set.
  • Configurable.Config.__post_init__ is a no-op, so every config can be re-entered. ConfigLoader.load calls it after the recipe and launch options. apply_overrides calls it after replacements. Trainer.__init__ does not. Seed recipes assign the flag and set no imports (tests/integration_tests/features.py, the checkpoint compat generator), so the loader is the call that sees them. The RL controller, rl/generate.py, precompile, and torchft already call apply_overrides, so they revalidate there.
  • torchtitan/config/transform/README.md names those two calls.
  • Deleted tests/unit_tests/cpu/test_seed_checkpoint_launch.py. The checkpointer rule is still covered by re-entering __post_init__. Two new tests lock the loader call and the apply_overrides call. No distributed monkeypatch.
  • HFTransformerModel.Config.__post_init__ forwards leftover kwargs to PretrainedConfig.__post_init__. Configurable.Config.__post_init__ is ahead of PretrainedConfig in that MRO and takes no extra arguments, so attn_implementation raised TypeError while collecting tests/unit_tests/cpu/recipes/test_debug_config_defaults.py.

Alternatives considered

  • Revalidating only in Trainer.__init__ misses the RL controller, which applies overrides and never builds a Trainer.
  • Revalidating only in apply_overrides misses the seed recipes. They assign the flag and leave override.imports empty, and every caller skips apply_overrides in that case.

Numerics / performance

No training math changes. A rejected launch does not save. A one-rank launch with a saving checkpointer still calls save_checkpoint(last_step=True). Kimi's optimizer alignment runs again on load; when the layouts already match it returns the same optimizer. No GPU loss comparison.

Testing

tests/unit_tests/cpu/config/test_override.py (including test_revalidates_after_assignment) and test_load_revalidates_recipe_assignments passed locally: 39 passed. test_seed_checkpoint_requires_a_saving_checkpointer still calls __post_init__() for checkpointer=None, load_only=True, and a normal checkpointer. This machine cannot collect that file: module 'spmd_types' has no attribute 'rules', then NumPy 2.2.6 vs bottleneck. The loader tests that import a recipe hit the same spmd_types error inside _load_config, before the new call. No seed-checkpoint launch was run here. CPU build-test job 125731353312 failed that collection with the attn_implementation TypeError. This machine still cannot import that test (spmd_types.rules). A local MRO replica of the same call raises on the base method and returns the kwargs once the subclass forwards them.

Known issues

Pure-fake seed checkpoint is not a workflow this needs. validate_fake_pg_compatibility already rejects create_seed_checkpoint unless the integration test sets use_real_pg. scripts/loss_compare.py starts the seed run under torchrun with one GPU. parallelism_context.world_size is NGPU in fake mode and the torchrun world size otherwise. A Trainer or FaultTolerantTrainer built in-process, without ConfigLoader and without override imports, does not re-enter __post_init__. FaultTolerantTrainer copies __init__ and does not add its own call.

The launch check read WORLD_SIZE, which pure fake mode does not set.
Use the initialized process-group world size and raise ValueError.
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 12, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 12, 2026
@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 30s —— View job


Request changes: the fix should read parallelism_context.world_size, move the checkpointer check (including load_only) to Trainer.Config.__post_init__, and delete the helper and its test. 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: Request changes -- The problem is real and small. The fix should read the world size the engine already computed, check the checkpointer at config time, and drop the helper and its test. That is about +12/-7 instead of +83/-7.

What this PR does. The seed-checkpoint path in main() used two asserts. The PR replaces them with ValueErrors in a new helper, _require_seed_checkpoint_launch. The helper reads torch.distributed.get_world_size() instead of os.environ["WORLD_SIZE"], and it adds a check that the process group is initialized. A new CPU test file monkeypatches torch.distributed to exercise the helper.

Example.

# main: NGPU=1 COMM_BACKEND=fake ./run_train.sh (seed recipe)
KeyError: 'WORLD_SIZE'                      # pure fake never sets it
# main: torchrun x8 + python -O
the assert is stripped -> sharded init is saved, "Created seed checkpoint" is logged
# main: checkpointer=CheckpointManager.Config(load_only=True)
nothing is saved, "Created seed checkpoint" is logged  # still true with this PR
# PR: the first two raise ValueError after config.build(); the third is unchanged

Must fix

  1. The PR description doesn't follow .github/pull_request_template.md. It has no "Summary (human-written)" section, and the only test-plan item is unchecked. Please use the template, and say whether you ran the new test or a real seed-checkpoint launch.
  2. torchtitan/train.py:28 -- Read trainer.engine.parallelism_context.world_size and remove the is_initialized() branch, which can't fire. Then inline the check in main().
  3. torchtitan/train.py:39 -- Move the checkpointer check to Trainer.Config.__post_init__, and reject load_only=True there as well.
  4. tests/unit_tests/cpu/test_seed_checkpoint_launch.py:11 -- Delete this file. It imports a private name and monkeypatch-tests error branches that fail loudly anyway.

Questions

  • Is a pure-fake seed checkpoint a workflow you actually need? validate_fake_pg_compatibility (tests/integration_tests/__init__.py:97) rejects checkpointing and create_seed_checkpoint under fake PG, and scripts/loss_compare.py launches the seed run with real torchrun and NGPU=1. If fake mode only needs a clear error here, the motivation could say so.
Details
  • ParallelismContext validates dp_replicate * dp_shard * cp * tp * pp == world_size. So world_size == 1 already implies every degree is 1, and the documented "every parallelism degree set to 1" doesn't need a separate check.
  • In real_pp_fake_spmd, init_fake_mode(NGPU) makes the default PG fake with NGPU ranks. get_world_size() therefore also returns NGPU, so the PR's helper isn't wrong there. parallelism_context.world_size is still the canonical value, and it removes the need for the is_initialized guard.
  • The world-size check still runs after engine.initialize, which does a full CPU init of the model on every rank. That's the same as before this PR. Failing earlier would mean adding it to Trainer.__init__ before engine.initialize, and that isn't required here.
  • No overlap with open PRs. #5748 touches seed checkpoints only inside the checkpointer, not train.py.

Not verified: I didn't run a real or fake seed-checkpoint launch. A maintainer still needs to review, since this touches torchtitan/train.py.

Comment thread torchtitan/train.py Outdated
Comment on lines +28 to +38
if not torch.distributed.is_initialized():
raise ValueError(
"Must create a seed checkpoint on an initialized single-device "
"process group."
)
world_size = torch.distributed.get_world_size()
if world_size != 1:
raise ValueError(
"Must create a seed checkpoint using a single device, to disable "
f"sharding. Got world size {world_size}."
)

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 engine already has the logical world size: trainer.engine.parallelism_context.world_size. init_distributed returns it (NGPU for fake and real_pp_fake_spmd, get_world_size() under torchrun), and ParallelismContext checks that the product of all degrees equals it. So world size 1 also means every parallelism degree is 1, which is the invariant the docs state.

Reading that field makes the is_initialized() branch unnecessary. TrainingEngine.__init__ always calls init_distributed before config.build() returns, so the branch can't fire on a real launch. It's a just-in-case check (CLAUDE.md principle 8), and the test for it exists only because of the branch. Inline it at the call site in main():

        if config.create_seed_checkpoint:
            world_size = trainer.engine.parallelism_context.world_size
            if world_size != 1:
                raise ValueError(
                    "Must create a seed checkpoint using a single device, to "
                    f"disable sharding. Got world size {world_size}."
                )
            trainer.engine.save_checkpoint(last_step=True)

With this and the checkpointer change below, _require_seed_checkpoint_launch has no reason to exist. It's a single-use helper (design.md).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Inlined in main() after config.build(). The check reads trainer.engine.parallelism_context.world_size. The is_initialized() branch is gone, and _require_seed_checkpoint_launch is deleted.

Pure-fake seed checkpoint is not a workflow this PR needs. validate_fake_pg_compatibility already rejects create_seed_checkpoint unless the integration test sets use_real_pg. scripts/loss_compare.py launches the seed run with torchrun and one GPU. parallelism_context.world_size is NGPU under fake and the torchrun world size otherwise, so a multi-rank launch still raises ValueError here.

Comment thread torchtitan/train.py Outdated
Comment on lines +39 to +42
if config.checkpointer is None:
raise ValueError(
"Must configure checkpointer when creating a seed checkpoint."
)

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 check depends only on config, so it belongs in Trainer.Config.__post_init__ (torchtitan/trainer.py:78), next to the create_seed_checkpoint field (config.md: "Validate in __post_init__ of the owning config"). Where it is now, it runs after distributed init, the full CPU model init, and the optimizer build.

checkpointer.load_only=True has the same problem the description lists for None: _should_save returns False, nothing is written, and main() still logs "Created seed checkpoint". Reject both in one place:

            if self.create_seed_checkpoint and (
                self.checkpointer is None or self.checkpointer.load_only
            ):
                raise ValueError(
                    "create_seed_checkpoint requires a checkpointer with "
                    "load_only=False."
                )

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The rule rejects both checkpointer is None and load_only=True. It lives on Trainer.Config and post_init calls it.

post_init does not see assignments made after the config object exists. tests/integration_tests/features.py llama3_debugmodel_seed_checkpoint and the checkpoint compat generator set create_seed_checkpoint = True on the returned config. Trainer.init therefore runs the same check after overrides and before the engine is built, so those configs still fail before model init.


import pytest

from torchtitan.train import _require_seed_checkpoint_launch

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.

Please delete this file. It imports a module-private name (_require_seed_checkpoint_launch), and it monkeypatches torch.distributed to cover three if statements whose failure is loud, not silent (tests.md: add a test only for an invariant that would otherwise break silently). The uninitialized-PG case tests the dead branch above. Once the checks are inlined and moved to __post_init__, nothing is left to import. If you want any coverage, a single pytest.raises(ValueError) case for the __post_init__ check in an existing config-validation test is enough.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Deleted tests/unit_tests/cpu/test_seed_checkpoint_launch.py. The checkpointer rule is covered by test_seed_checkpoint_requires_a_saving_checkpointer in tests/unit_tests/cpu/config/test_config_validation.py. It calls post_init again after setting the fields, which is the pattern already used in that file. There is no distributed monkeypatch and no world-size test.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 3, 2026
Comment thread torchtitan/trainer.py Outdated
)
# After overrides. Recipes also assign create_seed_checkpoint after
# the config object is built, so __post_init__ has already run.
config._reject_seed_checkpoint_without_save()

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.

instead of manually running this particular check, maybe we should force config.__post_init__ to be called in apply_overrides?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

apply_overrides runs only when override.imports is non-empty, and the same function is used by the RL controller, rl/generate.py, graph_trainer precompile, and the torchft trainer. The seed-checkpoint recipes never set those imports. llama3_debugmodel_seed_checkpoint and scripts/_checkpoint_test_config.py assign create_seed_checkpoint = True on a config that already exists.

Trainer.__init__ now calls config.__post_init__() after that overrides block and before the engine is built (29334a663). That replaces the separate validate_model_training_config re-call and the seed-checkpoint helper. GraphTrainer and FluxTrainer go through super().__init__, so their __post_init__ runs again. Kimi's __post_init__ rewrites DistMuon expert layouts and returns the same optimizer when those layouts already match, so the second call does not stack the rewrite.

FaultTolerantTrainer copies Trainer.__init__ and still does not revalidate. It did not revalidate before this change either.

Comment thread torchtitan/trainer.py Outdated
)
self._reject_seed_checkpoint_without_save()

def _reject_seed_checkpoint_without_save(self) -> None:

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.

inline this and make it simpler

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Inlined into Trainer.Config.__post_init__ (29334a663). The helper is gone. test_seed_checkpoint_requires_a_saving_checkpointer still calls __post_init__() after the fields are set.

@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@claude review my review

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 6s —— View job


Request changes (agrees with @tianyu-l): both comments are right, but the __post_init__ re-run belongs in Trainer.__init__ and should run unconditionally. Putting it in apply_overrides would miss this case, because recipes that assign create_seed_checkpoint never call apply_overrides. 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: Request changes (agrees with @tianyu-l) -- Both comments are correct in intent. The first one needs one adjustment: call config.__post_init__() unconditionally in Trainer.__init__, not inside apply_overrides, because the recipe-assignment case this PR targets never goes through apply_overrides.

What this PR does. It replaces the two seed-checkpoint asserts in main() with a ValueError on parallelism_context.world_size != 1. It also adds a config check that rejects checkpointer=None and load_only=True when create_seed_checkpoint is set. That check runs from __post_init__ and again by hand in Trainer.__init__.

Example.

config = llama3_debugmodel()          # __post_init__ runs here, flag is False
config.checkpointer = None
config.create_seed_checkpoint = True  # recipe assignment, no override imports
Trainer(config)
# with "__post_init__ in apply_overrides": apply_overrides is skipped
#   (trainer.py:160), nothing is saved, "Created seed checkpoint" is logged
# with "config.__post_init__() in Trainer.__init__": ValueError before engine build

On the maintainer's comments

  • torchtitan/trainer.py:173 (rerun __post_init__) -- Partly correct. Revalidating the whole tree is better than special-casing one check. But apply_overrides runs only when override.imports is non-empty, and it is shared with RL, precompile, and torchft. Put config.__post_init__() right after the overrides block in Trainer.__init__. That also replaces the duplicated validate_model_training_config(...) call at lines 163-170. Details inline.
  • torchtitan/trainer.py:96 (inline it) -- Correct. After the change above, __post_init__ is the only caller. Suggestion inline.

Must fix (missed)

  1. The PR description has an empty "Summary (human-written)" section, and its "What changed" bullet still describes Trainer.__init__ calling the helper. After the change, update the description and have the author fill in the summary.
Details
  • Call sites that set create_seed_checkpoint after construction: tests/integration_tests/features.py:840 and scripts/_checkpoint_test_config.py:108. Neither path uses override imports.
  • torchtitan/experiments/torchft/trainer.py:170 copies Trainer.__init__ and doesn't revalidate after overrides. That was already true before this PR and is out of scope here.
  • The world-size check in main() still runs after config.build(), so a multi-rank seed launch does a full CPU model init before it raises. This is unchanged from main, as the earlier review noted.

Not verified: no CPU tests or seed-checkpoint launch were run, and I didn't check whether any in-repo recipe's final config fails the re-run __post_init__. A maintainer still needs to review, since this touches torchtitan/trainer.py and torchtitan/train.py.

Comment thread torchtitan/trainer.py Outdated
Comment on lines +171 to +173
# After overrides. Recipes also assign create_seed_checkpoint after
# the config object is built, so __post_init__ has already run.
config._reject_seed_checkpoint_without_save()

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.

On @tianyu-l's comment: rerunning the full __post_init__ is the right idea, but apply_overrides is the wrong place to call it.

  • apply_overrides runs only when config.override.imports is non-empty (trainer.py:160). The case this check targets has no overrides: llama3_debugmodel_seed_checkpoint (tests/integration_tests/features.py:839-840) and scripts/_checkpoint_test_config.py:108 just assign create_seed_checkpoint = True to a config that already exists. A hook inside apply_overrides would miss them.
  • apply_overrides is shared with the RL controller, rl/generate.py, precompile_main.py, and the torchft trainer, and its config_root is typed as a plain Configurable.Config. Revalidation there would change every one of those callers.

Call it unconditionally in Trainer.__init__ instead. It also replaces the hand-written validate_model_training_config(...) re-call at lines 163-170, because Trainer.Config.__post_init__ already makes that call:

        if config.override.imports:
            apply_overrides(config.override, config)
        # Overrides and recipe assignments can change the config after
        # construction, so validate the final tree.
        config.__post_init__()
        model_config = config.model

The re-run is safe. TrainingEngine.Config.__post_init__, Trainer.Config.__post_init__, and GraphTrainer.Config.__post_init__ only validate and never mutate, and the tests already call config.__post_init__() repeatedly. The call dispatches to the subclass, so GraphTrainer's own checks also start covering post-construction edits. Unverified: an in-repo recipe whose final config fails a __post_init__ check that today runs only at construction would now raise. That would be a real bug, but CI is what would surface it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

config.__post_init__() is in Trainer.__init__ after the overrides block, not inside apply_overrides (29334a663). The manual validate_model_training_config re-call is gone. Subclass __post_init__ methods that only validate run again through normal dispatch. Kimi's layout rewrite returns the same optimizer when the layouts already match.

Comment thread torchtitan/trainer.py Outdated
Comment on lines +94 to +109
self._reject_seed_checkpoint_without_save()

def _reject_seed_checkpoint_without_save(self) -> None:
"""Reject a seed checkpoint that cannot write.

Recipes assign ``create_seed_checkpoint`` after the config object is
built, so ``__post_init__`` alone does not see that assignment.
``Trainer.__init__`` runs this again on the final config.
"""
if not self.create_seed_checkpoint:
return
if self.checkpointer is None or self.checkpointer.load_only:
raise ValueError(
"create_seed_checkpoint requires a checkpointer with "
"load_only=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.

Agree with @tianyu-l. Once Trainer.__init__ calls config.__post_init__() (see the comment at line 173), __post_init__ is this method's only caller. Its docstring then only explains the second call site, which goes away. Inline it:

Suggested change
self._reject_seed_checkpoint_without_save()
def _reject_seed_checkpoint_without_save(self) -> None:
"""Reject a seed checkpoint that cannot write.
Recipes assign ``create_seed_checkpoint`` after the config object is
built, so ``__post_init__`` alone does not see that assignment.
``Trainer.__init__`` runs this again on the final config.
"""
if not self.create_seed_checkpoint:
return
if self.checkpointer is None or self.checkpointer.load_only:
raise ValueError(
"create_seed_checkpoint requires a checkpointer with "
"load_only=False."
)
if self.create_seed_checkpoint and (
self.checkpointer is None or self.checkpointer.load_only
):
raise ValueError(
"create_seed_checkpoint requires a checkpointer with "
"load_only=False."
)

The existing test (test_seed_checkpoint_requires_a_saving_checkpointer) calls config.__post_init__() directly, so it keeps working unchanged.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Inlined into Trainer.Config.__post_init__ (29334a663). The test still calls config.__post_init__() directly.

@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@claude
I don't necessarily agree with either of your point

apply_overrides runs only when config.override.imports is non-empty (trainer.py:160). The case this check targets has no overrides: llama3_debugmodel_seed_checkpoint (tests/integration_tests/features.py:839-840) and scripts/_checkpoint_test_config.py:108 just assign create_seed_checkpoint = True to a config that already exists. A hook inside apply_overrides would miss them.

I think it could never be absolutely safe. E.g. even after the validation, users could ad hoc change the dataclass and violate the constraint. Compared with manually inserting post_init everywhere, I feel putting it in apply_overrides is somewhat more principled.

apply_overrides is shared with the RL controller, rl/generate.py, precompile_main.py, and the torchft trainer, and its config_root is typed as a plain Configurable.Config. Revalidation there would change every one of those callers.

I would argue that in those scenarios, we should also re-do the validation?

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 21s —— View job


Request changes (agrees with @tianyu-l on apply_overrides): I withdraw point 2 and agree with most of point 1. Recipe-assigned fields still need a second __post_init__() call at the end of ConfigLoader.load. 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: Request changes (agrees with @tianyu-l on apply_overrides) -- I withdraw point 2 and agree with most of point 1. But if apply_overrides is the only place that revalidates, this PR's check never runs for the seed recipes it targets. A second call is needed where the recipe's output enters the framework: ConfigLoader.load.

Point 2 (revalidate for RL, generate, precompile, torchft): correct, I withdraw it

"It changes every caller" is the reason to do it, not a cost. The root configs those callers pass have __post_init__s that only validate. I checked Controller.Config.__post_init__ (torchtitan/rl/controller/controller.py:336), which RL train and rl/generate.py both use. It assigns nothing, so running it again is safe. One wrinkle: Configurable.Config (torchtitan/config/configurable.py:43) defines no __post_init__, and the toy configs in tests/unit_tests/cpu/config/test_override.py don't either. A bare config_root.__post_init__() would raise AttributeError there. Give the base Config a no-op __post_init__.

Point 1 (apply_overrides is more principled): partly correct

No placement is airtight, and a function that mutates the tree should validate what it leaves behind. The catch is that recipe assignments aren't ad hoc edits made after validation. They are how configs get written in this repo: a factory builds a config and then assigns fields (tests/integration_tests/features.py:836-842, scripts/_checkpoint_test_config.py:108). The framework first receives that output at loader.py:134, and _apply_launch_options (loader.py:52) changes it again. Neither recipe uses override imports, and every caller guards with if config.override.imports:. So with only apply_overrides revalidating, create_seed_checkpoint=True with checkpointer=None still logs "Created seed checkpoint" without saving anything.

Both places that change a config after construction are framework mechanisms, not per-trainer call sites. Validate at both:

# configurable.py, Configurable.Config
def __post_init__(self) -> None:
    pass

# override.py, end of apply_overrides
config_root.__post_init__()

# loader.py, end of ConfigLoader.load (after recipe + launch options)
config.__post_init__()

Every entry point gets both calls: train.py:32, rl/train.py:50, rl/generate.py:100, precompile_main.py:335, and flux infer.py:102. Trainer.__init__ can then drop the manual validate_model_training_config(...) (trainer.py:163-170) and _reject_seed_checkpoint_without_save() (trainer.py:173). The helper gets inlined into __post_init__ as you suggested. The net LoC should go down. One thing is lost: a Trainer built directly, without ConfigLoader (unit tests, scripts), no longer gets the post-recipe check. That is the ad hoc case you describe, so I think the trade is fine.

Must fix (missed)

  1. torchtitan/config/transform/README.md:194-195 says "The trainer validates it again after command-line overrides." Update it to name the two places above.
  2. The description's "What changed" section still describes the manual call in Trainer.__init__, and "Summary (human-written)" is still empty.

Not verified: a recipe whose config is invalid until an override replaces a node would now fail at ConfigLoader.load. I didn't find one, but CI is what would surface it. A maintainer still needs to review, since this touches torchtitan/config/ and torchtitan/trainer.py.

Recipe assignments and overrides land after the first __post_init__.
Run it again in Trainer.__init__ and inline the seed-checkpoint check.
@YeonwooSung

Copy link
Copy Markdown
Contributor Author

Applied in 29334a6. The check is inlined in Trainer.Config.__post_init__, and Trainer.__init__ calls config.__post_init__() after overrides.

Comment thread torchtitan/trainer.py Outdated
# Assignments after construction (seed checkpoint, overrides) are
# invisible to the first __post_init__. apply_overrides does not run
# when override.imports is empty, so re-validate here.
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.

Instead, can we follow what claude says and do

# override.py, end of apply_overrides
config_root.__post_init__()

# loader.py, end of ConfigLoader.load (after recipe + launch options)
config.__post_init__()

This also helps https://github.com/pytorch/torchtitan/blob/main/torchtitan/rl/controller/controller.py#L438

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Moved in a9dc3af. ConfigLoader.load calls config.__post_init__() after launch options, and apply_overrides calls it after replacements. Configurable.Config.__post_init__ is a no-op, so a config that does not define its own still takes the call. Trainer.__init__ no longer calls it.

The seed recipes assign create_seed_checkpoint and leave override.imports empty, so the loader is the call that sees them. The controller call at controller.py:438 revalidates through apply_overrides, and so do rl/generate.py, precompile, and torchft. A Trainer built in-process, without ConfigLoader and without imports, still does not.

@tianyu-l tianyu-l 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.

last nit

Comment on lines +48 to +49
def __post_init__(self) -> None:
"""Validate this config. A second call must leave a valid config unchanged."""

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.

I don't think we need this? A dataclass comes with it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

A dataclass does not define __post_init__. The generated __init__ calls it only when a class in the MRO already does.

@dataclass(kw_only=True, slots=True)
class Bare:
    x: int = 0

Bare().__post_init__()  # AttributeError: 'Bare' object has no attribute '__post_init__'

ComponentA.Config, ParentComponent.Config, and Root.Config in tests/unit_tests/cpu/config/test_override.py inherit Configurable.Config and do not define their own. apply_overrides calls config_root.__post_init__() on those roots, and ConfigLoader.load does the same. Without this method those calls raise. A subclass that defines its own does not call super(), so this body does not run for it.

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.

A dataclass does not define post_init.

I might have missed something, but dataclass does define __post_init__.
https://docs.python.org/3/library/dataclasses.html#dataclasses.__post_init__

@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@claude review again

check my latest comments

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve. The author is right on the last nit: @dataclass doesn't add a __post_init__, so the base no-op is needed. 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 -- Every earlier must-fix item is resolved at HEAD. On the last nit, the author is right: @dataclass does not create a __post_init__, so the base no-op at configurable.py:48-49 is needed.

On @tianyu-l's latest comment (torchtitan/config/configurable.py:49)

Mistaken. Keep the method. The docs section you linked describes a hook that you write yourself. It doesn't describe a default that @dataclass adds. The docs say: "The generated __init__() code will call a method named __post_init__(), if __post_init__() is defined on the class." CPython does the same thing: _process_class computes has_post_init = hasattr(cls, _POST_INIT_NAME) and adds the call to __init__ only when that is true. It never adds the attribute. So for a config that defines no __post_init__, anywhere in its MRO, the new calls fail with AttributeError:

@dataclass(kw_only=True, slots=True)
class Root(Configurable.Config):          # e.g. Root/ParentComponent in test_override.py
    child: ComponentA.Config
apply_overrides(OverrideConfig(), Root(...))
# without the base no-op: AttributeError at config_root.__post_init__()  (override.py:507)
# with it: no-op

The two new unconditional calls (override.py:507, loader.py:56) accept any Configurable.Config root, so the base class is the right place for a default. The alternative is getattr(config_root, "__post_init__", None) at each call site, which is worse. Defining it on the base also means every subclass's generated __init__ now calls a method. When the subclass has no override, that method is an empty function, so the cost is negligible. No in-repo __post_init__ calls super().__post_init__() (I grepped), so subclasses with their own method don't change.

Earlier items, now resolved

  • Revalidation is now in apply_overrides and at the end of ConfigLoader.load, as you asked. The manual call in Trainer.__init__ and the duplicate validate_model_training_config call are gone.
  • The transform/README.md text names both calls.
  • The check is inlined into Trainer.Config.__post_init__, and the helper is gone.
  • The description is updated, and the human-written summary is filled in.

Should consider

  • The two new calls revalidate only the root config. Nested __post_init__s (for example ParallelismConfig) don't rerun when a recipe edits a nested field after construction. That's fine for this PR, because the seed-checkpoint check lives on the root. Just don't read "validates again" in the README as covering the whole tree.

Not verified: I couldn't run Python in this environment. The dataclass behavior above comes from the stdlib docs and source, and the author's snippet shows the same result. A maintainer has already approved. This PR touches torchtitan/config/ and torchtitan/trainer.py.

@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve: no new commits since the last review, and every earlier must-fix item is resolved at HEAD (a9dc3afae). 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 -- Nothing has been pushed since the last automated review. HEAD is still a9dc3afae, and none of the earlier must-fix items are open.

What this PR does. main() now raises ValueError when parallelism_context.world_size != 1 for a seed checkpoint, so it no longer relies on asserts over os.environ["WORLD_SIZE"]. Trainer.Config.__post_init__ rejects checkpointer=None and load_only=True when create_seed_checkpoint is set. The root config's __post_init__ runs again at the end of ConfigLoader.load and of apply_overrides. A no-op base method on Configurable.Config keeps those calls safe on configs that define nothing to check.

Example.

config = llama3_debugmodel()
config.checkpointer = CheckpointManager.Config(load_only=True)
config.create_seed_checkpoint = True     # recipe assignment, no override imports
# main:  nothing saved, "Created seed checkpoint" logged
# PR:    ConfigLoader.load -> ValueError: create_seed_checkpoint requires a
#        checkpointer with load_only=False.

Since the last review

  • No new commits. The configurable.py:48 thread is settled. @dataclass only calls a __post_init__ that the class already has, and it never creates one, so the base no-op stays.
  • Re-checked at HEAD:
    • Every root config that the two new calls re-run only validates and never assigns to its own fields: TrainingEngine.Config, Trainer.Config, GraphTrainer.Config, FluxTrainer.Config, and Controller.Config.
    • Both seed callers end up with a valid config. llama3_debugmodel_seed_checkpoint (tests/integration_tests/features.py:839) sets a default CheckpointManager.Config(). scripts/_checkpoint_test_config.py sets load_only only in "load" mode.
Details
  • Trainer.__init__ no longer calls validate_model_training_config again. A Trainer that is built in-process, with no ConfigLoader and no override imports, therefore skips revalidation after post-construction edits. The description lists this under Known issues, and it is the ad hoc case the maintainer accepted.
  • Revalidation still covers only the root. Nested __post_init__s (e.g. ParallelismConfig) don't rerun when a recipe edits a nested field after construction. That doesn't affect this PR, because the seed check lives on the root.

Not verified: I didn't run a seed-checkpoint launch or the CPU tests here. This touches torchtitan/config/, torchtitan/trainer.py, and torchtitan/train.py, and a maintainer has already approved.

@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Thanks. LGTM.

Is CPU failure related?

Configurable.Config.__post_init__ sits ahead of PretrainedConfig in the
MRO, so leftover kwargs such as attn_implementation raised TypeError.
@YeonwooSung

Copy link
Copy Markdown
Contributor Author

Yes. build-test job 125731353312 fails while collecting tests/unit_tests/cpu/recipes/test_debug_config_defaults.py.

HFTransformerModel.Config calls PretrainedConfig.__init__ with attn_implementation. That init calls self.__post_init__(**leftover). Configurable.Config.__post_init__(self) is ahead of PretrainedConfig in the MRO, so the call raised TypeError: unexpected keyword argument 'attn_implementation'.

Fixed in f33054c. HFTransformerModel.Config.__post_init__ forwards those kwargs to PretrainedConfig.__post_init__. The base method stays a no-op with no extra parameters.

tianyu-l added a commit that referenced this pull request Nov 3, 2026
…skill fixes (#5759)

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

This PR adapts learnings from recent code review experience from me.

## Why
Three problems with the review automation on `main`:

1. **Area routing.** Several areas lack the right PoCs, `cuda_graph` is
named after files that were renamed to `accelerator_graph`, and the RL
vLLM attention code has no area of its own because it is spread across
`torchtitan/rl/generator/vllm/`.
2. **The bot approves one-sided designs.** On #5689 the bot approved a
generator-only fused GDN projection. That design needed `free_storage`
on FSDP-owned params, a refresh hook, a private
`torch._C._accelerator_setAllocatorSettings` call, and an ordering
invariant. A native fused parameter shared with the trainer would delete
all of that, and the bot only said so after being asked to review the
maintainer's review. The first two runs on #5689 didn't load the
`pr-review` skill at all.
3. **A stale REQUEST_CHANGES.** On #5313 the bot wrote "Approve" in a
"review my review" run but submitted `COMMENT`, as the skill instructed
for that mode. Its earlier `REQUEST_CHANGES` stayed and kept blocking
the PR.

**Example (area matching).** A PR touching
`rl/generator/vllm/attention/gdn.py`, `rl/generator/vllm/worker.py` and
`tests/rl/x.py`:

| | Areas matched | Requested |
| --- | --- | --- |
| Before (any prefix match) | `rl` (3) | `felipemello1, pzhan9, wwwjn`
(cap of 3 used up) |
| After (longest prefix) | `rl` (2), `rl_attention` (1) | `felipemello1,
pzhan9, wwwjn, liangel-02, drisspg`, minus the author and
already-requested code owners, capped at 3 |

## What changed
- **`.github/area_reviewers.yml`**
  - `attention` += `fegin`, `liangel-02`
  - `quantization` += `vkuzo`
  - `context_parallel` += `liangel-02`, `drisspg`
  - `cuda_graph` -> `accelerator_graph`, += `sanketpurandare`
- new `rl_attention` (`torchtitan/rl/generator/vllm/attention/`):
`liangel-02`, `drisspg`
- **`.github/workflows/area_reviewers.yml`:** each changed file counts
toward the area with its longest matching prefix, so a subarea wins over
its parent.
- **Mechanical, skim:** `attention.py`, `mla.py`, `gdn.py`, `kda.py`,
`linear_attention.py` move from `torchtitan/rl/generator/vllm/` to
`torchtitan/rl/generator/vllm/attention/` (mirrors
`models/common/attention/`). The only other changes are import updates
in `model_wrapper.py`, `registry.py`, `worker.py`, the moved files, and
the RL tests.
- **`.claude/skills/pr-review/`**
- New gate question 7, "one-sided design": an optimization added to only
one side (generator vs. trainer, inference vs. training, one model or
backend) must be compared against the shared version and what it would
delete. Workaround machinery counts as evidence for the shared version:
private APIs, storage tricks on FSDP-owned tensors, refresh hooks,
copies kept in sync, ordering invariants.
- If the shared version would delete that machinery, the finding is the
lead must-fix with Request changes or Needs discussion, never a TODO.
Same item added to `review-checklist.md`.
- The review event always matches the verdict line in every mode.
`COMMENT` is used only for answers with no verdict.
- The fallback body file is written in the working directory; writes to
`/tmp` are denied.
- **`.github/workflows/claude-code.yml`**
- Allow `mcp__github__create_and_submit_pull_request_review`; its
absence made the #5689 "review my review" run fail to post.
  - The prompt says invoking the `pr-review` skill is the first action.

## Numerics
No computation change. The RL change only moves files and updates
imports.

## Testing
- `pytest tests/rl/unit_tests/cpu/test_vllm_wrapper.py
tests/rl/unit_tests/cpu/test_vllm_registry.py`: 25 passed.
- All moved modules plus `model_wrapper`, `registry` and `worker`
import. The GDN GPU tests collect (23 tests) but were not run on GPU.
- I checked the area-matching logic with a local node script on the
example above.
- The skill and workflow changes take effect only after merge (the
workflows run from `main`).
@tianyu-l
tianyu-l merged commit 01586df into pytorch:main Nov 3, 2026
@YeonwooSung
YeonwooSung deleted the pr/validate-seed-checkpoint branch November 4, 2026 00:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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