Repository navigation
Conversation
[ghstack-poisoned]
[ghstack-poisoned]
…ardConfig() 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, the integration-tests-and-docs PR, the EMA PR, the DistMuon PR and the DeepSeek V3 DistMuon recipe PR. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Description The DeepSeek V3 PR lets DeepSeek V3 train with FlexShard, but `validate_flex_shard_training` rejects multi-token prediction (MTP) layers, for two reasons. FlexShard summed the grads of a module that runs more than once per backward, as the embedding and `lm_head` do with MTP layers (once per objective), in another dtype than FSDP2. flex_shard fixes that in "Sum the grads of a module called more than once per backward as FSDP2 does" (not merged yet). And the MTP layers' own modules didn't initialize under FlexShard as one device would. This PR fixes the initialization and deletes the rejection, so DeepSeek V3 with MTP layers trains with FlexShard, bitwise identical to FSDP2, once torchtitan's CI pins a flex_shard with that fix. An MTP layer's `enorm`, `hnorm`, `eh_proj` and `mtp_norm` were the only DeepSeek V3 modules without a `param_init`, so `Module._init_self_parameters` initialized them with `reset_parameters()`. Under FSDP2, that runs on the DTensor parameter, as a `param_init` would. Under FlexShard, it would run on each rank's plain local shard, so each rank would draw its own values, and `validate_flex_shard_training` rejects any module that has a `reset_parameters()` and no `param_init`. `_build_mtp_layers`, which builds the MTP layers of every DeepSeek V3 flavor, now gives them a `param_init`, as `param_init.py` asks of every module config and as DeepSeek V4's MTP layers have. Each keeps the initialization it had: the norms get ones (`_NORM_INIT`, which is what `RMSNorm.reset_parameters` does), and `eh_proj` gets `nn.Linear`'s default, `kaiming_uniform_(a=sqrt(5))`, as `Linear.reset_parameters` applies it (its `flatten(0, -2)` returns a 2D weight itself). So FSDP2 draws the same values as before, which the A/B run below checks. `validate_flex_shard_training` no longer rejects MTP layers, and loses the TODO. `MTP.md` drops its FlexShard TODO section and says that FlexShard gets the same groups as FSDP2. `FLEX_SHARD_FSDP.md` drops MTP layers from its rejections, and its parity tests now cover DeepSeek V3 with an MTP layer too. One gap stays, behind an existing rejection: `flex_shard_partial_backwards` turns `lm_head`'s gradient sync on before `ChunkedLossWrapper`'s last chunk, since `validate_flex_shard_training` rejects `fsdp_defer_gradient_reduction`. When that rejection is lifted, it has to keep sync off in backwards that defer reduction, with or without MTP layers. `test_flex_shard_fsdp.py` gains `test_matches_fsdp2_for_deepseek_v3_mtp` (`ep=1`) and `test_matches_fsdp2_for_deepseek_v3_mtp_with_expert_parallelism` (`ep=2`). Both run the parity check on DeepSeek V3's `debugmodel` with one MTP layer, as in `deepseek_v3_debugmodel_mtp`, with `MTPCrossEntropyLoss` on full logits and inside `ChunkedLossWrapper` (the recipe's loss), each with one and with two microbatches. For a model with MTP layers, the training loop passes one routing-token count and one loss-token count per objective. `_check_matches_fsdp2` now takes the chunked-loss flag in each case instead of as an argument, and its callers pass it there, because a second `ParallelismContext` in the same process trips FSDP2's mesh check ("Expected param's DTensor mesh to be the same mesh passed to fully_shard"). The check that each FlexShard shard is its slice of one device's initialization covers the MTP layers' parameters like any others. It now gathers the mismatches from all ranks before it asserts: a mismatch on one rank alone left the other waiting in training's first all-gather until the test timed out after 300 s, without a message. The new tests run on 4 GPUs in CI (`dp_shard=4`, so `edp_shard=2` at `ep=2`) and haven't run at 4 GPUs: this machine has 2. On 2 GB200 GPUs with `world_size` set to 2 and flex_shard's fix, they pass, as does `test_matches_fsdp2`. With flex_shard at CI's pin (`d6bb546`), `test_matches_fsdp2_for_deepseek_v3_mtp` fails at the first step of its first case (plain loss, one microbatch): the grad norm differs. With the initialization fix reverted, `_apply_flex_shard` fails its assertion on an MTP layer parameter that has no `param_init` to wrap. On the DeepSeek V3 PR, before this PR moved to the top of the stack, the `ep=2` test failed at CI's pin the same way, as did a copy with only the chunked-loss cases. So the multi-GPU unit-test job needs its flex_shard pin (`.github/workflows/unit_test_gpu.yaml`) moved to a commit with flex_shard's fix, in this PR or before it; this PR leaves the pin as it is. The FSDP2 path trains as before, bit for bit. When this PR sat on an earlier revision of the DeepSeek V3 PR, `9d6b3a5e0`, `scripts/loss_compare.py 9d6b3a5e0 <this PR> --assert-equal --metrics loss,grad_norm` (seed 42, deterministic, 50 steps, 2 GB200 GPUs, `dp_shard=2`) reported equal loss and grad norm at every step for `deepseek_v3_debugmodel_mtp` (one MTP layer, `ChunkedLossWrapper` around `MTPCrossEntropyLoss`; step-50 loss 3.87412, training captured in CUDA graphs). It uses flex attention because the environment has no FA4, and skips the seed checkpoint, so both runs initialize the model themselves, from seed 42 with the same parallelism. The FSDP2 code this PR changes, the MTP layers' `param_init`, is the same here; the A/B hasn't run on this base. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 255dab6 Pull-Request: #6215
|
@claude review this pr |
|
Claude finished @anshul-si's task in 2m 2s —— View job Request changes: the PR removes the MTP + FlexShard guard while the pinned flex_shard still lacks the fix this PR depends on. The full review with inline comments is on the PR. |
There was a problem hiding this comment.
Verdict: Request changes -- the PR removes the guard against MTP + FlexShard while the pinned flex_shard still lacks the grad-summation fix the PR depends on. Both CI and the documented install would then train MTP with numerics that differ from FSDP2, with nothing to signal it.
What this PR does. It gives the DeepSeek V3 MTP layers' enorm, hnorm, mtp_norm (ones) and eh_proj (kaiming_uniform_(a=sqrt(5))) an explicit param_init. The values are the same ones reset_parameters() drew before, so FlexShard can initialize them through init_from_full. It deletes the "MTP layers" rejection in validate_flex_shard_training, updates MTP.md and FLEX_SHARD_FSDP.md, and adds parity tests against FSDP2 for DeepSeek V3 with one MTP layer at ep=1 and ep=2.
Example.
recipe: deepseek_v3_debugmodel_mtp, parallelism.fsdp_backend=FlexShardConfig()
before: ValueError at engine build ("MTP layers" unsupported)
after, flex_shard @ d6bb546 (current pin):
trains; lm_head/embedding grads (one call per objective) are summed in bf16
-> grad_norm differs from FSDP2 at step 1 (per the PR description)
after, flex_shard with the "sum grads as FSDP2 does" fix:
bitwise identical to FSDP2 (claimed; 2-GPU runs only)
Must fix
- The "Summary (human-written)" section is empty. The author has to fill it in.
.github/scripts/install_flex_shard.sh:13--FLEX_SHARD_COMMITstill pinsd6bb546, the commit at which, per the description,test_matches_fsdp2_for_deepseek_v3_mtpfails. The deleted check (flex_shard_fsdp.py, the oldif getattr(model_config, "mtp_layers", None)block) was the only thing stopping this configuration. Once it lands, the new tests fail in CI, and anyone who installs with the documented script (FLEX_SHARD_FSDP.md:44) gets FlexShard MTP training that differs from FSDP2, with no error. The description says the pin lives in.github/workflows/unit_test_gpu.yaml. It actually lives in this script, which isn't a workflow file, so this PR can change it. Fix: bumpFLEX_SHARD_COMMITin this PR once the flex_shard fix merges, and hold the PR until then. Keeping the rejection would also work, but then the PR has nothing left to do.
Should consider
tests/unit_tests/gpu/distributed/test_flex_shard_fsdp.py:597-619-- drop theep=1MTP test, or fold MTP into the existing DeepSeek V3 EP test (inline).torchtitan/models/deepseek_v3/flavors.py:93--_DEFAULT_LINEAR_INITskips theflatten(0, -2)thatLinear.reset_parametersapplies, so its name overclaims (inline).
Details
- Gate: the problem is real (MTP + FlexShard raises on the base), and the MTP layers were the only DeepSeek V3 modules without a
param_init. The fix sits in the model's flavors, which is the right layer, and it matches DeepSeek V4's MTP (deepseek_v4/flavors.py:702-718). No other model builds MTP layers through_build_mtp_layers. DeepSeek V4 overrides_apply_fsdp, so FlexShard still rejects it. - Init equivalence:
RMSNorm.reset_parameterssets the weight to ones.Linear.reset_parametersrunskaiming_uniform_(weight.flatten(0, -2), a=sqrt(5)), and foreh_proj's 2D[dim, 2*dim]weight the flatten is the identity, so fan-in and RNG consumption are the same.bias=False, so the missing bias init doesn't matter. - The guard that rejects modules with
reset_parameters()and noparam_initstays in place, so a future MTP module missing its init still fails clearly. - Most of the test diff, moving
chunked_lossinto the case tuple at about 12 call sites, is mechanical. Theall_gather_objecton init mismatches turns a 300 s hang into an error message on every rank. That's justified.
Not verified: the 4-GPU runs of the new tests (dp_shard=4, edp_shard=2). Also the FSDP2 A/B on this base: per the description, it ran on an earlier revision of the DeepSeek V3 PR.
| def _check_deepseek_v3_mtp_matches_fsdp2(self, *, ep: int) -> None: | ||
| # One MTP layer, as in deepseek_v3_debugmodel_mtp. The embedding and | ||
| # lm_head run once per objective, so their buckets sum two calls' grads | ||
| # in each backward. The loss is MTPCrossEntropyLoss on full logits, and | ||
| # inside ChunkedLossWrapper, as in the recipe, which runs lm_head on its | ||
| # own on the chunks of both outputs. | ||
| self._check_matches_fsdp2( | ||
| ep=ep, | ||
| cases=product( | ||
| [(partial(build_deepseek_v3_config, num_mtp_layers=1), "debugmodel")], | ||
| ("default",), | ||
| (1, 2), | ||
| (False, True), | ||
| ), | ||
| ) | ||
|
|
||
| @with_comms | ||
| def test_matches_fsdp2_for_deepseek_v3_mtp(self): | ||
| self._check_deepseek_v3_mtp_matches_fsdp2(ep=1) | ||
|
|
||
| @with_comms | ||
| def test_matches_fsdp2_for_deepseek_v3_mtp_with_expert_parallelism(self): | ||
| self._check_deepseek_v3_mtp_matches_fsdp2(ep=2) |
There was a problem hiding this comment.
Two new 4-GPU tests with 4 cases each (1/2 microbatches x plain/chunked loss) cost 8 more parity runs. The thing they guard, a module called once per objective summing its grads inside one backward, doesn't depend on EP. The ep=2 test already covers ep=1's concern, and it is the harder configuration (.claude/rules/tests.md: "Cover the harder configuration").
Suggestion: drop test_matches_fsdp2_for_deepseek_v3_mtp and inline _check_deepseek_v3_mtp_matches_fsdp2 into the ep=2 test, since it would have only one caller. You could also fold MTP into the existing test_matches_fsdp2_for_deepseek_v3_with_expert_parallelism by adding num_mtp_layers=1 to its build config. The MTP model runs the same decoder layers plus one more, so this wouldn't add a test at all. Its only loss is the non-MTP DeepSeek V3 case under FlexShard, and the plain decoder tests (Qwen3 MoE with EP) already cover that path.
| _NORM_INIT = {"weight": nn.init.ones_} | ||
| _EMBEDDING_INIT = {"weight": partial(nn.init.normal_, std=1.0)} | ||
| # nn.Linear's default initialization, as Linear.reset_parameters applies it. | ||
| _DEFAULT_LINEAR_INIT = {"weight": partial(nn.init.kaiming_uniform_, a=math.sqrt(5))} |
There was a problem hiding this comment.
Linear.reset_parameters (torchtitan/models/common/linear/linear.py:94) and the LoRA adapter init (torchtitan/models/common/lora.py:217) both apply this init to w.flatten(0, -2). That keeps fan-in equal to in_features for stacked num_linears weights too. Here it's applied to the raw weight, which is equivalent only while eh_proj stays 2D. That holds today, but the constant's name, _DEFAULT_LINEAR_INIT, claims to be Linear's default in general. Either match the flatten, so it is exactly Linear.reset_parameters, or name it after its one consumer (e.g. _EH_PROJ_INIT).
[ghstack-poisoned]
…ardConfig() 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, the integration-tests-and-docs PR, the EMA PR, the DistMuon PR and the DeepSeek V3 DistMuon recipe PR. ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Description The DeepSeek V3 PR lets DeepSeek V3 train with FlexShard, but `validate_flex_shard_training` rejects multi-token prediction (MTP) layers, for two reasons. FlexShard summed the grads of a module that runs more than once per backward, as the embedding and `lm_head` do with MTP layers (once per objective), in another dtype than FSDP2. flex_shard fixes that in "Sum the grads of a module called more than once per backward as FSDP2 does" (not merged yet). And the MTP layers' own modules didn't initialize under FlexShard as one device would. This PR fixes the initialization and deletes the rejection, so DeepSeek V3 with MTP layers trains with FlexShard, bitwise identical to FSDP2, once torchtitan's CI pins a flex_shard with that fix. An MTP layer's `enorm`, `hnorm`, `eh_proj` and `mtp_norm` were the only DeepSeek V3 modules without a `param_init`, so `Module._init_self_parameters` initialized them with `reset_parameters()`. Under FSDP2, that runs on the DTensor parameter, as a `param_init` would. Under FlexShard, it would run on each rank's plain local shard, so each rank would draw its own values, and `validate_flex_shard_training` rejects any module that has a `reset_parameters()` and no `param_init`. `_build_mtp_layers`, which builds the MTP layers of every DeepSeek V3 flavor, now gives them a `param_init`, as `param_init.py` asks of every module config and as DeepSeek V4's MTP layers have. Each keeps the initialization it had: the norms get ones (`_NORM_INIT`, which is what `RMSNorm.reset_parameters` does), and `eh_proj` gets `nn.Linear`'s default, `kaiming_uniform_(a=sqrt(5))`, as `Linear.reset_parameters` applies it (its `flatten(0, -2)` returns a 2D weight itself). So FSDP2 draws the same values as before, which the A/B run below checks. `validate_flex_shard_training` no longer rejects MTP layers, and loses the TODO. `MTP.md` drops its FlexShard TODO section and says that FlexShard gets the same groups as FSDP2. `FLEX_SHARD_FSDP.md` drops MTP layers from its rejections, and its parity tests now cover DeepSeek V3 with an MTP layer too. One gap stays, behind an existing rejection: `flex_shard_partial_backwards` turns `lm_head`'s gradient sync on before `ChunkedLossWrapper`'s last chunk, since `validate_flex_shard_training` rejects `fsdp_defer_gradient_reduction`. When that rejection is lifted, it has to keep sync off in backwards that defer reduction, with or without MTP layers. `test_flex_shard_fsdp.py` gains `test_matches_fsdp2_for_deepseek_v3_mtp` (`ep=1`) and `test_matches_fsdp2_for_deepseek_v3_mtp_with_expert_parallelism` (`ep=2`). Both run the parity check on DeepSeek V3's `debugmodel` with one MTP layer, as in `deepseek_v3_debugmodel_mtp`, with `MTPCrossEntropyLoss` on full logits and inside `ChunkedLossWrapper` (the recipe's loss), each with one and with two microbatches. For a model with MTP layers, the training loop passes one routing-token count and one loss-token count per objective. `_check_matches_fsdp2` now takes the chunked-loss flag in each case instead of as an argument, and its callers pass it there, because a second `ParallelismContext` in the same process trips FSDP2's mesh check ("Expected param's DTensor mesh to be the same mesh passed to fully_shard"). The check that each FlexShard shard is its slice of one device's initialization covers the MTP layers' parameters like any others. It now gathers the mismatches from all ranks before it asserts: a mismatch on one rank alone left the other waiting in training's first all-gather until the test timed out after 300 s, without a message. The new tests run on 4 GPUs in CI (`dp_shard=4`, so `edp_shard=2` at `ep=2`) and haven't run at 4 GPUs: this machine has 2. On 2 GB200 GPUs with `world_size` set to 2 and flex_shard's fix, they pass, as does `test_matches_fsdp2`. With flex_shard at CI's pin (`d6bb546`), `test_matches_fsdp2_for_deepseek_v3_mtp` fails at the first step of its first case (plain loss, one microbatch): the grad norm differs. With the initialization fix reverted, `_apply_flex_shard` fails its assertion on an MTP layer parameter that has no `param_init` to wrap. On the DeepSeek V3 PR, before this PR moved to the top of the stack, the `ep=2` test failed at CI's pin the same way, as did a copy with only the chunked-loss cases. So the multi-GPU unit-test job needs its flex_shard pin (`.github/workflows/unit_test_gpu.yaml`) moved to a commit with flex_shard's fix, in this PR or before it; this PR leaves the pin as it is. The FSDP2 path trains as before, bit for bit. When this PR sat on an earlier revision of the DeepSeek V3 PR, `9d6b3a5e0`, `scripts/loss_compare.py 9d6b3a5e0 <this PR> --assert-equal --metrics loss,grad_norm` (seed 42, deterministic, 50 steps, 2 GB200 GPUs, `dp_shard=2`) reported equal loss and grad norm at every step for `deepseek_v3_debugmodel_mtp` (one MTP layer, `ChunkedLossWrapper` around `MTPCrossEntropyLoss`; step-50 loss 3.87412, training captured in CUDA graphs). It uses flex attention because the environment has no FA4, and skips the seed checkpoint, so both runs initialize the model themselves, from seed 42 with the same parallelism. The FSDP2 code this PR changes, the MTP layers' `param_init`, is the same here; the A/B hasn't run on this base. Co-authored-by: Wei Feng <[email protected]> ghstack-source-id: 0ca4f31 Pull-Request: #6215
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, the integration-tests-and-docs PR, the EMA PR, the DistMuon
PR and the DeepSeek V3 DistMuon recipe PR.
Summary (human-written)
Description
The DeepSeek V3 PR lets DeepSeek V3 train with FlexShard, but
FlexShardConfig.validate_modelrejects multi-token prediction (MTP) layers, for tworeasons. FlexShard summed the grads of a module that runs more than once per backward,
as the embedding and
lm_headdo with MTP layers (once per objective), in another dtypethan FSDP2. flex_shard fixes that in "Sum the grads of a module called more than once
per backward as FSDP2 does" (not merged yet). And the MTP layers' own modules didn't
initialize under FlexShard as one device would. This PR fixes the initialization and
deletes the rejection, so DeepSeek V3 with MTP layers trains with FlexShard, bitwise
identical to FSDP2, once torchtitan's CI pins a flex_shard with that fix.
An MTP layer's
enorm,hnorm,eh_projandmtp_normwere the only DeepSeek V3modules without a
param_init, soModule._init_self_parametersinitialized them withreset_parameters(). Under FSDP2, that runs on the DTensor parameter, as aparam_initwould. Under FlexShard, it would run on each rank's plain local shard, so each rank
would draw its own values, and
FlexShardConfig.validate_modelrejects any module thathas a
reset_parameters()and noparam_init._build_mtp_layers, which builds theMTP layers of every DeepSeek V3 flavor, now gives them a
param_init, asparam_init.pyasks of every module config and as DeepSeek V4's MTP layers have. Eachkeeps the initialization it had: the norms get ones (
_NORM_INIT, which is whatRMSNorm.reset_parametersdoes), andeh_projgetsnn.Linear's default,kaiming_uniform_(a=sqrt(5)), asLinear.reset_parametersapplies it (itsflatten(0, -2)returns a 2D weight itself). So FSDP2 draws the same values as before, which theA/B run below checks.
FlexShardConfig.validate_modelno longer rejects MTP layers, and loses the TODO.MTP.mddrops its FlexShard TODO section and says that FlexShard gets the same units asFSDP2.
FLEX_SHARD_FSDP.mddrops MTP layers from its rejections, and its parity testsnow cover DeepSeek V3 with an MTP layer too.
One gap stays, behind an existing rejection:
FlexShardConfig._partial_backwardsturnslm_head's gradient sync on beforeChunkedLossWrapper's last chunk, sinceFlexShardConfig.validate_modelrejectsfsdp_defer_gradient_reduction. When thatrejection is lifted, it has to keep sync off in backwards that defer reduction, with or
without MTP layers.
test_flex_shard_fsdp.pygainstest_matches_fsdp2_for_deepseek_v3_mtp(ep=1) andtest_matches_fsdp2_for_deepseek_v3_mtp_with_expert_parallelism(ep=2). Both run theparity check on DeepSeek V3's
debugmodelwith one MTP layer, as indeepseek_v3_debugmodel_mtp, withMTPCrossEntropyLosson full logits and insideChunkedLossWrapper(the recipe's loss), each with one and with two microbatches. For amodel with MTP layers, the training loop passes one routing-token count and one
loss-token count per objective.
_check_matches_fsdp2now takes the chunked-loss flagin each case instead of as an argument, and its callers pass it there, because a second
ParallelismContextin the same process trips FSDP2's mesh check ("Expected param'sDTensor mesh to be the same mesh passed to fully_shard"). The check that each FlexShard
shard is its slice of one device's initialization covers the MTP layers' parameters like
any others. It now gathers the mismatches from all ranks before it asserts: a mismatch
on one rank alone left the other waiting in training's first all-gather until the test
timed out after 300 s, without a message.
The new tests run on 4 GPUs in CI (
dp_shard=4, soedp_shard=2atep=2) and haven'trun at 4 GPUs: this machine has 2. On 2 GB200 GPUs with
world_sizeset to 2 andflex_shard's fix, they pass, as does
test_matches_fsdp2. With flex_shard at CI's pin(
d6bb546),test_matches_fsdp2_for_deepseek_v3_mtpfails at the first step of itsfirst case (plain loss, one microbatch): the grad norm differs. With the initialization
fix reverted,
FlexShardConfig.apply_to_decoderfails its assertion on an MTP layerparameter that has no
param_initto wrap. On the DeepSeek V3 PR, before this PR movedto the top of the stack, the
ep=2test failed at CI's pin the same way, as did a copywith only the chunked-loss cases.
So the multi-GPU unit-test job needs its flex_shard pin
(
.github/workflows/unit_test_gpu.yaml) moved to a commit with flex_shard's fix, inthis PR or before it; this PR leaves the pin as it is.
The FSDP2 path trains as before, bit for bit. When this PR sat on an earlier revision of
the DeepSeek V3 PR,
9d6b3a5e0,scripts/loss_compare.py 9d6b3a5e0 <this PR> --assert-equal --metrics loss,grad_norm(seed 42, deterministic, 50 steps, 2 GB200GPUs,
dp_shard=2) reported equal loss and grad norm at every step fordeepseek_v3_debugmodel_mtp(one MTP layer,ChunkedLossWrapperaroundMTPCrossEntropyLoss; step-50 loss 3.87412, training captured in CUDA graphs). It usesflex attention because the environment has no FA4, and skips the seed checkpoint, so
both runs initialize the model themselves, from seed 42 with the same parallelism. The
FSDP2 code this PR changes, the MTP layers'
param_init, is the same here; the A/Bhasn't run on this base.
Co-authored-by: Wei Feng [email protected]