Skip to content

[MoE] Support padding masks in load balancing - #4594

Merged
acisseJZhong merged 9 commits into
mainfrom
padding_mask
Sep 14, 2026
Merged

acisseJZhong merged 9 commits into
mainfrom
padding_mask

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • propagate padding_mask through decoder, MoE, and MTP paths
  • validate padding masks against the routing-map token axis, then build one padding-filtered routing map for expert counts and auxiliary load-balancing statistics
  • preserve the original routing map for dispatch, and shard the mask with router tokens under expert parallelism

This 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.

Test Before loss (steps 1, 2) After loss (steps 1, 2) Result
DeepSeek V3, no padding, SP 8.06509018, 6.36459827 8.06509018, 6.36459827 Exact match
DeepSeek V3, padding, SP 7.92675018, 5.56190205 7.92675018, 5.56203842 Step 1 exact; step 2 +0.00013638 after the padding-aware update
DeepSeek V3, padding, no SP N/A 7.92675018, 5.56203842 Exact match with the after-SP run
DeepSeek V4 hash router, padding, SP 8.15526104, 5.90886402 8.15526104, 5.90848827 Step 1 exact; step 2 -0.00037575 after the padding-aware expert-bias update

Follow-up

  • assign padding tokens to experts round-robin to balance dispatch and expert compute, while continuing to exclude them from auxiliary loss, expert-bias updates, and usage metrics

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 11, 2026
@acisseJZhong acisseJZhong changed the title [MoE] Support padding masks in load balancing [do not review][MoE] Support padding masks in load balancing Sep 11, 2026
input_ids_src_placement = token_id_placement()
input_ids_dst_placement = (
token_id_sequence_parallel_placement()
if enable_sp and enable_ep

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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:

  1. Keep the two-condition form (enable_sp and enable_ep). Merging token_id_sequence_parallel_placement into token_id_placement(enable_sp=...) is a nice cleanup on its own; it just wants enable_sp=enable_sp and enable_ep at this call site.
  2. If EP without SP should not be a supported configuration, make that explicit -- reject it (or force SP) in ParallelismConfig.__post_init__ -- and then enable_sp=enable_ep really 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.

@acisseJZhong
acisseJZhong marked this pull request as ready for review September 12, 2026 07:10
@acisseJZhong acisseJZhong changed the title [do not review][MoE] Support padding masks in load balancing [MoE] Support padding masks in load balancing Sep 12, 2026

@tianyu-l tianyu-l 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.

very nice, identified some loose ends.

Comment on lines 250 to +253
positions: torch.Tensor | None = None,
attention_masks: AttentionMasksType | None = None,
*,
padding_mask: torch.Tensor | None = 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.

hoping to make non-tokens, all optional fields to kwargs, but could be a followup

Comment thread torchtitan/models/muse_glimmer/model.py Outdated
h_TD,
attention_masks,
positions,
padding_mask=padding_mask,

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.

I thought muse glimmer is dense only

*,
enable_ep: bool,
enable_sp: bool,
padding_mask_sequence_sharded: bool = False,

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.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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.

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.

@acisseJZhong acisseJZhong Sep 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread torchtitan/models/deepseek_v3/mtp.py Outdated
mtp_input_embed: torch.Tensor,
prev_embed: torch.Tensor,
mtp_input_valid_mask: torch.Tensor,
mtp_input_valid_mask_T: torch.Tensor,

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.

other args don't have shape suffix

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +74 to +78
padding_mask=(
~mtp_input_valid_mask_T
if padding_mask_T is None
else ~mtp_input_valid_mask_T | padding_mask_T
),

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.

code structure looks a bit different between v3 mtp and v4 mtp -- here it looks more succinct

@acisseJZhong acisseJZhong Sep 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

V4 delegates the full block to super().forward(), while V3 implements the MoE branch inline. The mask semantics are identical.

Comment on lines +417 to +418
with torch.no_grad():
self.tokens_per_expert_E.add_(masked_routing_map_TE.sum(dim=0))

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.

I feel this would be helpful for inference as well -- can we move it out of if self.training?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#4148

we don't want to update during inference/eval as it could potentially leak into the next step's expert_bias_E update?

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.

expert_bias_E is never updated in inference

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes but I thought #4148 introduces this bug fix to prevent accumulating this value during eval, which will pollute the next optimizer.update.

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.

oh ... right, that's when it happens on the same instance. OK I agree with keeping it not accumulated for inference for now.

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.

need to rebase onto #4631 and fix deepseekv3 as well

Comment thread torchtitan/models/common/moe.py Outdated
)


def _validate_padding_mask(

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.

nit: let's put this inline to make the boundary clear

Comment on lines +553 to +554
if padding_mask_T is not None:
probs_TE = probs_TE * ~padding_mask_T.unsqueeze(-1)

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.

)
input_sharding = decoder_input_sharding()
for depth in depths:
mtp_input_tokens, mtp_input_valid_mask = roll_mtp_sequence(

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.

I think we need to roll the padding_mask as well?

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.

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.

cc @sdmyzlp @Matrix-Z97

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes I missed that. Now passed in padding mask and it will update the mtp_input_valid_mask.

@acisseJZhong acisseJZhong Sep 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

assigned the todo to @sdmyzlp

@tianyu-l tianyu-l Sep 14, 2026 •

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.

@acisseJZhong where did you assign it? I was hoping on the trainer AuxLoss.set_step_denominator call.

Could you also make a GH issue?

@acisseJZhong acisseJZhong Sep 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added it here. also created #4682

Image

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

cc @sdmyzlp @Matrix-Z97

Got it, will take a look at this.

@acisseJZhong
acisseJZhong force-pushed the padding_mask branch 2 times, most recently from 7ecc074 to 69cf626 Compare September 13, 2026 07:05

@tianyu-l tianyu-l 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.

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@acisseJZhong
acisseJZhong merged commit d34a13f into main Sep 14, 2026
6 of 8 checks passed
acisseJZhong added a commit that referenced this pull request Sep 15, 2026
## 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
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Sep 16, 2026
….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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Sep 16, 2026
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Sep 16, 2026
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Sep 17, 2026
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Sep 17, 2026
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.
@rakkit

rakkit commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

hey, i have a question @acisseJZhong.

should we consider extend this "padding mask" to, in general, "no-loss-tokens"?
for case like sft, the user prompts usually not count in loss, and it is not "padding token". for me it is a bit weird to update expert's load balance for bias or loss. from our experiment, exclude these tokens for load-balance helped a lot in SFT. publicly i only see times ago a russian model discussed about this.

@acisseJZhong

Copy link
Copy Markdown
Contributor Author

exclude these tokens for load-balance helped a lot in SFT.

@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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

5 participants