Skip to content

Support EMA with parallelism.storage=FlexShardConfig() - #6212

Open
anshul-si wants to merge 5 commits into
gh/anshul-si/30/basefrom
gh/anshul-si/30/head
Open

anshul-si wants to merge 5 commits into
gh/anshul-si/30/basefrom
gh/anshul-si/30/head

Conversation

@anshul-si

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

Copy link
Copy Markdown
Contributor

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.ema with parallelism.storage=FlexShardConfig(), so
a 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 pinned
CPU 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 as
the 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 same
checkpoints as FSDP2. As in #5842, nothing on the FlexShard path creates a DTensor.

The EMA copies now declare their parameters' layouts, through DCP's
CheckpointableTensor attributes, as the model's state dict does:

  • Helper. The new declare_param_layouts(model, tensors) in flex_shard_backend.py
    takes (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 ones
    model.state_dict() declares, from flex_shard's get_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.
  • EMA (torchtitan/components/optim/ema.py). EMA.state_dict() calls it on the
    copies 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_dtensor rewraps only the
    copies 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_dict keeps the same tensors; with offloading, the copy back
    into 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 lose
    them. 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 save
    them as replicated.
  • EMA updates need no change. Between steps a FlexShard model holds its sharded
    parameters, as an FSDP2 model does, so _foreach_lerp_ updates each copy from the
    same elements as FSDP2's DTensor's local shard. The test compares the values bit for
    bit.

FlexShardConfig.validate_trainer no longer rejects optim.ema. Neither
FlexShardConfig's nor storage's docstring listed EMA, and
FLEX_SHARD_FSDP.md moves 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 with
checkpointer.async_mode="async_with_pinned_mem" or another checkpointer stays rejected
by the checkpointing PR's checks. Threaded async saves keep the attributes for the EMA
as for the model and optimizer (StateDictStager copies each tensor's __dict__), but
no test here runs one.

The parity test file gains test_ema_checkpoints_match_fsdp2, on the Qwen3 MoE debug
model with ep=2, as the checkpointing PR's test. FSDP2 trains three AdamW steps with
an EMA (decays=[0.9]), updated after each optimizer step as Optim.step updates it,
and its CheckpointManager saves. 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 the
EMA 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 to
pinned 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=2 leaves edp_shard=2, so the routed experts' copies have composed layouts. It
passes on 2 GB200 GPUs with world_size set to 2 (edp_shard=1), in 69 s. With
declare_param_layouts setting no layout, it fails at the first comparison: FlexShard's
checkpoint holds ema.state.tok_embeddings.weight.ema_params.decay_0p9 as 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 test
builds 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()'s
declare_param_layouts, which returns at once without flex_shard imported, and
otherwise finds no FlexShard layouts in an FSDP2 model and sets nothing. The existing
EMA tests pass: cpu/components/optim/test_ema.py and test_ema_resharding.py (44
passed), which save and load EMAs over plain and DTensor parameters, and
gpu/components/optim/test_ema.py (13 passed), which does so with offloading over
FSDP2 parameters. No training code changes.

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

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

Copy link
Copy Markdown
Contributor Author

@claude review this pr

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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 test_checkpoints_match_fsdp2). 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 -- 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

  1. 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 into test_checkpoints_match_fsdp2 rather than adding a separate 4-GPU test. That also covers EMA with tp=2, which nothing tests today (details inline).
Details
  • Load paths. Without offloading, Optimizer.load_state_dict keeps the same tensors, because the .to() call in _process_value_according_to_param_policy returns the same object when dtype and device already match. So the layout attributes survive a load. That makes re-declaring on every state_dict() call a cheap safeguard, not a requirement. With offloading, _materialize_dtensor returns the pinned CPU copy unchanged for non-DTensor params. DCP loads into it in place, and the later copy_ 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_patterns copies declare no layout and DCP saves them as replicated. This matches FSDP2.
  • Placement. declare_param_layouts follows the existing pattern of declare_optimizer_state_layouts: it lives in flex_shard_fsdp.py, looks up sys.modules instead of importing flex_shard, and has a single caller in components. That is consistent with how optimizer.py already 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.

Comment on lines +713 to +804
@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")
)

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.

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 the CheckpointManager there;
  • run the FlexShard load once per offload_to_cpu value.

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]
@anshul-si
anshul-si marked this pull request as ready for review November 19, 2026 07:39
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 19, 2026
@github-actions
github-actions Bot requested a review from weifengpy November 19, 2026 07:39
[ghstack-poisoned]
@anshul-si anshul-si changed the title Support EMA with parallelism.fsdp_backend=FlexShardConfig() Support EMA with parallelism.fsdp_backend=FlexShardBackend.Config() Nov 25, 2026
[ghstack-poisoned]
@anshul-si anshul-si changed the title Support EMA with parallelism.fsdp_backend=FlexShardBackend.Config() Support EMA 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 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