Skip to content

Support DeepSeek V3 with parallelism.storage=FlexShardConfig() - #6209

Open
anshul-si wants to merge 4 commits into
gh/anshul-si/27/basefrom
gh/anshul-si/27/head
Open

anshul-si wants to merge 4 commits into
gh/anshul-si/27/basefrom
gh/anshul-si/27/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 and the tensor- and context-parallelism
PR.

Summary (human-written)

Description

FlexShardConfig.validate_model rejects every model that overrides
Decoder._apply_fsdp, because Decoder._apply_fsdp is the only path that applies
storage. MTPDecoder, the base class of DeepSeek V3, overrides it to shard
its multi-token prediction (MTP) layers, so DeepSeek V3 can't use FlexShard, even
without MTP layers. The override shards with FSDP2 only: apply_fsdp_to_mtp_decoder
inserts the MTP layers into model.layers for the duration of
FullyShardConfig.apply_to_decoder,
which shards each of them as one more block. That doesn't carry over to FlexShard, whose
buckets name parameters by FQN: while inserted, an MTP layer's parameters are
layers.6.*, and afterwards mtp_layers.0.*. This PR lets DeepSeek V3 without MTP
layers train with FlexShard, bitwise identical to FSDP2. MTP layers stay rejected until
FlexShard matches FSDP2 for them.

The MTP layers move into the decoder's shared sharding units. decoder_sharding_units
and decoder_prefetch_order take the transformer blocks from a new _decoder_blocks:
model.layers, then model.mtp_layers if the model has any, found by attribute, as the
MoE load-balancing hook already finds them. MTPDecoder no longer overrides
_apply_fsdp, and apply_fsdp_to_mtp_decoder is deleted, so DeepSeek V3 shards through
Decoder._apply_fsdp, which applies the selected backend, and the override check in
FlexShardConfig.validate_model lets it through unchanged. Both backends shard the
units decoder_sharding_units gives, so the FlexShard code itself doesn't change, and
nothing on its path creates a DTensor.

For FSDP2, the sharding units and their order stay the same: each MTP layer is still a
unit after layers, in the fully_shard calls and in the expert-parallel prefetch
order. The rejection of fsdp_unshard_in_current_stream for models with MTP layers
moves from apply_fsdp_to_mtp_decoder into FullyShardConfig.apply_to_decoder, with
the same condition (mtp_layers is not None, which DeepSeek V4 always meets, as
before).

DeepSeek V4 reused apply_fsdp_to_mtp_decoder for its own MTP layers. Its _apply_fsdp
now calls FullyShardConfig().apply_to_decoder, which finds them itself. It keeps the
override, FSDP2 only, with a TODO to delete it once DeepSeek V4 has been checked against
FSDP2 with FlexShard; until then the override check rejects DeepSeek V4, as it does now.
(Its hyper-connection modules' preserve_dtype_params would reject it too.)
test_deepseek_v4_mtp.py loses test_uses_mtp_fsdp_path, which checked that DeepSeek
V4 called the deleted helper with its arguments; the test_fsdp.py test below covers
MTP layers.

FlexShardConfig.validate_model now rejects MTP layers, read from the model config's
mtp_layers, for two reasons:

  • TODO(<flex_shard issue link>): training with MTP layers isn't bitwise identical to
    FSDP2. lm_head runs once per objective, and FlexShard sums the calls' grads in bf16,
    where FSDP2 sums them in fp32, as the earlier revision of this PR traced with a
    flex_shard prototype. On this stack, a one-off probe (the parity test below with one
    MTP layer and FSDP2's parameters copied in, 2 GPUs, not part of the PR) shows more:
    the step-0 losses are equal, but every parameter's step-0 grad differs from FSDP2's,
    at ep=1 and ep=2, with MTPCrossEntropyLoss on full logits and inside
    ChunkedLossWrapper. At ep=1 with the plain loss, lm_head's grad differs by up to
    3e-3 of its largest entry and the others by about 1e-6 of theirs. FSDP2 against FSDP2
    in the same probe is bitwise identical. The earlier revision saw only lm_head's grad
    differ, with the plain loss; the other differences aren't explained yet.
  • The MTP layers' eh_proj, enorm, hnorm and mtp_norm have no param_init, so
    Module initializes them with reset_parameters(), which would run on each rank's
    local shard. FlexShardConfig.validate_model already rejects such modules for every
    model, so this needs no check of its own.

MTP.md describes the new FSDP path and lists both blockers, and the load-balancing
hook's comment no longer says that MTP layers are inserted into layers.

The new test_flex_shard_fsdp.py::test_matches_fsdp2_for_deepseek_v3 runs the parity
check on DeepSeek V3's debugmodel without MTP layers, with ep=2 and
ChunkedLossWrapper, as in its recipes, with one and with two microbatches. It covers
what DeepSeek V3 adds over the Qwen3 MoE cases: MLA attention, a dense first block
before the MoE blocks, and shared experts next to the routed ones. In CI it runs on 4
GPUs (dp_shard=4, so edp_shard=2). It passes on 2 GB200 GPUs with world_size set
to 2 (edp_shard then has size 1), and hasn't run at 4 GPUs: this machine has 2. With
the base's MTPDecoder._apply_fsdp and apply_fsdp_to_mtp_decoder restored, it fails:
tok_embeddings.weight isn't a FlexShard parameter, because the override sharded the
model with FSDP2. In test_fsdp.py, the fake decoder of
test_fully_shard_shards_an_moe_held_as_mlp (now
..._shards_mtp_layers_and_an_moe_held_as_mlp) also has an MTP layer, and the test
requires one sharding unit per block, in order, MTP layer last, with each block's
routed-expert placement.

On an earlier revision of this PR, the FSDP2 path matched the chunked-loss PR bit for
bit. scripts/loss_compare.py 4f80bce4f <that revision> --assert-equal --metrics loss,grad_norm (seed 42, deterministic, 50 steps, 2 GB200 GPUs) reports equal loss and
grad norm at every step for deepseek_v3_debugmodel_mtp (one MTP layer, the recipe's
ChunkedLossWrapper around MTPCrossEntropyLoss) with dp_shard=2 (step-50 loss
3.87412, training captured in CUDA graphs) and with dp_shard=2, ep=2 (3.87773), and
for DeepSeek V4's debugmodel (2.90584). The DeepSeek V3 runs use flex attention
because the environment has no FA4, and all skip the seed checkpoint, since both runs
start from seed 42 with the same parallelism. DeepSeek V4's MTP recipe fails at its
first step on the base too (MTPCrossEntropyLoss gets one labels tensor), so a
structural check covers it instead: with fully_shard wrapped, on meta with a 4-rank
fake process group, the base and this PR make the same fully_shard calls (modules,
reshard policy, mesh, and each parameter's placement and mesh) and set the same prefetch
lists, for DeepSeek V3 and V4 with one MTP layer, each at ep=1 and ep=2. The only
difference is the MTP layer's parameter names during the call, layers.6.* and
layers.4.* on the base.

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

[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 1m 43s —— View job


Approve, with two small items to fix before merging: fill in the "Summary (human-written)" section and replace the TODO(<flex_shard issue link>) placeholder with a real issue link. 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. Removing the insert-into-layers hack fixes the root cause: FlexShard's FQN-keyed buckets saw MTP parameters under temporary layers.N.* names. The FSDP2 grouping and prefetch order stay structurally the same, and the change is net -93 LoC. This touches core distributed code, so a maintainer still needs to review it.

What this PR does. It deletes MTPDecoder._apply_fsdp and apply_fsdp_to_mtp_decoder. The shared _decoder_fsdp_groups and _decoder_prefetch_order now visit model.mtp_layers after model.layers through a new _decoder_blocks. With that, DeepSeek V3 goes through Decoder._apply_fsdp and gets fsdp_backend. validate_flex_shard_training keeps rejecting MTP layers explicitly, because of a known grad mismatch.

Example. DeepSeek V3 debugmodel (no MTP layers), fsdp_backend=FlexShardConfig():

base: MTPDecoder overrides _apply_fsdp
      -> validate_flex_shard_training: "models that override Decoder._apply_fsdp (DeepSeekV3Model)"
PR:   Decoder._apply_fsdp -> apply_fsdp_to_decoder(fsdp_backend=FlexShard)
      -> trains bitwise equal to FSDP2

With 1 MTP layer under FSDP2:
base: fully_shard([layers["0"]]), ..., fully_shard([layers["6"]])  # mtp_layers[0] temporarily inserted
PR:   fully_shard([layers["0"]]), ..., fully_shard([mtp_layers[0]]) # same modules and order, real FQNs

Must fix

  1. The PR description has an empty "Summary (human-written)" section. The author needs to fill it in.
  2. torchtitan/distributed/flex_shard_fsdp.py:499 -- TODO(<flex_shard issue link>) is a placeholder. File the issue and link it here and in MTP.md.

Should consider

  • torchtitan/models/deepseek_v4/model.py:160 -- the V4 override is now a copy of Decoder._apply_fsdp whose only job is to trip the override check. The existing preserve_dtype_params check already rejects V4 (mHC and compressor), so the override can be deleted (about 30 lines).
  • torchtitan/distributed/fsdp.py:962 -- "has MTP layers" is tested three different ways. is not None here rejects V4 even with zero MTP layers.
Details
  • Gate. The problem is real on the base: MTPDecoder overrode _apply_fsdp and never passed fsdp_backend, so the override check rejected DeepSeek V3 even with no MTP layers. Sharing the group builder is the right layer. Two models (V3 and V4) now use the mtp_layers attribute in fsdp.py, and the MoE load-balancing hook (moe.py:1047) already finds them by the same attribute, so this isn't single-consumer bending of shared code.
  • FSDP2 equivalence. Before, model.layers was [..., mtp_0, ...] during the call. Now _decoder_blocks returns [*layers.values(), *mtp_layers]. That gives the same modules in the same order for both the fully_shard groups and the EP prefetch order (tok_embeddings, then blocks, then lm_head). Each MTP block's MoE placements come from the same loop. The 50-step loss_compare runs and the meta-device structural comparison in the description cover this.
  • The redundant MTP rejection is justified. For V3, the existing reset_parameters() check already rejects MTP layers (eh_proj, enorm, ...). The explicit "MTP layers" entry still earns its place: if param_init is added to those modules later, it keeps the known numerics mismatch from passing silently.
  • Tests. The extended test_apply_fsdp_to_decoder_shards_mtp_layers_and_an_moe_held_as_mlp replaces the deleted V4 mock test with a check of the real invariant (group order and expert placements for MTP blocks), not of call arguments. The new GPU parity case adds MLA, a dense first block and shared experts, which the Qwen3 cases don't cover.

Not verified: the 4-GPU run of test_matches_fsdp2_for_deepseek_v3 (dp_shard=4, edp_shard=2), which the description says ran only on 2 GPUs.

)
unsupported.append(f"models that override Decoder._apply_fsdp ({name})")
if getattr(model_config, "mtp_layers", None):
# TODO(<flex_shard issue link>): lm_head runs once per objective, and

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.

TODO(<flex_shard issue link>) is still a placeholder. If it lands like this, nobody can trace the MTP grad mismatch, and the non-lm_head differences that the description says "aren't explained yet" have no record anywhere. Please file the issue, including the probe's numbers from the description (lm_head off by about 3e-3 relative, other params by about 1e-6, at ep=1 and ep=2), and link it here and in the MTP.md FlexShard section.

Comment thread torchtitan/models/deepseek_v4/model.py Outdated
Comment on lines +160 to +163
# TODO: Delete this FSDP2-only copy of Decoder._apply_fsdp once DeepSeek
# V4 is checked against FSDP2 with FlexShard. Until then, it makes
# validate_flex_shard_training, which rejects models that override
# Decoder._apply_fsdp, reject DeepSeek V4.

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.

This override is now a copy of Decoder._apply_fsdp (torchtitan/models/common/decoder.py:196-226) without fsdp_backend=. Its only job is to trip the override check in validate_flex_shard_training. That check doesn't need it. Every DeepSeek V4 block has HcPre/HcPost with preserve_dtype_params=("hc_fn", "hc_base", "hc_scale") (mhc.py:83,163), and compressor.py:84 has ("ape",). So the existing preserve_dtype_params check already rejects V4 with a clearer reason than "overrides Decoder._apply_fsdp".

With the default FSDP2Config, the FSDP2 path is identical either way. Suggest deleting the whole override (about 30 lines) and the now-unused imports. That also removes rejection-by-side-effect, which is the implicit kind of check the "explicit over implicit" principle warns against.

Comment thread torchtitan/distributed/fsdp.py Outdated
FlexShard instead; ``validate_flex_shard_training`` rejects the
arguments it doesn't support. FSDP2 otherwise.
"""
if unshard_in_current_stream and getattr(model, "mtp_layers", None) is not None:

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.

The PR now tests "has MTP layers" three different ways:

  • _decoder_blocks: getattr(model, "mtp_layers", None) or (), so truthiness
  • validate_flex_shard_training: truthiness on the config
  • here: is not None

DeepSeek V4 always sets self.mtp_layers = ModuleList() (deepseek_v4/model.py:268), so this branch rejects fsdp_unshard_in_current_stream for V4 even with zero MTP layers. The stated reason, that tok_embeddings runs once per MTP depth, doesn't apply then.

The behavior is unchanged from the base, so this is optional. Now that the check sits in shared code, though, truthiness would be accurate and consistent with the other two:

Suggested change
if unshard_in_current_stream and getattr(model, "mtp_layers", None) is not None:
if unshard_in_current_stream and getattr(model, "mtp_layers", None):

[ghstack-poisoned]
[ghstack-poisoned]
@anshul-si anshul-si changed the title Support DeepSeek V3 with parallelism.fsdp_backend=FlexShardConfig() Support DeepSeek V3 with parallelism.fsdp_backend=FlexShardBackend.Config() Nov 25, 2026
[ghstack-poisoned]
@anshul-si anshul-si changed the title Support DeepSeek V3 with parallelism.fsdp_backend=FlexShardBackend.Config() Support DeepSeek V3 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