Repository navigation
Conversation
[ghstack-poisoned]
[ghstack-poisoned]
|
@claude review this pr |
|
Claude finished @anshul-si's task in 2m 23s —— View job Approve -- please address the items before merging (empty human-written summary; consider folding the EMA test into |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging -- EMA's checkpoint state now declares the same FlexShard layouts that the model state dict uses, which unblocks EMA with FlexShard. The change is small and the FSDP2 path is unchanged. This PR touches components/optim/ema.py, so a maintainer still needs to review it.
What this PR does. On the base branch, validate_flex_shard_training rejects optim.ema. EMA copies of FlexShard params are plain local shards. Without a declared layout, DCP would save each rank's copy as the whole tensor. The new declare_param_layouts(model, pairs) copies each FlexShard param's GlobalLayout (from get_flex_shard_global_layouts) onto its EMA copies. EMA.state_dict() calls it before building the state dict. The rejection is removed and FLEX_SHARD_FSDP.md is updated.
Example. Qwen3 MoE debug model, dp_shard=2, optim.ema.decays=[0.9]:
before: config rejected ("optim.ema")
(with the rejection removed and no layouts declared: the saved
ema.state.tok_embeddings.weight.ema_params.decay_0p9 is one chunk,
one rank's [1024, 256] copy stored as the full [2048, 256] tensor)
after: the EMA copy is saved as 2 chunks at FSDP2's offsets, bit-equal to
FSDP2's checkpoint; FlexShard loads FSDP2's EMA in place, with or
without offload_to_cpu
Must fix
- PR description -- the "Summary (human-written)" section is empty. The author needs to fill it in. Agents don't write this section.
Should consider
tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py:713-- fold the EMA intotest_checkpoints_match_fsdp2rather than adding a separate 4-GPU test. That also covers EMA withtp=2, which nothing tests today (details inline).
Details
- Load paths. Without offloading,
Optimizer.load_state_dictkeeps the same tensors, because the.to()call in_process_value_according_to_param_policyreturns the same object when dtype and device already match. So the layout attributes survive a load. That makes re-declaring on everystate_dict()call a cheap safeguard, not a requirement. With offloading,_materialize_dtensorreturns the pinned CPU copy unchanged for non-DTensor params. DCP loads into it in place, and the latercopy_copies the tensor onto itself, which is harmless. - Tied weights and PP.
named_parameters(remove_duplicate=False)maps both tied FQNs to the same param object, and both carry the same layout.zip(self._param_optimizers, self.model_parts)handles each PP model part separately, using that part's own FQNs. - Buffers. Neither backend shards buffers, so
buffer_patternscopies declare no layout and DCP saves them as replicated. This matches FSDP2. - Placement.
declare_param_layoutsfollows the existing pattern ofdeclare_optimizer_state_layouts: it lives inflex_shard_fsdp.py, looks upsys.modulesinstead of importing flex_shard, and has a single caller in components. That is consistent with howoptimizer.pyalready uses its helper.
Not verified: the composed EP x edp_shard=2 layout for routed-expert EMA copies. The description says the author ran the test only with world_size=2 (edp_shard=1), so the 4-GPU CI run is the first time that path is exercised.
| @with_comms | ||
| @with_temp_dir | ||
| def test_ema_checkpoints_match_fsdp2(self): | ||
| # FlexShard's EMA copies are plain local shards, which its checkpoints | ||
| # place in the full tensors as FSDP2's do. Trained from FSDP2's initial | ||
| # weights, it saves FSDP2's checkpoint, EMA included. It also loads | ||
| # FSDP2's checkpoint into an EMA in GPU memory and into one offloaded | ||
| # to pinned CPU memory, and saves it again. With ep=2, the routed | ||
| # experts are split over ep, then over edp_shard. | ||
| parallelism_context = ParallelismContext( | ||
| dp_replicate=1, | ||
| dp_shard=self.world_size, | ||
| cp=1, | ||
| tp=1, | ||
| pp=1, | ||
| ep=2, | ||
| world_size=self.world_size, | ||
| enable_sequence_parallel=False, | ||
| ) | ||
|
|
||
| def build( | ||
| fsdp_backend, folder, *, initial_params=None, offload_to_cpu=False, **config | ||
| ): | ||
| model, *setup = self._build( | ||
| build_qwen3_config, | ||
| "debugmodel_moe", | ||
| fsdp_backend, | ||
| "default", | ||
| parallelism_context, | ||
| ) | ||
| if initial_params is not None: | ||
| with torch.no_grad(): | ||
| for fqn, param in model.named_parameters(): | ||
| param.copy_(initial_params[fqn]) | ||
| optimizers = OptimizersContainer( | ||
| OptimizersContainer.Config( | ||
| optimizers=[AdamW.Config(pattern=".*", lr=1e-3)] | ||
| ), | ||
| model_parts=[model], | ||
| ) | ||
| ema = EMA.Config(decays=[0.9], offload_to_cpu=offload_to_cpu).build( | ||
| model_parts=[model] | ||
| ) | ||
| # As Optim.step updates it, after each optimizer step. | ||
| steps = count(1) | ||
| optimizers.register_step_post_hook(lambda *_: ema.step(next(steps))) | ||
| checkpointer = CheckpointManager( | ||
| CheckpointManager.Config( | ||
| folder=folder, interval=1, keep_latest_k=0, **config | ||
| ), | ||
| model_parts=[model], | ||
| optimizers=optimizers, | ||
| lr_schedulers=cast(Any, None), | ||
| ema=ema, | ||
| extra_states={}, | ||
| sd_adapter=None, | ||
| base_folder=self.temp_dir, | ||
| ) | ||
| return model, setup, optimizers, checkpointer | ||
|
|
||
| model, setup, optimizers, checkpointer = build(FSDP2Config(), "fsdp2") | ||
| initial_params = self._local_params(model) | ||
| self._train(model, *setup, 1, False, optim=optimizers) | ||
| checkpointer.save(3) | ||
| checkpointer.close() | ||
| expected = os.path.join(self.temp_dir, "fsdp2", "step-3") | ||
|
|
||
| model, setup, optimizers, checkpointer = build( | ||
| FlexShardConfig(), "flex", initial_params=initial_params | ||
| ) | ||
| self._train(model, *setup, 1, False, optim=optimizers) | ||
| checkpointer.save(3) | ||
| checkpointer.close() | ||
| self._assert_equal_checkpoints( | ||
| expected, os.path.join(self.temp_dir, "flex", "step-3") | ||
| ) | ||
|
|
||
| for offload_to_cpu in (False, True): | ||
| folder = f"flex_loaded_offload_to_cpu_{offload_to_cpu}" | ||
| *_, checkpointer = build( | ||
| FlexShardConfig(), | ||
| folder, | ||
| offload_to_cpu=offload_to_cpu, | ||
| initial_load_path=expected, | ||
| initial_load_model_only=False, | ||
| ) | ||
| self.assertTrue(checkpointer.load()) | ||
| checkpointer.save(3) | ||
| checkpointer.close() | ||
| self._assert_equal_checkpoints( | ||
| expected, os.path.join(self.temp_dir, folder, "step-3") | ||
| ) |
There was a problem hiding this comment.
Consider adding the EMA to test_checkpoints_match_fsdp2 (line 620) instead of adding a separate 4-GPU test. That test already builds FSDP2, trains, saves, loads into FlexShard and saves again on this same Qwen3 MoE ep=2 config. It also runs tp=2, which this test doesn't cover. With TP, FlexShard EMA copies of TP-split dense params get a layout composed from the TP split and the bucket. The doc now lists EMA as supported, but nothing tests EMA together with TP.
To fold it in:
- pass
ema=EMA.Config(decays=[0.9], offload_to_cpu=...).build(model_parts=[model])to theCheckpointManagerthere; - run the FlexShard load once per
offload_to_cpuvalue.
That still catches the regression you describe: with no layouts declared, the load fails with the [2048, 256] vs [1024, 256] size mismatch. It also removes most of the ~90 lines here. The extra training-parity step (FlexShard trains from FSDP2's initial weights and saves the same checkpoint) checks the EMA update. That update is a _foreach_lerp_ over the same local shards as FSDP2's, and the parameter parity tests already check those shards. Keep the step only if you see a regression it would catch that the load-then-save check misses.
[ghstack-poisoned]
Stack from ghstack (oldest at bottom):
Stacked on #5842, the expert-parallelism PR, the chunked-loss PR, the
checkpointing PR, the Hugging Face load PR, the tensor- and context-parallelism PR,
the DeepSeek V3 PR, the accelerator-graphs PR and the integration-tests-and-docs PR.
Summary (human-written)
Description
#5842 rejects
optim.emawithparallelism.storage=FlexShardConfig(), soa FlexShard run can't keep a weight EMA. Lifting the rejection alone would train the EMA
correctly but write corrupt checkpoints without an error. EMA keeps a copy of each
parameter for each decay, a clone of the parameter or, with
offload_to_cpu, a pinnedCPU copy of its local shard. A FlexShard parameter is its plain local shard, so each
copy is too.
EMA.state_dict()hands DCP the copies, and DCP saves a plain tensor asthe whole tensor: every rank writes its copy under the full parameter's key, and DCP's
planner keeps one of them as if they were replicated. The checkpointing PR declares the
layouts of the model's parameters and of the optimizer's states, but EMA's state goes
through neither of its hooks. flex_shard's optimizer hook couldn't take it either: it
accepts only Adam and AdamW, and skips nested states, while each EMA state is a dict of
copies (
ema_params.<key>). This PR lets FlexShard runs keep an EMA, with the samecheckpoints as FSDP2. As in #5842, nothing on the FlexShard path creates a DTensor.
The EMA copies now declare their parameters' layouts, through DCP's
CheckpointableTensorattributes, as the model's state dict does:declare_param_layouts(model, tensors)inflex_shard_backend.pytakes
(param, tensor)pairs and declares on each tensor the layout of its parameter,if that is a FlexShard parameter of
model. The layouts are the onesmodel.state_dict()declares, from flex_shard'sget_flex_shard_global_layouts,matched to the parameters through
model.named_parameters(). Like the other helpers,it returns at once unless flex_shard is imported.
torchtitan/components/optim/ema.py).EMA.state_dict()calls it on thecopies of each model part's parameters, before it builds its state dict. Both of its
paths hand DCP the copies themselves: without offloading, the flat optimizer state
dict holds the live copies; with offloading,
_materialize_dtensorrewraps only thecopies of DTensor parameters, so a FlexShard parameter's pinned copy goes to DCP as
it is. DCP then loads into the copies in place. Without offloading,
Optimizer.load_state_dictkeeps the same tensors; with offloading, the copy backinto the pinned tensor is a no-op for them. The attributes stay on the live copies,
as flex_shard's optimizer hook leaves them on the live Adam states, and every
state_dict()call declares them again, so a copy replaced by a load can't losethem. Routed experts under expert parallelism get the layouts that compose the EP
split with the expert bucket's, as their parameters do. The buffers' copies
(
buffer_patterns) declare nothing: neither backend shards buffers, so both savethem as replicated.
parameters, as an FSDP2 model does, so
_foreach_lerp_updates each copy from thesame elements as FSDP2's DTensor's local shard. The test compares the values bit for
bit.
FlexShardConfig.validate_trainerno longer rejectsoptim.ema. NeitherFlexShardConfig's norstorage's docstring listed EMA, andFLEX_SHARD_FSDP.mdmoves it from the rejections to the supported training features.The earlier revision of this PR handed DCP DTensor views of FlexShard's copies, built by
as_fsdp2_dtensor, which #5842 deleted. EMA withcheckpointer.async_mode="async_with_pinned_mem"or another checkpointer stays rejectedby the checkpointing PR's checks. Threaded async saves keep the attributes for the EMA
as for the model and optimizer (
StateDictStagercopies each tensor's__dict__), butno test here runs one.
The parity test file gains
test_ema_checkpoints_match_fsdp2, on the Qwen3 MoE debugmodel with
ep=2, as the checkpointing PR's test. FSDP2 trains three AdamW steps withan EMA (
decays=[0.9]), updated after each optimizer step asOptim.stepupdates it,and its
CheckpointManagersaves. A FlexShard model with FSDP2's initial weights,copied into its local shards before its EMA is built, trains the same three steps and
saves. Its checkpoint must equal FSDP2's: the same keys, global shapes and dtypes, the
same non-empty chunks, and bitwise-equal values (
_assert_equal_checkpoints), for theEMA as for the model and AdamW states. Then FlexShard loads FSDP2's checkpoint through
initial_load_path, once into an EMA in GPU memory and once into one offloaded topinned CPU memory, since the two paths build and load the state dict differently, and
saves it again. Each checkpoint must equal FSDP2's. In CI the test runs on 4 GPUs, where
ep=2leavesedp_shard=2, so the routed experts' copies have composed layouts. Itpasses on 2 GB200 GPUs with
world_sizeset to 2 (edp_shard=1), in 69 s. Withdeclare_param_layoutssetting no layout, it fails at the first comparison: FlexShard'scheckpoint holds
ema.state.tok_embeddings.weight.ema_params.decay_0p9as one chunk,one rank's copy as the whole tensor, where FSDP2's holds two. Such a FlexShard model
can't load FSDP2's checkpoint either, with or without offloading: DCP reports a size
mismatch, saved
[2048, 256]against current[1024, 256], for that entry. The testbuilds the EMA without a trainer config, so it doesn't go through
FlexShardConfig.validate_trainer.The FSDP2 path doesn't change. It runs one new call,
EMA.state_dict()'sdeclare_param_layouts, which returns at once without flex_shard imported, andotherwise finds no FlexShard layouts in an FSDP2 model and sets nothing. The existing
EMA tests pass:
cpu/components/optim/test_ema.pyandtest_ema_resharding.py(44passed), which save and load EMAs over plain and DTensor parameters, and
gpu/components/optim/test_ema.py(13 passed), which does so with offloading overFSDP2 parameters. No training code changes.
Co-authored-by: Wei Feng [email protected]