Repository navigation
[train] Require one device for a seed checkpoint - #5313
Conversation
The launch check read WORLD_SIZE, which pure fake mode does not set. Use the initialized process-group world size and raise ValueError.
|
|
|
@claude review |
There was a problem hiding this comment.
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
- 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. torchtitan/train.py:28-- Readtrainer.engine.parallelism_context.world_sizeand remove theis_initialized()branch, which can't fire. Then inline the check inmain().torchtitan/train.py:39-- Move the checkpointer check toTrainer.Config.__post_init__, and rejectload_only=Truethere as well.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 andcreate_seed_checkpointunder fake PG, andscripts/loss_compare.pylaunches the seed run with realtorchrunandNGPU=1. If fake mode only needs a clear error here, the motivation could say so.
Details
ParallelismContextvalidatesdp_replicate * dp_shard * cp * tp * pp == world_size. Soworld_size == 1already 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 withNGPUranks.get_world_size()therefore also returnsNGPU, so the PR's helper isn't wrong there.parallelism_context.world_sizeis still the canonical value, and it removes the need for theis_initializedguard. - 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 toTrainer.__init__beforeengine.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.
| 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}." | ||
| ) |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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.
| if config.checkpointer is None: | ||
| raise ValueError( | ||
| "Must configure checkpointer when creating a seed checkpoint." | ||
| ) |
There was a problem hiding this comment.
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."
)There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| ) | ||
| # 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() |
There was a problem hiding this comment.
instead of manually running this particular check, maybe we should force config.__post_init__ to be called in apply_overrides?
There was a problem hiding this comment.
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.
| ) | ||
| self._reject_seed_checkpoint_without_save() | ||
|
|
||
| def _reject_seed_checkpoint_without_save(self) -> None: |
There was a problem hiding this comment.
inline this and make it simpler
There was a problem hiding this comment.
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.
|
@claude review my review |
|
Claude finished @tianyu-l's task in 2m 6s —— View job Request changes (agrees with @tianyu-l): both comments are right, but the |
There was a problem hiding this comment.
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 buildOn the maintainer's comments
torchtitan/trainer.py:173(rerun__post_init__) -- Partly correct. Revalidating the whole tree is better than special-casing one check. Butapply_overridesruns only whenoverride.importsis non-empty, and it is shared with RL, precompile, and torchft. Putconfig.__post_init__()right after the overrides block inTrainer.__init__. That also replaces the duplicatedvalidate_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)
- 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_checkpointafter construction:tests/integration_tests/features.py:840andscripts/_checkpoint_test_config.py:108. Neither path uses override imports. torchtitan/experiments/torchft/trainer.py:170copiesTrainer.__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 afterconfig.build(), so a multi-rank seed launch does a full CPU model init before it raises. This is unchanged frommain, 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.
| # 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() |
There was a problem hiding this comment.
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_overridesruns only whenconfig.override.importsis non-empty (trainer.py:160). The case this check targets has no overrides:llama3_debugmodel_seed_checkpoint(tests/integration_tests/features.py:839-840) andscripts/_checkpoint_test_config.py:108just assigncreate_seed_checkpoint = Trueto a config that already exists. A hook insideapply_overrideswould miss them.apply_overridesis shared with the RL controller,rl/generate.py,precompile_main.py, and the torchft trainer, and itsconfig_rootis typed as a plainConfigurable.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.modelThe 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.
There was a problem hiding this comment.
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.
| 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." | ||
| ) |
There was a problem hiding this comment.
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:
| 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.
There was a problem hiding this comment.
Inlined into Trainer.Config.__post_init__ (29334a663). The test still calls config.__post_init__() directly.
|
@claude
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
I would argue that in those scenarios, we should also re-do the validation? |
There was a problem hiding this comment.
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)
torchtitan/config/transform/README.md:194-195says "The trainer validates it again after command-line overrides." Update it to name the two places above.- 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.
|
Applied in 29334a6. The check is inlined in |
| # 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__() |
There was a problem hiding this comment.
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__()
There was a problem hiding this comment.
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.
| def __post_init__(self) -> None: | ||
| """Validate this config. A second call must leave a valid config unchanged.""" |
There was a problem hiding this comment.
I don't think we need this? A dataclass comes with it.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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__
|
@claude review again check my latest comments |
There was a problem hiding this comment.
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-opThe 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_overridesand at the end ofConfigLoader.load, as you asked. The manual call inTrainer.__init__and the duplicatevalidate_model_training_configcall are gone. - The
transform/README.mdtext 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 exampleParallelismConfig) 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.
|
@claude review again |
There was a problem hiding this comment.
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:48thread is settled.@dataclassonly 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, andController.Config. - Both seed callers end up with a valid config.
llama3_debugmodel_seed_checkpoint(tests/integration_tests/features.py:839) sets a defaultCheckpointManager.Config().scripts/_checkpoint_test_config.pysetsload_onlyonly in"load"mode.
- Every root config that the two new calls re-run only validates and never assigns to its own fields:
Details
Trainer.__init__no longer callsvalidate_model_training_configagain. ATrainerthat is built in-process, with noConfigLoaderand 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.
|
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.
|
Yes.
Fixed in f33054c. |
…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`).
Summary (human-written)
A seed checkpoint has to be written from one rank, but
main()assertedint(os.environ["WORLD_SIZE"]) == 1. Pure fake mode never sets that variable, so the assert raisesKeyError, andpython -Oremoves it, so an 8-rank launch can save a sharded init and still log "Created seed checkpoint".checkpointer=Noneandload_only=Truealso skip the write and log success. The launch check now raisesValueErrorfromtrainer.engine.parallelism_context.world_size, andTrainer.Config.__post_init__rejects a checkpointer that will not save. Seed recipes setcreate_seed_checkpointafter the config is built and leaveoverride.importsempty, soConfigLoader.loadruns__post_init__again after launch options andapply_overridesruns it again after replacements.Why
A seed checkpoint has to be written from one rank.
main()used to assertint(os.environ["WORLD_SIZE"]) == 1. Pure fake never setsWORLD_SIZE, so that assert raisesKeyError. Underpython -Othe assert is removed, so an 8-rank launch can save a sharded init and still log "Created seed checkpoint".checkpointer=Noneandcheckpointer.load_only=Truealso skip the write (_should_savereturns false) and still log success.Example.
What changed
main()readstrainer.engine.parallelism_context.world_sizeand raisesValueErrorunless it is 1. The helper and theis_initialized()branch are gone. World size 1 already means every parallelism degree is 1.Trainer.Config.__post_init__rejects a missing checkpointer andload_only=Truewhencreate_seed_checkpointis set.Configurable.Config.__post_init__is a no-op, so every config can be re-entered.ConfigLoader.loadcalls it after the recipe and launch options.apply_overridescalls 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 callapply_overrides, so they revalidate there.torchtitan/config/transform/README.mdnames those two calls.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 theapply_overridescall. No distributed monkeypatch.HFTransformerModel.Config.__post_init__forwards leftover kwargs toPretrainedConfig.__post_init__.Configurable.Config.__post_init__is ahead ofPretrainedConfigin that MRO and takes no extra arguments, soattn_implementationraisedTypeErrorwhile collectingtests/unit_tests/cpu/recipes/test_debug_config_defaults.py.Alternatives considered
Trainer.__init__misses the RL controller, which applies overrides and never builds aTrainer.apply_overridesmisses the seed recipes. They assign the flag and leaveoverride.importsempty, and every caller skipsapply_overridesin 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(includingtest_revalidates_after_assignment) andtest_load_revalidates_recipe_assignmentspassed locally: 39 passed.test_seed_checkpoint_requires_a_saving_checkpointerstill calls__post_init__()forcheckpointer=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 samespmd_typeserror inside_load_config, before the new call. No seed-checkpoint launch was run here. CPUbuild-testjob 125731353312 failed that collection with theattn_implementationTypeError. 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_compatibilityalready rejectscreate_seed_checkpointunless the integration test setsuse_real_pg.scripts/loss_compare.pystarts the seed run undertorchrunwith one GPU.parallelism_context.world_sizeisNGPUin fake mode and the torchrun world size otherwise. ATrainerorFaultTolerantTrainerbuilt in-process, withoutConfigLoaderand without override imports, does not re-enter__post_init__.FaultTolerantTrainercopies__init__and does not add its own call.