Repository navigation
Conversation
[ghstack-poisoned]
|
@claude review this pr |
|
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 |
There was a problem hiding this comment.
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
- The PR description has an empty "Summary (human-written)" section. The author needs to fill it in.
torchtitan/distributed/flex_shard_fsdp.py:499--TODO(<flex_shard issue link>)is a placeholder. File the issue and link it here and inMTP.md.
Should consider
torchtitan/models/deepseek_v4/model.py:160-- the V4 override is now a copy ofDecoder._apply_fsdpwhose only job is to trip the override check. The existingpreserve_dtype_paramscheck 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 Nonehere rejects V4 even with zero MTP layers.
Details
- Gate. The problem is real on the base:
MTPDecoderoverrode_apply_fsdpand never passedfsdp_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 themtp_layersattribute infsdp.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.layerswas[..., mtp_0, ...]during the call. Now_decoder_blocksreturns[*layers.values(), *mtp_layers]. That gives the same modules in the same order for both thefully_shardgroups and the EP prefetch order (tok_embeddings, then blocks, thenlm_head). Each MTP block's MoE placements come from the same loop. The 50-steploss_compareruns 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: ifparam_initis 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_mlpreplaces 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 |
There was a problem hiding this comment.
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.
| # 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. |
There was a problem hiding this comment.
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.
| 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: |
There was a problem hiding this comment.
The PR now tests "has MTP layers" three different ways:
_decoder_blocks:getattr(model, "mtp_layers", None) or (), so truthinessvalidate_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:
| 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]
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_modelrejects every model that overridesDecoder._apply_fsdp, becauseDecoder._apply_fsdpis the only path that appliesstorage.MTPDecoder, the base class of DeepSeek V3, overrides it to shardits 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_decoderinserts the MTP layers into
model.layersfor the duration ofFullyShardConfig.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 afterwardsmtp_layers.0.*. This PR lets DeepSeek V3 without MTPlayers 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_unitsand
decoder_prefetch_ordertake the transformer blocks from a new_decoder_blocks:model.layers, thenmodel.mtp_layersif the model has any, found by attribute, as theMoE load-balancing hook already finds them.
MTPDecoderno longer overrides_apply_fsdp, andapply_fsdp_to_mtp_decoderis deleted, so DeepSeek V3 shards throughDecoder._apply_fsdp, which applies the selected backend, and the override check inFlexShardConfig.validate_modellets it through unchanged. Both backends shard theunits
decoder_sharding_unitsgives, so the FlexShard code itself doesn't change, andnothing 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 thefully_shardcalls and in the expert-parallel prefetchorder. The rejection of
fsdp_unshard_in_current_streamfor models with MTP layersmoves from
apply_fsdp_to_mtp_decoderintoFullyShardConfig.apply_to_decoder, withthe same condition (
mtp_layers is not None, which DeepSeek V4 always meets, asbefore).
DeepSeek V4 reused
apply_fsdp_to_mtp_decoderfor its own MTP layers. Its_apply_fsdpnow calls
FullyShardConfig().apply_to_decoder, which finds them itself. It keeps theoverride, 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_paramswould reject it too.)test_deepseek_v4_mtp.pylosestest_uses_mtp_fsdp_path, which checked that DeepSeekV4 called the deleted helper with its arguments; the
test_fsdp.pytest below coversMTP layers.
FlexShardConfig.validate_modelnow rejects MTP layers, read from the model config'smtp_layers, for two reasons:TODO(<flex_shard issue link>): training with MTP layers isn't bitwise identical toFSDP2.
lm_headruns 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=1andep=2, withMTPCrossEntropyLosson full logits and insideChunkedLossWrapper. Atep=1with the plain loss,lm_head's grad differs by up to3e-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 graddiffer, with the plain loss; the other differences aren't explained yet.
eh_proj,enorm,hnormandmtp_normhave noparam_init, soModuleinitializes them withreset_parameters(), which would run on each rank'slocal shard.
FlexShardConfig.validate_modelalready rejects such modules for everymodel, so this needs no check of its own.
MTP.mddescribes the new FSDP path and lists both blockers, and the load-balancinghook's comment no longer says that MTP layers are inserted into
layers.The new
test_flex_shard_fsdp.py::test_matches_fsdp2_for_deepseek_v3runs the paritycheck on DeepSeek V3's
debugmodelwithout MTP layers, withep=2andChunkedLossWrapper, as in its recipes, with one and with two microbatches. It coverswhat 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, soedp_shard=2). It passes on 2 GB200 GPUs withworld_sizesetto 2 (
edp_shardthen has size 1), and hasn't run at 4 GPUs: this machine has 2. Withthe base's
MTPDecoder._apply_fsdpandapply_fsdp_to_mtp_decoderrestored, it fails:tok_embeddings.weightisn't a FlexShard parameter, because the override sharded themodel with FSDP2. In
test_fsdp.py, the fake decoder oftest_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 testrequires 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 andgrad norm at every step for
deepseek_v3_debugmodel_mtp(one MTP layer, the recipe'sChunkedLossWrapperaroundMTPCrossEntropyLoss) withdp_shard=2(step-50 loss3.87412, training captured in CUDA graphs) and with
dp_shard=2, ep=2(3.87773), andfor DeepSeek V4's
debugmodel(2.90584). The DeepSeek V3 runs use flex attentionbecause 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 (
MTPCrossEntropyLossgets one labels tensor), so astructural check covers it instead: with
fully_shardwrapped, on meta with a 4-rankfake process group, the base and this PR make the same
fully_shardcalls (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=1andep=2. The onlydifference is the MTP layer's parameter names during the call,
layers.6.*andlayers.4.*on the base.Co-authored-by: Wei Feng [email protected]