Skip to content

Shard MoMa's experts under tensor parallelism - #791

Open
Naeemkh wants to merge 5 commits into
mainfrom
feat/moma-experts-sharded-under-tp
Open

Naeemkh wants to merge 5 commits into
mainfrom
feat/moma-experts-sharded-under-tp

Conversation

@Naeemkh

@Naeemkh Naeemkh commented Dec 6, 2026

Copy link
Copy Markdown
Member

Summary

This builds on #777, now merged, and replaces its skip of MoMaFFN with real sharding. cd1cc9f merges main bdaf4a4 (with #777, #775, #782 and #783) without a conflict.

  • Shard MoMa's expert groups under tensor parallelism #769: under tensor parallelism every TP rank held and ran each MoMa expert whole. _build_mlp_tp_plan (kempnerforge/distributed/tensor_parallel.py) now gives a MoMaFFN entries for every expert of every modality: mlp.experts.<modality>.experts.<i>.gate_proj and up_proj column-parallel and down_proj row-parallel, with replicated input and output layouts, so each expert's output is all-reduced over the TP group. The routers (mlp.experts.<modality>.router.gate) stay whole. An MoEMLP still gets no entries, and a MoMa block's attention plan is unchanged.
  • Routing noise. Each expert picks its top-k_e tokens, and in training the router scores carry Gumbel noise that each rank drew for itself; the TP ranks matched only because they share a seed and draw in the same order. With the experts sharded, ranks that picked different tokens would sum partial outputs of different tokens. ExpertChoiceSigmoidRouter (kempnerforge/model/moma.py) now has a noise_mesh, which apply_tensor_parallel sets to the 1-D TP mesh. In training every rank still draws its own noise, so the random number streams advance as before, and then adds the noise of the mesh's first rank, received through torch.distributed._functional_collectives.broadcast (its src is a rank within the group). Eval adds no noise and runs no broadcast. Under activation checkpointing the recompute draws the same noise again (the RNG state is restored) and broadcasts again. The router holds the mesh rather than its ProcessGroup, so a model under tensor parallelism alone can still be deep-copied (a probe holding the ProcessGroup failed with TypeError: cannot pickle 'torch._C._distributed_c10d.ProcessGroup' object; FSDP2 refuses a deep copy either way).
  • MoMaFFN adds a zero-valued term over a modality's experts when none of its tokens is routed, so their parameters get zero rather than missing gradients. That term now sums each parameter's local shard: with the experts sharded, the old sum mixed DTensors and plain tensors, and a batch whose image positions are all padding failed with RuntimeError: aten.add.Tensor got mixed torch.Tensor and DTensor (probe with the new plan and the old term).
  • JobConfig.validate (kempnerforge/config/job.py) refuses a MoMa job whose model.computed_expert_ffn_hidden_dim does not divide by distributed.tp, next to the cross-attention check, for example model.computed_expert_ffn_hidden_dim (256) must be divisible by tp (3): tensor parallelism splits the hidden dim of each MoMa expert across the tp ranks. .... Without it the first forward fails in the experts' row-parallel down_proj (probe at tp = 3 with 128-wide experts: RuntimeError: a and b must have same reduction dim, but got [4, 129] X [128, 96]). The width is a multiple of 16, so a tp of 2, 4, 8 or 16 always passes.

What a user notices:

  • A MoMa run with tp > 1 keeps 1/tp of each expert's weights, gradients and optimizer state on each rank and splits each expert's matmuls across the TP ranks, where every rank held and computed every expert whole.
  • More collectives: per expert, one all-reduce of its output in the forward, and in the backward one all-reduce of its input gradient per column-parallel projection (two for SwiGLU), as for a dense MLP without SequenceParallel; plus one broadcast per router per training forward, of that router's tokens x experts noise. CommDebugMode on the 2-layer test model at tp = 2 (8 experts, 4 routers) counts per step: forward 10 all-reduces (2 for the attention, 8 for the experts) and 4 broadcasts (none in eval); backward 22 all-reduces (6 for the attention, 16 for the experts). With the default capacity factor the experts of a modality pick about as many rows as it has tokens, so the volume is about a dense MLP's, while the number of collectives grows with the number of experts.
  • A MoMa config whose expert width tp does not divide is refused at validation, naming the width and tp.
  • Checkpoints keep the same parameter names and full shapes. A probe that saves and loads as CheckpointManager does (get_model_state_dict, dcp.save and dcp.load, set_model_state_dict) loaded a checkpoint saved by Skip MoMaFFN in the tensor-parallel plan, so no MoMa plan key goes unresolved #777's code into this branch, and one saved by this branch into Skip MoMaFFN in the tensor-parallel plan, so no MoMa plan key goes unresolved #777's code, with every parameter equal, at tp = 2 and at dp_shard = 2 x tp = 2 under FSDP2.
  • Without tensor parallelism a router draws the same noise in the same order as before, but adds the difference of its two Gumbel samples as one term, so the noised logits can differ by rounding.

Decisions taken by default, each yours to reverse:

  1. Broadcast the first TP rank's noise rather than rely on the TP ranks' shared seed. Correctness then does not depend on the random number streams staying aligned, and a misaligned stream does not fail loudly: with the broadcast removed and one extra draw on the second rank, the run trains on, the two ranks pick different tokens, and their 3-step losses (3.760695, 3.445591, 3.15929 and 3.759345, 3.446199, 3.15975) differ from each other and from a single process (3.760831, 3.445418, 3.152572). The cost is the broadcast above. To reverse: drop the broadcast and pin the shared seed with a test.
  2. One all-reduce per expert through the standard ColwiseParallel and RowwiseParallel styles, not one reduce per MoMaFFN over the summed partial outputs. A fused reduce is worth it only if a GPU profile shows that launch latency matters.
  3. The expert entries keep replicated layouts with SequenceParallel on as well, since an expert runs on the tokens its router gathered from the whole sequence. MoMa trains under tensor parallelism only with SequenceParallel off (JobConfig.validate refuses it otherwise), so this matters only to a direct apply_tensor_parallel call. Skip MoMaFFN in the tensor-parallel plan, so no MoMa plan key goes unresolved #777's plan test asserted no mlp.* entry with SequenceParallel on; the replaced test asserts the replicated expert entries instead. To reverse: give a MoMaFFN no entries when sequence_parallel is on.
  4. The noise is added as one term, as above. To reverse: broadcast both samples stacked, at twice the volume.

Docs: docs/distributed/tensor-parallelism.md (a per-MoMaBlock table under "What gets sharded", the expert width under "Head divisibility", and the VLM section), docs/configuration/validation-rules.md (the VLM section and the new rule), docs/configuration/config-sections.md (the tp rule and moma_gumbel_noise), the README's VLM paragraph, and MoMaConfig.supports_tensor_parallel's docstring.

codebase-map.json: an entry for kempnerforge/model/moma.py, which had none; MoMaConfig in kempnerforge/config/vlm.py's entry; _build_mlp_tp_plan's new prefix argument and the router's noise_mesh; TestMoMaUnderTensorParallelism(2) (test_config.py, count 175) and TestMoMaTensorParallel(3) (test_moma.py, count 66).

Testing

  • uv run ruff check . passes
  • uv run ruff format --check . passes
  • uv run pyright kempnerforge/ passes (0 errors)
  • uv run pytest tests/unit/ -v --timeout=60 passes at b76f16f, apart from the 38 failures this node's offline Hugging Face cache gives every branch, main included, none in a file this branch touches (6587 passed, 14 skipped, 46 min): 35 in test_vlm_dataset.py and 3 in test_video_dataset.py, which load the gpt2 tokenizer whose cached files were purged.
  • If distributed code changed: uv run torchrun --nproc_per_node=4 -m pytest tests/distributed/ -v: not run. tensor_parallel.py changed, but that suite needs GPUs and this branch was tested on CPU only. The gloo tests below run the new plan on 2 and 4 CPU ranks instead, under FSDP2 and activation checkpointing too.
  • If training loop / parallelism / optimizers changed: uv run pytest tests/e2e/ --e2e -v: not run, for the same reason (the e2e tests need GPUs).

New tests:

  • tests/unit/test_distributed.py: TestBuildBlockTPPlan::test_moma_block_plan_splits_every_expert, for SwiGLU and standard experts, replaces Skip MoMaFFN in the tensor-parallel plan, so no MoMa plan key goes unresolved #777's test_moma_block_plan_has_only_the_attention_projections. The plan has the four attention keys and every expert's keys, each naming a Linear, with the expected styles and replicated layouts, with SequenceParallel off and on.
  • tests/unit/test_moma.py: TestMoMaTensorParallel, which replaces Skip MoMaFFN in the tensor-parallel plan, so no MoMa plan key goes unresolved #777's one test, on gloo CPU ranks with tied embeddings:
    • test_the_attention_and_every_expert_are_sharded, at tp = 2 and at dp_shard = 2 x tp = 2 under FSDP2: no plan key is left unresolved, the attention and every expert projection are sharded over tp (Q/K/V, gate and up Shard(0), O and down Shard(1)), the routers are not and hold their TP mesh, which a deep copy of the tp = 2 model keeps, and in eval the logits and every parameter's full gradient match an unsharded copy, on a normal batch and on one whose image positions are all padding (the image experts' gradients are zero).
    • test_the_ranks_pick_the_same_tokens_when_one_draws_an_extra_number, at tp = 2 and at dp_shard = 2 x tp = 2 under FSDP2 with full activation checkpointing: with Gumbel noise on, the second rank of each TP group draws one extra random number before training, the TP ranks still pick the same tokens, and 3 SGD steps match a single process.
    • test_each_tp_group_takes_its_first_ranks_noise, on 4 ranks (dp_shard = 2 x tp = 2): ranks 2 and 3 take rank 2's noise, so the broadcast's source is the group's first rank. The 2-rank tests cannot tell this from global rank 0.
  • tests/unit/test_config.py: TestMoMaUnderTensorParallelism: widths 256 at tp = 3 and 80 at tp = 6 are refused with the message; 256 at tp = 2 passes, and so does an FFN width of 200 at tp = 3, whose experts are 192 wide.

Failing first, on #777's head 80752d6 with this branch's three test files (9 failed; the 9 others, the old plan tests and the two cases that must validate, passed):

  • test_the_attention_and_every_expert_are_sharded[tp2] and [dp_shard2_tp2]: AssertionError: ['layers.0.mlp.experts.image.experts.0.down_proj.weight', 'layers.0.mlp.experts.image.experts.0.gate_proj.weight', ..., the expert weights missing from the weights sharded over tp
  • test_the_ranks_pick_the_same_tokens_when_one_draws_an_extra_number[tp2] and [dp_shard2_tp2-full-ac]: AssertionError: TP ranks 0 and 1 picked different tokens
  • test_each_tp_group_takes_its_first_ranks_noise: AssertionError: rank 3 did not take rank 2's noise
  • test_moma_block_plan_splits_every_expert[swiglu] and [standard]: AssertionError: assert {'attention.k...ntion.v_proj'} == {'attention.k...te_proj', ...}, with the expert keys as the extra items
  • test_an_expert_hidden_dim_that_does_not_split_over_tp_is_refused[derived] and [set]: Failed: DID NOT RAISE <class 'ValueError'>

Mutants of the head, run against the same tests:

  • Without the broadcast: the two routing-noise cases and the 4-rank test fail (AssertionError: TP ranks 0 and 1 picked different tokens, AssertionError: rank 1 did not take rank 0's noise), and both sharding cases pass.
  • With the broadcast's src given as the global rank of the group's first rank: the two 4-rank cases that broadcast fail with RuntimeError: ProcessGroupGloo::broadcast: invalid root rank: 2, and the other three pass: the two 2-rank cases, since there the group's first rank is global rank 0, and the 4-rank sharding case, which runs in eval and broadcasts nothing.

Also checked:

At the merge cd1cc9f: ruff check and ruff format --check pass, pyright reports 0 errors, codebase-map.json parses with only main's known mismatches, Sphinx -W builds, and test_moma.py, test_distributed.py and test_config.py pass (683 passed).

Contribution terms

Closes #769

@Naeemkh Naeemkh added the core Affecting core label Dec 6, 2026
@amazloumi
amazloumi self-requested a review December 6, 2026 03:35
@codecov

codecov Bot commented Dec 6, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Files with missing lines Coverage Δ
kempnerforge/config/job.py 98.31% <100.00%> (+0.02%) ⬆️
kempnerforge/config/vlm.py 100.00% <ø> (ø)
kempnerforge/distributed/tensor_parallel.py 97.89% <100.00%> (+0.27%) ⬆️
kempnerforge/model/moma.py 97.05% <100.00%> (+0.18%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@amazloumi amazloumi left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Request changes. The tensor-parallel sharding, the shared routing noise and checkpoint compatibility all hold on GPU, but the noise is now added as one term on every run, so a MoMa run without tensor parallelism no longer reproduces main bit for bit (moma.py:157).

logits = self.gate(x)
if self.training and self.gumbel_noise:
logits = logits + _gumbel_like(logits) - _gumbel_like(logits)
noise = _gumbel_like(logits) - _gumbel_like(logits)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This changes the routing noise for every MoMa training run, with or without tensor parallelism, so the default path is no longer bit-equal to main: (logits + g1) - g2 and logits + (g1 - g2) round differently, and in bf16 that changes which tokens the experts pick. With the same seed and data, a 4-rank FSDP MoMa run without tensor parallelism logs grad_norm 3.250 at step 8 on this branch and 3.266 on main, and no test pins the non-tensor-parallel noise to main's.

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

core Affecting core

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Shard MoMa's expert groups under tensor parallelism

2 participants