Repository navigation
Conversation
|
@claude review this pr |
|
Claude finished @anshul-si's task in 4m 17s —— View job Request changes: the PR description doesn't match the code. It describes an expert-parallelism change and tests that aren't in this diff, and the TODOs that work around upstream gaps have no issue links. See the review. |
There was a problem hiding this comment.
Verdict: Request changes -- I found no defect in the code. But the description's "What changed" and "Testing" sections describe a different revision: a change that isn't in this diff, and tests that don't exist. A maintainer can't check the stated evidence against the code.
What this PR does. It lifts FlexShard's blanket ban on checkpointing. A state_dict post-hook on the model and flex_shard's optimizer checkpoint hook make the local shards carry DCP's CheckpointableTensor layout attributes. export_state_dict copies those attributes through the bf16 cast. async_with_pinned_mem, TorchCheckpointingManager and HF load/save are still rejected.
Example. Qwen3 MoE debug, ep=2, dp_shard=world_size, CheckpointManager with the default async_mode="disabled":
before: fsdp_backend=FlexShardConfig() + any checkpointer -> ValueError("... checkpointing ...")
after: FlexShard loads FSDP2's step-3 (model + AdamW). Its re-saved step-3 and
exports/step-3 (bf16) have the same keys, sizes, dtypes, non-empty chunks
and values as FSDP2's.
Must fix
- The description doesn't match the code.
- "Expert parallelism (
flex_shard_fsdp.py) ... declares the EP layout withset_global_layout": that code is already on the base (fsdp.py:525-544, unchanged here). This PR adds no EP change, so the "Reverted: the EP layout -> fails only the EP test" row also doesn't apply. - "
apply_flex_shard_to_decoderregisters astate_dictpost-hook": the hook is registered in_apply_flex_shard(fsdp.py:640) throughdeclare_state_dict_layouts. - Testing lists
test_checkpoints_across_backends(Llama 3,ep=1) and..._with_expert_parallelism. The diff has a singletest_checkpoints_match_fsdp2(Qwen3 MoE,ep=2). That test:- covers sync saves and the bf16 export, but not threaded async;
- never loads a FlexShard checkpoint into FSDP2;
- trains no steps after the load, so it can't check steps 3-5 or a step-6 save;
- doesn't register the model's optimizer hooks.
- The CPU test is
test_flex_shard_rejects_checkpointers_that_drop_shard_layoutswith 5 cases. The description saystest_flex_shard_checkpointerwith 7 cases that accept async and bf16 export. Only the defaultCheckpointManager.Config()case is accepted. - The Numerics and Testing sections say some rows ran on an "earlier revision". Please say which results were produced at HEAD.
- "Expert parallelism (
torchtitan/distributed/flex_shard_fsdp.py:392-399(and:255): the upstream-workaround TODOs have no issue links (inline).
Should consider
tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py:391-397: threadedasync_mode="async"is newly allowed but untested (inline).close()already waits for the pending save (base.py:430-431), so addingasync_mode="async"to the FlexShardbuild(...)is enough.
Details
- Gate. The problem is real: the base rejects any checkpointer under FlexShard. Fixing it at the state-dict layer, rather than in
dcp_save/_flattened_model_states_sd, is the right place. It holds forModelWrapper's rebuilt cache after a load (base.py:158), because_get_state_dictalways goes throughmodel.state_dict(). - Optimizer path.
get_flat_optim_state_dictre-keysoptim.state_dict()but keeps the same tensor objects (optim/utils.py:98-108), so the attributes set by the hook reach DCP. Afterload_flat_optim_state_dict, the nextstate_dict()call declares the layouts on the new live tensors. - Core coupling. The
declare_optimizer_state_layoutscall inOptimizersContainer.__init__is the one FlexShard-specific line in a core component.optimizer.pyalready imports FlexShard'sDistMuon, and the description explains why_register_optimizer_hooksdoesn't work (the overrides don't callsuper()). I'm not flagging it. - Validation.
initial_load_in_hf/last_save_in_hflive onBaseCheckpointManager.Config(base.py:653,662), so checking them outside theisinstancebranch is safe forTorchCheckpointingManager.Config.preserve_dtype_paramsis already rejected under FlexShard, soexport_state_dict's promote branch doesn't apply here.
Not verified: the GPU tests and loss comparisons (no GPU, and flex_shard/torch aren't inspectable here); that isinstance(..., CheckpointableTensor) is False for DTensor (the FSDP2 bf16 export in the new test covers it); and that set_state_dict_global_layouts ignores buffers. A maintainer still needs to review, since this touches core checkpointer and optimizer code.
| # TODO: Allow once torch_checkpointing's resharder reads the | ||
| # layouts, not only DTensor placements. | ||
| unsupported.append("checkpointers other than CheckpointManager") | ||
| elif checkpointer.async_mode == "async_with_pinned_mem": | ||
| # TODO: Allow once DCP's process-based async save keeps the | ||
| # layouts, which torch.multiprocessing drops on the way to the save | ||
| # process. | ||
| unsupported.append("checkpointer.async_mode='async_with_pinned_mem'") |
There was a problem hiding this comment.
These two TODOs work around upstream gaps: torch_checkpointing's DefaultResharder only reads DTensor placements, and torch.multiprocessing's rebuild_tensor drops the CheckpointableTensor attributes. Neither one links an upstream issue. The PR description's table lists "pytorch/pytorch issue" and "meta-pytorch/torch_checkpointing issue" as the TODOs, but the code has no links. CLAUDE.md requires a link for every upstream workaround, because without one nobody can tell when the ban can be lifted. Please file the issues and add the URLs here. The same applies to the TODO: Drop once a FlexShard module's state_dict() declares its layouts at line 255, which needs a meta-pytorch/flex_shard issue.
| # gives it FSDP2's values. | ||
| flex, _, flex_optimizers, checkpointer = build( | ||
| FlexShardConfig(), | ||
| "flex", | ||
| initial_load_path=os.path.join(self.temp_dir, "fsdp2", "step-3"), | ||
| initial_load_model_only=False, | ||
| ) |
There was a problem hiding this comment.
validate_flex_shard_training now allows async_mode="async", on the grounds that StateDictStager copies __dict__ and so keeps the layout attributes. No test exercises that path. If a future stager change stops copying __dict__, async FlexShard saves would silently write each rank's shard as the whole tensor. That's exactly the failure this PR bans async_with_pinned_mem for. Passing async_mode="async" to this FlexShard build(...) would cover it at no extra CI cost, since _assert_equal_checkpoints already compares the result against FSDP2's checkpoint. You'd need to wait on the async save before close(). If that's not wanted, ban "async" as well until it's covered.
[ghstack-poisoned]
[ghstack-poisoned]
|
@claude review the pr |
|
Claude finished @anshul-si's task in 3m 2s —— View job Approve (please address the items before merging): the description now matches the code. Before merging, run the committed 4-GPU test and add the upstream TODO links. See the review. |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The description now matches the code, and I found no defect. What's left is a missing 4-GPU run of the committed test and the TODO links that were already requested.
What this PR does. It lifts FlexShard's blanket ban on checkpointing:
- A
state_dictpost-hook on the model makes the local shards carry DCP'sCheckpointableTensorlayout attributes. flex_shard's optimizer checkpoint hook does the same for the optimizer states. export_state_dictcopies those attributes through the bf16 cast.async_with_pinned_mem,TorchCheckpointingManagerand HF load/save are still rejected, at config time.
Example. Qwen3 MoE debug, ep=2, CheckpointManager with the default async_mode="disabled":
before: fsdp_backend=FlexShardConfig() + any checkpointer -> ValueError("... checkpointing ...")
after: FlexShard loads FSDP2's step-3 (model + AdamW). Its re-saved step-3 and
exports/step-3 (bf16) have the same keys, sizes, dtypes, non-empty chunks
and values as FSDP2's.
Since the last review
- Resolved: the description now matches the diff. It covers the hook in
_apply_flex_shard,test_checkpoints_match_fsdp2, the 5-case CPU test, and which results come from this revision. - Still open:
torchtitan/distributed/flex_shard_fsdp.py:232,375,379. The three upstream-workaround TODOs still have no issue links. The description says "issue links to be added". This is a small edit, but CLAUDE.md requires the links before merge. - Still open (should consider): no test covers threaded
async_mode="async", though it's newly allowed. The description now records a one-off run, but nothing in CI would catch a regression.
Must fix
tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py:384: the test as committed (world_size=4,edp_shard=2) hasn't run at this revision. CI skipped GPU unit tests on this PR (inline).- The TODO links above.
Questions
.github/workflows/unit_test_gpu.yaml:97pins flex_shard atd6bb546. Does that commit exportset_state_dict_global_layoutsandregister_optimizer_checkpoint_hook? If not, the multi-GPU job fails with an ImportError once this lands. Bump the pin in this PR if needed.
Details
- Cache in
ModelWrapper.state_dict()returns the tensors cached at construction (base.py:131,140-150). They carry the layouts, because the post-hook already ran whenCheckpointManagerbuilt the wrapper afterinit_weights. The cache is rebuilt through the hook after a load (base.py:158). The export path callsmodel.state_dict()directly (dcp.py:643). So every DCP save and load path sees the layouts. - Validation.
TorchFTCheckpointManager.ConfigsubclassesCheckpointManager.Config, so it passes theisinstancecheck. TorchFT's trainer is still rejected further down (flex_shard_fsdp.py:400-407).EMA(anOptimizersContainersubclass) is still rejected throughoptim.ema. - FSDP2 path.
declare_optimizer_state_layoutsreturns early whenflex_shardisn't imported (holds_flex_shard_paramscheckssys.modules).export_state_dictonly copies attributes for aCheckpointableTensor. - Minor (not blocking).
declare_state_dict_layoutshas one caller,_apply_flex_shard, which already imports fromflex_shardlazily (fsdp.py:512). Inlining the hook there would remove a cross-module helper and an__all__entry.
Not verified: the GPU tests (no GPU here), whether the pinned flex_shard commit has the two APIs, and whether isinstance(DTensor, CheckpointableTensor) is False (the FSDP2 export in the test covers it). This PR touches core checkpointer and optimizer code, so a maintainer still needs to review it.
| # edp_shard. | ||
| parallelism_context = ParallelismContext( | ||
| dp_replicate=1, | ||
| dp_shard=self.world_size, |
There was a problem hiding this comment.
TestFlexShardDecoder.world_size is 4 (line 73-75), so this runs with ep=2, edp_shard=2. The description says the test has passed at this revision only with world_size edited to 2 (edp_shard=1). This PR's GPU Unit Tests run was skipped (ghstack base), so the committed configuration hasn't run anywhere yet.
edp_shard=2 is the case the comment above says this test exists for: the routed experts' layout composes the EP split with the bucket's split over edp_shard. With edp_shard=1, the second split is a no-op, so the expert layouts are never really checked. Please run it on 4 GPUs at HEAD and put the result in the description. Otherwise the multi-GPU job could first fail after the stack lands on main.
Stack from ghstack (oldest at bottom):
Stacked on #5842, the expert-parallelism PR and the chunked-loss PR.
Summary (human-written)
Description
#5842 rejects checkpointing with
parallelism.storage=FlexShardConfig(),so a FlexShard run can't resume, and a run trained under FSDP2 can't continue under
FlexShard. Lifting the rejection alone would write corrupt checkpoints without an error.
FlexShard parameters are plain local shards, so
model.state_dict()and the optimizer'sstate dict hold local shards, and DCP saves a plain tensor as the whole tensor: every
rank writes its shard under the full parameter's key, and DCP's planner deduplicates
them as if they were replicated. This PR lets
CheckpointManagersave and loadFlexShard models, with the same checkpoints as FSDP2. As in #5842, nothing on the
FlexShard path creates a DTensor.
flex_shard declares where a local shard sits in the full tensor through DCP's
CheckpointableTensorprotocol, four attributes on the tensor (global_shape,global_offsets,local_offsets,local_sizes), but each state dict passed to DCPhas to carry them. Three changes make FlexShard's state dicts carry them:
flex_shard(),FlexShardConfig.apply_to_decodercalls the newdeclare_state_dict_layouts(model), which registers astate_dictpost-hook thatcalls flex_shard's
set_state_dict_global_layouts.model.state_dict()thendeclares its layouts, as FSDP2's DTensors do.
CheckpointManagerdoesn't change:ModelWrappertakes every state dict it saves or loads frommodel.state_dict(),including the one it takes again after a load, so no call site has to remember the
layouts. The routed experts' layouts compose the EP split that the expert-parallelism
PR declares before
flex_shard()with the expert bucket's split overedp_shard, soEP needs nothing more. The earlier revision of this PR declared that EP split itself.
OptimizersContainercalls the newdeclare_optimizer_state_layouts(optimizer, model)for each optimizer it builds. IfFlexShard sharded the model part (the chunked-loss PR's
holds_flex_shard_params), itregisters flex_shard's
register_optimizer_checkpoint_hook, sooptimizer.state_dict()declares each Adam/AdamW state's layout on the live statetensors.
stepgets no layout, so it is saved as replicated, as FSDP2 saves it. Thecontainer is the one place where an optimizer is paired with the model part holding
its parameters, which the hook needs, and it already registers a
state_dictpost-hook (
_save_host_lr). The model-side_register_optimizer_hookswould keep thecontainer unaware of FlexShard, but none of its overrides calls
super(), so aregistration there would silently not run for Qwen3 and GPT-OSS. flex_shard raises
NotImplementedErrorfor optimizers other than Adam and AdamW. Only those two reachit in-tree, since DistMuon is rejected.
export_state_dictkeeps a tensor'sCheckpointableTensorattributes through its dtype cast.
.to()returns a new tensor without them, so alast_save_model_onlyexport withexport_dtype="bfloat16"would save each rank'sshard as the whole tensor.
FlexShardConfig.validate_trainerreplaces its rejection of all checkpointing withrejections of the paths that would lose the layouts and treat every rank's shard as the
whole tensor, without an error:
checkpointer.async_mode="async_with_pinned_mem". DCP's process executor sends thestaged state dict to the save process through
torch.multiprocessing, whoserebuild_tensordrops the attributes. Threaded async (async_mode="async") keepsthem, since
StateDictStagercopies each tensor's__dict__.CheckpointManager, i.e.TorchCheckpointingManager, whosetorch_checkpointing resharder reads only DTensor placements.
checkpointer.initial_load_in_hfandcheckpointer.last_save_in_hf. The state dictadapters need DTensor parameters. Hugging Face support comes later in the stack.
EMA stays rejected.
CheckpointManagerin sync and threaded async mode, bf16 exportsand
initial_load_path, for example to continue from an FSDP2 checkpoint, work. TwoTODOs remain: thestate_dictpost-hook should come from flex_shard, as a FlexShardmodule's
state_dict()that declares its layouts, and the rejections go as DCP andtorch_checkpointing keep the layouts.
The parity test file gains
test_checkpoints_match_fsdp2, on the Qwen3 MoE debug modelwith
ep=2. FSDP2 trains three AdamW steps through anOptimizersContainer, then itsCheckpointManagersaves a full checkpoint and a bf16 export. A FlexShard model, whichstarts from its own initialization and so from different weights, loads FSDP2's
checkpoint through
initial_load_pathand saves both again. Each FlexShard checkpointmust equal FSDP2's: the same keys, global shapes and dtypes, the same non-empty chunks,
and bitwise-equal values (read back with
dcp_to_torch_save). Saving again would givethe same checkpoint even if two ranks had swapped their shards in the load, so right
after the load, each rank's FlexShard parameters and AdamW states must equal its FSDP2
ones too. That covers the model's parameters and AdamW states, the routed experts split
over
epandedp_shard, a load, a save after a load, and the export. Since thecheckpoints are the same, FSDP2
loads FlexShard's as its own. In CI the test runs on 4 GPUs, where
ep=2leavesedp_shard=2. It passes on 2 GB200 GPUs withworld_sizeset to 2 (edp_shard=1),in 39 s. Without the model's post-hook, it fails at the load: DCP reports a size
mismatch, saved
[128]against current[64], forlayers.0.attention.k_norm.weight. Without the export's attribute copy, the FlexShardexport holds
tok_embeddings.weightas one chunk, one rank's shard as the wholetensor, where FSDP2's holds two. A one-off run with the FlexShard saves in threaded
async mode also matched FSDP2's checkpoint.
_traintakes an optional optimizer forthe test.
A CPU test,
test_flex_shard_rejects_checkpointers_that_drop_shard_layouts, checksthat
TrainingEngine.Config.__post_init__acceptsCheckpointManagerand rejectseach of the four paths above, since each would corrupt checkpoints without an error. It
runs without flex_shard installed.
An earlier revision of this PR, with the same hooks, also resumed training at the
trainer level in both directions between the backends, with bitwise-equal loss and
grad norm over 20 steps, for the Llama 3 debug model and the Qwen3 MoE debug model with
ep=2, on 2 GB200 and 4 GB300 GPUs.The FSDP2 path doesn't change. It runs two of the changed lines:
export_state_dict'scast, and
OptimizersContainer's call todeclare_optimizer_state_layouts, whichreturns for a model FlexShard didn't shard. A DTensor and a plain tensor aren't
CheckpointableTensors (checked withisinstance), so FSDP2's exports are cast asbefore. No training code changes.
Co-authored-by: Wei Feng [email protected]