Skip to content

Support checkpointing with parallelism.storage=FlexShardConfig() - #6012

Open
anshul-si wants to merge 9 commits into
gh/anshul-si/23/basefrom
gh/anshul-si/23/head
Open

anshul-si wants to merge 9 commits into
gh/anshul-si/23/basefrom
gh/anshul-si/23/head

Conversation

@anshul-si

@anshul-si anshul-si commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

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's
state 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 CheckpointManager save and load
FlexShard 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
CheckpointableTensor protocol, four attributes on the tensor (global_shape,
global_offsets, local_offsets, local_sizes), but each state dict passed to DCP
has to carry them. Three changes make FlexShard's state dicts carry them:

  • Model. After flex_shard(), FlexShardConfig.apply_to_decoder calls the new
    declare_state_dict_layouts(model), which registers a state_dict post-hook that
    calls flex_shard's set_state_dict_global_layouts. model.state_dict() then
    declares its layouts, as FSDP2's DTensors do. CheckpointManager doesn't change:
    ModelWrapper takes every state dict it saves or loads from model.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 over edp_shard, so
    EP needs nothing more. The earlier revision of this PR declared that EP split itself.
  • Optimizer. OptimizersContainer calls the new
    declare_optimizer_state_layouts(optimizer, model) for each optimizer it builds. If
    FlexShard sharded the model part (the chunked-loss PR's holds_flex_shard_params), it
    registers flex_shard's register_optimizer_checkpoint_hook, so
    optimizer.state_dict() declares each Adam/AdamW state's layout on the live state
    tensors. step gets no layout, so it is saved as replicated, as FSDP2 saves it. The
    container 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_dict
    post-hook (_save_host_lr). The model-side _register_optimizer_hooks would keep the
    container unaware of FlexShard, but none of its overrides calls super(), so a
    registration there would silently not run for Qwen3 and GPT-OSS. flex_shard raises
    NotImplementedError for optimizers other than Adam and AdamW. Only those two reach
    it in-tree, since DistMuon is rejected.
  • bf16 exports. export_state_dict keeps a tensor's CheckpointableTensor
    attributes through its dtype cast. .to() returns a new tensor without them, so a
    last_save_model_only export with export_dtype="bfloat16" would save each rank's
    shard as the whole tensor.

FlexShardConfig.validate_trainer replaces its rejection of all checkpointing with
rejections 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 the
    staged state dict to the save process through torch.multiprocessing, whose
    rebuild_tensor drops the attributes. Threaded async (async_mode="async") keeps
    them, since StateDictStager copies each tensor's __dict__.
  • Checkpointers other than CheckpointManager, i.e. TorchCheckpointingManager, whose
    torch_checkpointing resharder reads only DTensor placements.
  • checkpointer.initial_load_in_hf and checkpointer.last_save_in_hf. The state dict
    adapters need DTensor parameters. Hugging Face support comes later in the stack.
    EMA stays rejected. CheckpointManager in sync and threaded async mode, bf16 exports
    and initial_load_path, for example to continue from an FSDP2 checkpoint, work. Two
    TODOs remain: the state_dict post-hook should come from flex_shard, as a FlexShard
    module's state_dict() that declares its layouts, and the rejections go as DCP and
    torch_checkpointing keep the layouts.

The parity test file gains test_checkpoints_match_fsdp2, on the Qwen3 MoE debug model
with ep=2. FSDP2 trains three AdamW steps through an OptimizersContainer, then its
CheckpointManager saves a full checkpoint and a bf16 export. A FlexShard model, which
starts from its own initialization and so from different weights, loads FSDP2's
checkpoint through initial_load_path and saves both again. Each FlexShard checkpoint
must 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 give
the 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 ep and edp_shard, a load, a save after a load, and the export. Since the
checkpoints are the same, FSDP2
loads FlexShard's as its own. In CI the test runs on 4 GPUs, where ep=2 leaves
edp_shard=2. It passes on 2 GB200 GPUs with world_size set 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], for
layers.0.attention.k_norm.weight. Without the export's attribute copy, the FlexShard
export holds tok_embeddings.weight as one chunk, one rank's shard as the whole
tensor, where FSDP2's holds two. A one-off run with the FlexShard saves in threaded
async mode also matched FSDP2's checkpoint. _train takes an optional optimizer for
the test.

A CPU test, test_flex_shard_rejects_checkpointers_that_drop_shard_layouts, checks
that TrainingEngine.Config.__post_init__ accepts CheckpointManager and rejects
each 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's
cast, and OptimizersContainer's call to declare_optimizer_state_layouts, which
returns for a model FlexShard didn't shard. A DTensor and a plain tensor aren't
CheckpointableTensors (checked with isinstance), so FSDP2's exports are cast as
before. No training code changes.

Co-authored-by: Wei Feng [email protected]

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@anshul-si

Copy link
Copy Markdown
Contributor Author

@claude review this pr

@claude

claude Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

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.

@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 -- 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

  1. The description doesn't match the code.
    • "Expert parallelism (flex_shard_fsdp.py) ... declares the EP layout with set_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_decoder registers a state_dict post-hook": the hook is registered in _apply_flex_shard (fsdp.py:640) through declare_state_dict_layouts.
    • Testing lists test_checkpoints_across_backends (Llama 3, ep=1) and ..._with_expert_parallelism. The diff has a single test_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_layouts with 5 cases. The description says test_flex_shard_checkpointer with 7 cases that accept async and bf16 export. Only the default CheckpointManager.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.
  2. 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: threaded async_mode="async" is newly allowed but untested (inline). close() already waits for the pending save (base.py:430-431), so adding async_mode="async" to the FlexShard build(...) 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 for ModelWrapper's rebuilt cache after a load (base.py:158), because _get_state_dict always goes through model.state_dict().
  • Optimizer path. get_flat_optim_state_dict re-keys optim.state_dict() but keeps the same tensor objects (optim/utils.py:98-108), so the attributes set by the hook reach DCP. After load_flat_optim_state_dict, the next state_dict() call declares the layouts on the new live tensors.
  • Core coupling. The declare_optimizer_state_layouts call in OptimizersContainer.__init__ is the one FlexShard-specific line in a core component. optimizer.py already imports FlexShard's DistMuon, and the description explains why _register_optimizer_hooks doesn't work (the overrides don't call super()). I'm not flagging it.
  • Validation. initial_load_in_hf/last_save_in_hf live on BaseCheckpointManager.Config (base.py:653,662), so checking them outside the isinstance branch is safe for TorchCheckpointingManager.Config. preserve_dtype_params is already rejected under FlexShard, so export_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.

Comment on lines +392 to +399
# 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'")

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.

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.

Comment on lines +391 to +397
# 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,
)

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.

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]
[ghstack-poisoned]
@anshul-si

Copy link
Copy Markdown
Contributor Author

@claude review the pr

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. The 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_dict post-hook on the model makes the local shards carry DCP's CheckpointableTensor layout attributes. flex_shard's optimizer checkpoint hook does the same for the optimizer states.
  • export_state_dict copies those attributes through the bf16 cast.
  • async_with_pinned_mem, TorchCheckpointingManager and 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

  1. 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).
  2. The TODO links above.

Questions

  • .github/workflows/unit_test_gpu.yaml:97 pins flex_shard at d6bb546. Does that commit export set_state_dict_global_layouts and register_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 when CheckpointManager built the wrapper after init_weights. The cache is rebuilt through the hook after a load (base.py:158). The export path calls model.state_dict() directly (dcp.py:643). So every DCP save and load path sees the layouts.
  • Validation. TorchFTCheckpointManager.Config subclasses CheckpointManager.Config, so it passes the isinstance check. TorchFT's trainer is still rejected further down (flex_shard_fsdp.py:400-407). EMA (an OptimizersContainer subclass) is still rejected through optim.ema.
  • FSDP2 path. declare_optimizer_state_layouts returns early when flex_shard isn't imported (holds_flex_shard_params checks sys.modules). export_state_dict only copies attributes for a CheckpointableTensor.
  • Minor (not blocking). declare_state_dict_layouts has one caller, _apply_flex_shard, which already imports from flex_shard lazily (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,

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.

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.

[ghstack-poisoned]
@anshul-si anshul-si changed the title Support checkpointing with parallelism.fsdp_backend=FlexShardConfig() Support checkpointing with parallelism.fsdp_backend=FlexShardBackend.Config() Nov 25, 2026
[ghstack-poisoned]
@anshul-si anshul-si changed the title Support checkpointing with parallelism.fsdp_backend=FlexShardBackend.Config() Support checkpointing with parallelism.storage=FlexShardConfig() Nov 30, 2026

This branch has not been deployed

No deployments
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.

1 participant