Skip to content

Initialize packed experts as the unpacked experts they stack - #787

Merged
amazloumi merged 5 commits into
mainfrom
fix/packed-experts-residual-init-scale
Dec 6, 2026
Merged

amazloumi merged 5 commits into
mainfrom
fix/packed-experts-residual-init-scale

Conversation

@Naeemkh

@Naeemkh Naeemkh commented Dec 5, 2026 •

Copy link
Copy Markdown
Member

Summary

#779: packed experts skip the residual init scale on down_w, and from one seed get other weights than unpacked experts

Yasin filed the issue, with the analysis and a CPU reproduction.

  • init_weights picked residual output projections by name (o_proj.weight, down_proj.weight), so a packed layer's down_w was drawn at init_std, sqrt(2 * n_layers) times the init_std / sqrt(2 * n_layers) each unpacked down_proj gets (2x at 2 layers, 8x at 32). It also drew up_w, down_w and gate_w whole and before the router, since named_parameters lists the MoEMLP's own parameters before its submodules', so each MoE layer's router, experts and shared expert landed on other parts of the random stream than in the unpacked layout.
  • init_weights now leaves a packed layer's expert weights out of its main pass and draws them right after the layer's last parameter, where the unpacked layout's experts come: after the router and the shared expert. The new _init_packed_experts draws them one expert at a time, each projection in the order an unpacked expert holds them (gate_proj under SwiGLU, then up_proj and down_proj), as that expert's (out, in) weight, stored transposed, with down_w at the residual std. From one seed a packed model now starts with exactly the weights of the unpacked one: each gate_w[e], up_w[e] and down_w[e] equals the unpacked expert's weight transposed, and the routers, shared experts and all other parameters are equal. This holds for both routers, SwiGLU and standard experts, shared experts, moe_frequency > 1, MoT's per-modality MoE layers, pipeline stage modules, and meta-device builds that run to_empty and then init_weights_and_freqs.
  • One build still gives the packed experts other values: under tensor parallelism, build_parallel_model and the VLM build apply FSDP2 to the meta-device model before init, since init_distributed gives every tensor-parallel mesh a dp_shard dimension (of size 1 without data parallelism). Each packed weight is then a DTensor and cannot be written one expert at a time, so each is drawn whole at its std: down_w gets the residual std there too (main drew it at init_std), and the router and shared expert still come first.
  • Models without packed experts initialize exactly as on main. A probe built 17 model kinds from seed 0, directly and through a meta build, on main and on this branch: dense, tied embeddings, gelu, unpacked MoE with each router, shared experts, gelu experts and MoE every other layer, MoT with and without MoE, MoMa, cross-attention, and pipeline stages. All 68 sets of parameters and buffers are bit-identical. MoMa's experts are always a ModuleList of MLPs, whose down_proj.weight already takes the residual scale, so MoMa has no packed layout to fix.
  • Docs: docs/architecture/model.md (Weight initialization), docs/moe/capacity-and-dispatch.md (Packed experts) and the moe_packed_experts row in docs/configuration/config-sections.md.
  • codebase-map.json: the two new helpers in init.py, the new test class, and the test_model.py count (80 to 86).

A decision you can reverse: the same weights from one seed. The issue's second half asks that packed experts get the unpacked experts' weights from one seed. This branch does it because it is cheap and exact: per expert, one normal_ per projection into a scratch tensor the size of one expert's projection, then a transposed copy, which gives bit-identical weights (checked on CPU). It changes the order of a packed layer's draws, so a packed run started from a seed gets other router, expert and shared-expert values than on main; the scale fix alone changes every packed run's down_w anyway, and resumed runs are not affected. To fix only the scale and keep main's draws instead, drop _init_packed_experts and the reordering, and let main's loop draw a parameter whose name ends in .down_w at the residual std; the two layouts then start from the same distributions but not the same values, and #470's same-seed comparison has to copy weights from one layout into the other.

Behavior a user will notice:

  • A new packed run's MoE layers start with down_w sqrt(2 * n_layers) times smaller than on main, as unpacked runs always did.
  • From one seed, packed and unpacked runs start with the same weights (except under tensor parallelism, see above), so moe_packed_experts changes the expert kernels, not the starting point. Muon gives packed MoE experts to AdamW, unpacked ones to Newton-Schulz #470's acceptance can compare the layouts directly.
  • A packed run restarted from scratch with a seed used on main gets other MoE layer weights than it did on main. In a build without tensor parallelism, which initializes on CPU, every parameter outside the MoE layers keeps main's value, since an expert projection's element count is a multiple of 16 (computed_expert_ffn_hidden_dim is), so drawing it expert by expert takes as many draws as drawing it whole. Under tensor parallelism each packed weight is drawn whole, as on main, only after the router and shared expert; DTensor's random ops advance the generator by a tensor's full size whatever the order, so parameters outside the MoE layers keep main's values there too (checked on CPU with gloo, not on a GPU). Runs resumed from a checkpoint are not affected.

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, apart from failures this CPU batch node causes, not the branch: at 5594867, 6645 passed, 14 skipped, 39 failed. 38 are test_vlm_dataset.py (35) and test_video_dataset.py (3), which need the Hugging Face gpt2 files the offline test cache no longer holds (LocalEntryNotFoundError). The other is test_hooks.py::TestActivationStoreParallel::test_whole_block_outputs_are_gathered_to_the_full_tensor[dp_shard2_tp2], where a rank hit OSError: [Errno 39] Directory not empty while removing its temporary directory on netscratch. That case passes alone on this branch (twice in a row); on main 3899909 it failed once with the same error and then passed. Runs of the whole file hit the same error in one or two of its dp_shard2_tp2 cases (41 passed, 2 failed in the last). Those tests build a dense model, whose init this branch leaves bit-identical.
  • If distributed code changed: uv run torchrun --nproc_per_node=4 -m pytest tests/distributed/ -v: not run, it needs 4 GPUs and this round ran on CPU only. No distributed code changed; the DTensor path that FSDP2 leaves before init is covered by a two-rank gloo unit test. Training never runs the per-expert draws on a GPU: a build without tensor parallelism initializes on CPU, and a build with it takes the whole-tensor DTensor path. That path was not run on CUDA.
  • If training loop / parallelism / optimizers changed: uv run pytest tests/e2e/ --e2e -v: not run, it needs GPUs. Only initial values change.

New tests in tests/unit/test_model.py::TestPackedExpertInit: the std of each packed weight against the unpacked layout's (SwiGLU, gelu, sigmoid router, shared expert, MoE every other layer), the same weights from one seed for the same five cases, a meta-device build, MoT, a meta model left on the meta device, and a two-rank FSDP2-sharded meta build, which checks that each packed weight is a DTensor drawn at its std (down_w at the residual std, gate_w and up_w at init_std).

Failing first, on main bdaf4a4 with this branch's tests at c9833a3 (13 of the 14 fail):

  • test_down_w_gets_the_residual_std (5 cases): AssertionError: layers.0.mlp.down_w, assert 0.02008027955889702 == 0.005 ± 2.5e-04 (8 layers, so the residual std is 0.02 / 4).
  • test_one_seed_gives_both_layouts_the_same_weights (5 cases), test_a_meta_build_gets_the_same_weights and test_mot_experts_get_the_same_weights: AssertionError: layers.0.mlp.up_w[0] (layers.1.mlp.up_w[0] with MoE every other layer, layers.0.mlp.image.up_w[0] for MoT), the first packed slice that differs from the unpacked expert.
  • test_a_sharded_meta_build_draws_down_w_at_the_residual_std: a rank raises AssertionError: layers.0.mlp.down_w.
  • test_a_meta_model_stays_on_the_meta_device passes on main too. It checks that init leaves a meta model on the meta device; it runs the early return for meta weights but would still pass without it, since drawing into meta tensors does nothing.

Also checked:

  • A mutant that draws gate_w at the residual std on the DTensor path fails only test_a_sharded_meta_build_draws_down_w_at_the_residual_std (AssertionError: layers.0.mlp.gate_w); before c9833a3 it passed all 14 cases.
  • The issue's reproduction on this branch: every packed tensor equals the stacked unpacked one ("same values: True" for all six), and 0 of 17 parameters outside the experts differ (main: 2, the routers).
  • Sphinx -W builds the docs, and map_counts.py reports only main's known mismatches.

The full unit suite ran at 5594867. The first review round added two commits: 80283cf9 says that every tensor-parallel build draws packed experts whole (docs/architecture/model.md, the moe_packed_experts row in docs/configuration/config-sections.md, and the meta-build test's docstring), and b28793d1 seeds the ranks of the two-rank FSDP2 test, so it is deterministic. At 80283cf9 ruff, ruff format, Sphinx -W and test_model.py pass (180 passed, 3 skipped). At b28793d1 ruff, ruff format, pyright (0 errors), Sphinx -W and the map counts pass, and test_model.py with test_moe.py pass (328 passed, 3 skipped). A third commit, c9833a33, has the two-rank test check every packed weight's std, gate_w included, after the review found that it checked only down_w and up_w. At c9833a33 ruff and ruff format pass, and test_model.py passes (180 passed, 3 skipped). The full suite was not rerun, since these commits change wording, one test seed and one test.

The head merges cleanly with main bdaf4a4, and with each open PR: #788 (afab6c32, and its main merge 89d601c8), #789 (db64875f), #781 (506fb678), #776 (d4e569bf), #709 (991b0b6a) and #648 (dce0ff8e). Each merged codebase-map.json parses and shows only main's known count mismatches. #788 at afab6c32, #781, #776 and #648 conflict with main on their own; merged with this head directly they do not conflict.

Contribution terms

Closes #779

@Naeemkh Naeemkh added the core Affecting core label Dec 5, 2026
@Naeemkh
Naeemkh requested a review from amazloumi December 5, 2026 22:52
@codecov

codecov Bot commented Dec 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Files with missing lines Coverage Δ
kempnerforge/model/init.py 98.38% <100.00%> (+1.16%) ⬆️

... and 6 files with indirect coverage changes

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

Thanks, Packed experts now start with exactly the unpacked experts' weights and down_w gets the residual std; non-packed models initialize bit-identically to main, and the tensor-parallel exception behaves as documented on GPU. just the test covering comment below and it will be good to go.

Comment thread tests/unit/test_model.py Resolved

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

Approve. The sharded test now covers every packed weight, which settles the one point from the last review, and the head passes the full test gate merged with current main.

@amazloumi
amazloumi merged commit 5392e1b into main Dec 6, 2026
15 checks passed
@amazloumi
amazloumi deleted the fix/packed-experts-residual-init-scale branch December 6, 2026 06:22
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.

Packed MoE experts skip the residual init scale on down_w, and from one seed their MoE layers get other weights than with unpacked experts

2 participants