Repository navigation
[MoE] Support padding masks in load balancing - #4594
Conversation
| input_ids_src_placement = token_id_placement() | ||
| input_ids_dst_placement = ( | ||
| token_id_sequence_parallel_placement() | ||
| if enable_sp and enable_ep |
There was a problem hiding this comment.
this is an intentional bug fix introduced in https://github.com/pytorch/torchtitan/pull/4490/changes#diff-4470b7d1c2056fee681bb0713ed8b980cec39a894a9d83e712e949ea2b2eb09cL293
as we always enable SP for MoE
@YeonwooSung please correct me if I am misunderstanding anything
There was a problem hiding this comment.
You have it right for the configuration that is actually used, but the enable_sp and half is load-bearing for one combination, so token_id_placement(enable_sp=enable_ep) is not equivalent to what is there today.
SP is on by default but not enforced. enable_sp comes from parallelism.enable_sequence_parallel (a user-settable field, default True) and enable_ep from expert_parallel_degree > 1; nothing ties them together, so --parallelism.enable_sequence_parallel=False with expert_parallel_degree > 1 is reachable.
That combination is exactly the one the conditional was protecting, because of _moe_sharding_config in torchtitan/models/common/moe_sharding.py:
sp_layout = (
dense_sequence_parallel_placement() if enable_sp
else dense_activation_placement(tp=spmd.I, cp=spmd.S(0))
)
desired_input_layout = (
sp_layout if enable_ep else dense_activation_placement(tp=spmd.R, cp=spmd.S(0))
)With EP on and SP off, x_TD's TP axis is I, not S(0) -- each rank still holds the full T. So the rule is not "EP decides whether x is sequence-parallel", it is "EP and SP together decide it". Under this PR the hash ids become S(0) on TP while x_TD stays full-T, which puts tid2eid[input_ids_T] back to indexing a T/tp-sized id tensor against a full-T activation -- the same class of mismatch #4490 fixed (CI showed scores[256, 4] vs ids[512, 3], just from the other direction). Today's else token_id_placement() keeps both sides full T, so the shapes agree even though the configuration is otherwise a bit odd.
Two ways to get the simplification you want:
- Keep the two-condition form (
enable_sp and enable_ep). Mergingtoken_id_sequence_parallel_placementintotoken_id_placement(enable_sp=...)is a nice cleanup on its own; it just wantsenable_sp=enable_sp and enable_epat this call site. - If EP without SP should not be a supported configuration, make that explicit -- reject it (or force SP) in
ParallelismConfig.__post_init__-- and thenenable_sp=enable_epreally is equivalent and the invariant is checked rather than assumed.
One thing to flag either way: this PR deletes tests/unit_tests/cpu/test_deepseek_v4_hash_sharding.py entirely, and test_ep_without_sp_keeps_hash_input_ids_replicated_on_tp in it is the test that covers this case. The token_id_sequence_parallel_placement assertions in test_parallel_dims.py go too, and I did not find replacement coverage for the hash-routing placement in the new tests. If the helper rename is what made the file awkward to keep, updating the imports would keep the coverage; as it stands the change to the condition and the removal of the test that would catch it land together.
Happy to be wrong about the EP-without-SP path if there is a constraint I have missed -- I could not run anything locally here, so this is from reading moe_sharding.py and the config, not from a repro.
tianyu-l
left a comment
There was a problem hiding this comment.
very nice, identified some loose ends.
| positions: torch.Tensor | None = None, | ||
| attention_masks: AttentionMasksType | None = None, | ||
| *, | ||
| padding_mask: torch.Tensor | None = None, |
There was a problem hiding this comment.
hoping to make non-tokens, all optional fields to kwargs, but could be a followup
| h_TD, | ||
| attention_masks, | ||
| positions, | ||
| padding_mask=padding_mask, |
There was a problem hiding this comment.
I thought muse glimmer is dense only
| *, | ||
| enable_ep: bool, | ||
| enable_sp: bool, | ||
| padding_mask_sequence_sharded: bool = False, |
There was a problem hiding this comment.
confused by why we need this -- I had thought
- padding mask sharding should always follow token sharding
- enable_sp and enable_ep are enough to determine padding's sharding
There was a problem hiding this comment.
I think this is for MTP only, added comment
# Regular decoder layers pass the TP-replicated model input mask directly
# to MoE. MTP redistributes the mask to sequence-sharded before calling its
# nested MoE. This flag describes the mask layout at the MoE boundary so an
# already-sharded MTP mask is not sharded again.
There was a problem hiding this comment.
I didn't get this. In my mind MTP treatment wouldn't be very different from regular decoder. Could you give an example where they have to be different.
There was a problem hiding this comment.
padding mask sharding should always follow token sharding
I think you are right. Previously we have tokens S(0) but padding mask R for MoE blocks, and for MTP will redistribute padding mask to S(0). So for MTP layers, I need a way to specify that the padding mask is already sharded to avoid double sharding.
Now I changed the padding mask to be S(0) at MoE block level, same as tokens, by introducing set_moe_block_padding_mask_sharding.
| mtp_input_embed: torch.Tensor, | ||
| prev_embed: torch.Tensor, | ||
| mtp_input_valid_mask: torch.Tensor, | ||
| mtp_input_valid_mask_T: torch.Tensor, |
There was a problem hiding this comment.
other args don't have shape suffix
There was a problem hiding this comment.
yeah I thought it would be more easier to understand if we add shape for mask, especially when doing mask manipulation.
let me remove, since we don't have shape annotations for things like positions and prev_embed anyways.
| padding_mask=( | ||
| ~mtp_input_valid_mask_T | ||
| if padding_mask_T is None | ||
| else ~mtp_input_valid_mask_T | padding_mask_T | ||
| ), |
There was a problem hiding this comment.
code structure looks a bit different between v3 mtp and v4 mtp -- here it looks more succinct
There was a problem hiding this comment.
V4 delegates the full block to super().forward(), while V3 implements the MoE branch inline. The mask semantics are identical.
| with torch.no_grad(): | ||
| self.tokens_per_expert_E.add_(masked_routing_map_TE.sum(dim=0)) |
There was a problem hiding this comment.
I feel this would be helpful for inference as well -- can we move it out of if self.training?
There was a problem hiding this comment.
we don't want to update during inference/eval as it could potentially leak into the next step's expert_bias_E update?
There was a problem hiding this comment.
expert_bias_E is never updated in inference
There was a problem hiding this comment.
yes but I thought #4148 introduces this bug fix to prevent accumulating this value during eval, which will pollute the next optimizer.update.
There was a problem hiding this comment.
oh ... right, that's when it happens on the same instance. OK I agree with keeping it not accumulated for inference for now.
There was a problem hiding this comment.
need to rebase onto #4631 and fix deepseekv3 as well
| ) | ||
|
|
||
|
|
||
| def _validate_padding_mask( |
There was a problem hiding this comment.
nit: let's put this inline to make the boundary clear
| if padding_mask_T is not None: | ||
| probs_TE = probs_TE * ~padding_mask_T.unsqueeze(-1) |
There was a problem hiding this comment.
after this, I believe we are making this line legit https://github.com/pytorch/torchtitan/blob/main/torchtitan/trainer.py#L912
see discussions in #3864 (comment)
cc @sdmyzlp
| ) | ||
| input_sharding = decoder_input_sharding() | ||
| for depth in depths: | ||
| mtp_input_tokens, mtp_input_valid_mask = roll_mtp_sequence( |
There was a problem hiding this comment.
I think we need to roll the padding_mask as well?
There was a problem hiding this comment.
In fact, I think for MTP https://github.com/pytorch/torchtitan/blob/main/torchtitan/trainer.py#L912 is invalid for MTP modules' AuxLoss, as each MTP module should have its own global_valid_tokens. Not sure what's the most clean way to fix.
There was a problem hiding this comment.
yes I missed that. Now passed in padding mask and it will update the mtp_input_valid_mask.
There was a problem hiding this comment.
@acisseJZhong where did you assign it? I was hoping on the trainer AuxLoss.set_step_denominator call.
Could you also make a GH issue?
There was a problem hiding this comment.
In fact, I think for MTP https://github.com/pytorch/torchtitan/blob/main/torchtitan/trainer.py#L912 is invalid for MTP modules'
AuxLoss, as each MTP module should have its ownglobal_valid_tokens. Not sure what's the most clean way to fix.
Got it, will take a look at this.
7ecc074 to
69cf626
Compare
tianyu-l
left a comment
There was a problem hiding this comment.
regarding #4594 (comment), at least add a NOTE / TODO around https://github.com/pytorch/torchtitan/blob/main/torchtitan/trainer.py#L912
dafe4bc to
422f129
Compare
6f70bf3 to
02c2983
Compare
|
landing this PR, the failing test https://github.com/pytorch/torchtitan/actions/runs/34900521241/job/104165936715?pr=4594 seems to be pre-existing. See #4535 (comment) |
02c2983 to
5ad23ef
Compare
## Summary - pass an explicit Sigmoid score function to the padding-mask router tests - align the tests added by #4594 with the required score_func API introduced by #4609 - fix the two CPU test failures observed in the PR #2769 CI job ## Test plan - pytest -q tests/unit_tests/cpu/test_moe.py - pre-commit hooks for ufmt, flake8, pydoclint, and codespell on tests/unit_tests/cpu/test_moe.py
….forward pytorch#4594 added padding_mask to the block contract -- Decoder.forward passes it by keyword to EVERY layer (models/common/decoder.py:249). Our moe block predates that, so every rank died in the first forward with TypeError: moeTransformerBlock.forward() got an unexpected keyword argument 'padding_mask' (job 12477668, after the init fix cleared the unflatten errors). The dense arms were unaffected because Llama3TransformerBlock already accepts it. Consume and discard, exactly as llama3 does (llama3/model.py:53). It feeds varlen attention metadata, which this block does not build -- blendcorpus emits fixed-length rows, so there is no padding to mask. Worth noting an earlier adversarial review flagged this exact parameter and we jointly refuted it as unreachable, reasoning that the block takes no **kwargs so the kwarg could not arrive. The signature observation was right; the conclusion was backwards -- no **kwargs is precisely why it raises.
feaa538 added the pytorch#4594 padding_mask parameter to Attention.forward instead of moeTransformerBlock.forward, so job 12477669 died with the exact same TypeError as 12477668. Decoder.forward passes padding_mask to the LAYER (models/common/decoder.py:249); Attention is called positionally from inside the block and never sees it. Verified by class, not by line number: the earlier check read lines 121-127, which is Attention.forward -- the block's forward is at 234.
Found by auditing the tree for the defect just fixed in moe/model.py rather than waiting for it to surface. Both classes subclass Llama3TransformerBlock -- which does accept padding_mask -- but override forward with the pre-pytorch#4594 signature, so the override is what the decoder calls and both would die on the first forward with the same TypeError the moe block hit (jobs 12477668-12477669). Neither block is exercised by the sync-84 smoke, so this would have stayed silent until the next fp32-residual 80B run. Audited by enclosing class: all 3 block classes in experiments/ezpz now accept padding_mask.
Job 12477670 on sunspot workq, torch 2.14.0+xpu: all three arms rc=0 with zero non-finite loss/grad_norm. moe trains 12.95236 -> 12.59633 -> 11.47142. Records the three stacked moe fixes (striped fused-gate-up init under uneven FSDP sharding, pytorch#4594 padding_mask, and the misplaced-edit repeat), plus the tree audit that caught the same padding_mask defect in both fp32-residual blocks.
Second, separate sync: sync 84 landed and was verified on three
machines first, so if one of these 22 breaks something it is isolated
against a known-good baseline rather than tangled with 148 commits.
Audited as inert for ezpz before merging:
- decoder_sharding.py renames RowParallelLinear ->
AsyncRowParallelLinear and DistGEMMFeedForward -> a w13 check.
ezpz has ZERO references to either (positive-controlled grep).
- common/moe.py adds an OPTIONAL padding_mask_T to the router. ezpz
configures the router rather than subclassing it and defines no
forward that receives it. Unlike pytorch#4594's padding_mask, which is
passed positionally to every block, this one defaults to None.
- overrides/fused_swiglu.py is a Triton int64 cast fixing an
infinite grad_norm on interleaved gate/up -- same w13 structure we
just fixed -- but it lives in an override no ezpz config enables.
- pytorch#4593 is graph_trainer/simple_fsdp, not our FSDP path.
Upstream touches 0 files under experiments/ezpz in this delta.
|
hey, i have a question @acisseJZhong. should we consider extend this "padding mask" to, in general, "no-loss-tokens"? |
@rakkit do you know if others have this similar conclusion, any reports? or any other framework does this? It makes sense to exclude padding tokens from load balance as they are meaningless, but prompt tokens are meaningful? |

Summary
padding_maskthrough decoder, MoE, and MTP pathsThis follows the separation between execution routing and padding-filtered statistics used by the Megatron-LM router implementation. The no-mask path is unchanged.
Test results
2x H100, FP32, deterministic seed 42, TP=2, EP=2.
Follow-up