Repository navigation
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests.
🚀 New features to boost your workflow:
|
amazloumi
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
Summary
This builds on #777, now merged, and replaces its skip of
MoMaFFNwith real sharding. cd1cc9f merges main bdaf4a4 (with #777, #775, #782 and #783) without a conflict._build_mlp_tp_plan(kempnerforge/distributed/tensor_parallel.py) now gives aMoMaFFNentries for every expert of every modality:mlp.experts.<modality>.experts.<i>.gate_projandup_projcolumn-parallel anddown_projrow-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. AnMoEMLPstill gets no entries, and a MoMa block's attention plan is unchanged.k_etokens, 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 anoise_mesh, whichapply_tensor_parallelsets 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 throughtorch.distributed._functional_collectives.broadcast(itssrcis 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 itsProcessGroup, so a model under tensor parallelism alone can still be deep-copied (a probe holding theProcessGroupfailed withTypeError: cannot pickle 'torch._C._distributed_c10d.ProcessGroup' object; FSDP2 refuses a deep copy either way).MoMaFFNadds 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 withRuntimeError: 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 whosemodel.computed_expert_ffn_hidden_dimdoes not divide bydistributed.tp, next to the cross-attention check, for examplemodel.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-paralleldown_proj(probe attp = 3with 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 atpof 2, 4, 8 or 16 always passes.What a user notices:
tp > 1keeps 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.CommDebugModeon the 2-layer test model attp = 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.tpdoes not divide is refused at validation, naming the width andtp.CheckpointManagerdoes (get_model_state_dict,dcp.saveanddcp.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, attp = 2and atdp_shard = 2xtp = 2under FSDP2.Decisions taken by default, each yours to reverse:
ColwiseParallelandRowwiseParallelstyles, not one reduce perMoMaFFNover the summed partial outputs. A fused reduce is worth it only if a GPU profile shows that launch latency matters.JobConfig.validaterefuses it otherwise), so this matters only to a directapply_tensor_parallelcall. Skip MoMaFFN in the tensor-parallel plan, so no MoMa plan key goes unresolved #777's plan test asserted nomlp.*entry with SequenceParallel on; the replaced test asserts the replicated expert entries instead. To reverse: give aMoMaFFNno entries whensequence_parallelis on.Docs:
docs/distributed/tensor-parallelism.md(a per-MoMaBlocktable 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(thetprule andmoma_gumbel_noise), the README's VLM paragraph, andMoMaConfig.supports_tensor_parallel's docstring.codebase-map.json: an entry forkempnerforge/model/moma.py, which had none;MoMaConfiginkempnerforge/config/vlm.py's entry;_build_mlp_tp_plan's newprefixargument and the router'snoise_mesh;TestMoMaUnderTensorParallelism(2)(test_config.py, count 175) andTestMoMaTensorParallel(3)(test_moma.py, count 66).Testing
uv run ruff check .passesuv run ruff format --check .passesuv run pyright kempnerforge/passes (0 errors)uv run pytest tests/unit/ -v --timeout=60passes 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 intest_vlm_dataset.pyand 3 intest_video_dataset.py, which load thegpt2tokenizer whose cached files were purged.uv run torchrun --nproc_per_node=4 -m pytest tests/distributed/ -v: not run.tensor_parallel.pychanged, 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.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'stest_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, attp = 2and atdp_shard = 2xtp = 2under FSDP2: no plan key is left unresolved, the attention and every expert projection are sharded overtp(Q/K/V, gate and upShard(0), O and downShard(1)), the routers are not and hold their TP mesh, which a deep copy of thetp = 2model 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, attp = 2and atdp_shard = 2xtp = 2under 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 = 2xtp = 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 attp = 3and 80 attp = 6are refused with the message; 256 attp = 2passes, and so does an FFN width of 200 attp = 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 overtptest_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 tokenstest_each_tp_group_takes_its_first_ranks_noise:AssertionError: rank 3 did not take rank 2's noisetest_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 itemstest_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:
AssertionError: TP ranks 0 and 1 picked different tokens,AssertionError: rank 1 did not take rank 0's noise), and both sharding cases pass.srcgiven as the global rank of the group's first rank: the two 4-rank cases that broadcast fail withRuntimeError: 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:
test_moma.pyandtest_distributed.py, 123 passed) and 803fe46 (test_config.py, 560 passed); b76f16f changes no test file. After two independent reviews, fcb4d6d runs each gloo rank of the new tests on one intra-op thread (the ranks share the CPU; with four threads each, the steps timed out under load) and narrows the MoE note intensor-parallelism.md:test_moma.pypasses (71 passed), andTestMoMaTensorParallelpasses beside 24 busy loops (5 passed, slowest case 51 s), where it timed out before.full, each training step runs the 4 routers in the forward and again in the backward recompute, and the losses still match a single process (3.760831, 3.445418, 3.152572 at every rank ofdp_shard = 2xtp = 2).torch.compile(MoMa still logs that compile is not yet validated for it): withbackend="aot_eager", the compiledtp = 2model's TP ranks pick the same tokens and its losses match the eager single process. With inductor the TP ranks pick the same tokens and agree on the losses (3.762212, 3.442275, 3.160095), which differ from the eager single process because inductor draws its random numbers its own way; a rerun withfallback_randomto confirm that hit this node's netscratchOSError: [Errno 39] Directory not emptytwice and did not finish.sphinx -W --keep-going -b html docsbuilds with no warnings.codebase-map.jsonparses, and its counts match except main's knowntest_moe.pyandtest_dataloader_iter.pyentries.git merge-tree --write-tree --name-onlyat b76f16f: the branch merges cleanly with main at 3899909 and with the open PRs Add a MathVista testmini task with answer extraction to the image-understanding evaluator #648, Reject conflicting dataset sources in job configuration #709, End finished gloo test ranks without interpreter shutdown #770, Let on_step_end hooks see the step's gradients #775, Route Muon by a declared muon_exempt marker, and let packed experts take Muon per expert #781 (which also edits the MoMa router's docstring, a paragraph away from this branch's edit), Do not save step 0 again on a resume from step_0 #782, Hold the floor leg to a release cutoff, name the CPU integration job, and state the CHANGELOG rule #783, Pin every package the dependency-floor leg installs #784 and Initialize packed experts as the unpacked experts they stack #787. The merge with main passes the three touched test files (683 passed), and itscodebase-map.jsonparses with only the two known mismatches. It conflicts with Agree on the data build across ranks and name a refused step-0 data phase #776 intests/unit/test_distributed.py(imports) andcodebase-map.json(thetest_distributed.pyclasses and count), as Skip MoMaFFN in the tensor-parallel plan, so no MoMa plan key goes unresolved #777's head already does. Keeping both sides resolves it:import torch.distributed as dist,from torch.distributed.tensor import Replicate, Shard,from kempnerforge.distributed.utils import agree_across_ranks, clip_grad_norm_and theMoMaBlockimport, andTestAgreeAcrossRanks(5),TestBuildBlockTPPlan(8)andTestApplyTensorParallelSequenceParallel(3)with count 50; the resolved merge passestest_distributed.pyandtest_moma.py(128 passed). It also conflicts with Bound the wait for an async checkpoint write with checkpoint.wait_timeout_sec #788 incodebase-map.json, on thetest_config.pycount alone (175 here, 211 there); the class lists merge on their own, so the count is 213, and the merged map then shows only the two known mismatches.At the merge cd1cc9f: ruff check and ruff format --check pass, pyright reports 0 errors,
codebase-map.jsonparses with only main's known mismatches, Sphinx-Wbuilds, andtest_moma.py,test_distributed.pyandtest_config.pypass (683 passed).Contribution terms
Closes #769