From f71b6d2b5400f04c2f6f999910512f59f7077be8 Mon Sep 17 00:00:00 2001 From: naeemkh Date: Sat, 5 Dec 2026 15:23:29 -0500 Subject: [PATCH 1/5] Initialize packed experts as the unpacked experts they stack --- codebase-map.json | 14 ++-- kempnerforge/model/init.py | 74 +++++++++++++++++---- tests/unit/test_model.py | 132 +++++++++++++++++++++++++++++++++++++ 3 files changed, 201 insertions(+), 19 deletions(-) diff --git a/codebase-map.json b/codebase-map.json index 1a845ed44..9baee9a7e 100644 --- a/codebase-map.json +++ b/codebase-map.json @@ -639,12 +639,15 @@ ] }, "kempnerforge/model/init.py": { - "purpose": "Standard initialization: Linear+Embedding ~ N(0, init_std); residual o_proj/down_proj scaled by 1/sqrt(2*n_layers); cross-attention block o_proj/down_proj zero-init; MoT per-modality o_proj.{m}.weight + mlp.{m}.down_proj.weight zero-init via a second isinstance pass (MoTAttention / MoTBlock)", + "purpose": "Standard initialization: Linear+Embedding ~ N(0, init_std); residual o_proj/down_proj scaled by 1/sqrt(2*n_layers); packed MoE experts drawn as the unpacked experts they stack (after the layer's router and shared expert, one expert at a time in the (out, in) layout, down_w at the residual scale), so one seed gives both layouts the same weights; cross-attention block o_proj/down_proj zero-init; MoT per-modality o_proj.{m}.weight + mlp.{m}.down_proj.weight zero-init via a second isinstance pass (MoTAttention / MoTBlock)", "functions": [ - "init_weights(model, config)" + "init_weights(model, config)", + "_init_parameter(name, param, std, residual_std) (one parameter by its name; skips meta and below-2-D parameters)", + "_init_packed_experts(moe, std, residual_std) (a packed MoEMLP's experts as the unpacked layout draws them; a DTensor weight, as FSDP2 leaves a meta build under tensor parallelism, is drawn whole at the same std)" ], "tested_by": [ - "tests/unit/test_model.py::TestInitWeights" + "tests/unit/test_model.py::TestInitWeights", + "tests/unit/test_model.py::TestPackedExpertInit" ] }, "kempnerforge/model/moe.py": { @@ -1948,9 +1951,10 @@ "TestModalityIdsCrossArgs(3)", "TestCrossAttentionInterleaving(10)", "TestMoT(10)", - "TestInitWeights(5)" + "TestInitWeights(5)", + "TestPackedExpertInit(6)" ], - "count": 80 + "count": 86 }, "tests/unit/test_config.py": { "classes": [ diff --git a/kempnerforge/model/init.py b/kempnerforge/model/init.py index d4523b788..9691978ac 100644 --- a/kempnerforge/model/init.py +++ b/kempnerforge/model/init.py @@ -4,7 +4,9 @@ import math +import torch import torch.nn as nn +from torch.distributed.tensor import DTensor from kempnerforge.config.schema import ModelConfig from kempnerforge.model.moe import MoEMLP @@ -13,6 +15,47 @@ from kempnerforge.model.router import SigmoidTopKRouter _RESETS_OWN_STATE = (RMSNorm, nn.LayerNorm, SigmoidTopKRouter) +_RESIDUAL_PROJECTIONS = ("o_proj.weight", "down_proj.weight") + + +def _init_parameter(name: str, param: nn.Parameter, std: float, residual_std: float) -> None: + """Draw ``param`` by its name; leave it as it is on the meta device or below 2 dims.""" + if param.is_meta or param.dim() < 2: + return + if name.startswith("cross_attention_layers.") and name.endswith(_RESIDUAL_PROJECTIONS): + nn.init.zeros_(param) + elif name.endswith(_RESIDUAL_PROJECTIONS): + nn.init.normal_(param, mean=0.0, std=residual_std) + else: + nn.init.normal_(param, mean=0.0, std=std) + + +def _init_packed_experts(moe: MoEMLP, std: float, residual_std: float) -> None: + """Draw a packed layer's expert weights as the unpacked layout draws its experts. + + Expert by expert, each projection, in the order an unpacked expert holds them + (``gate_proj`` under SwiGLU, then ``up_proj`` and ``down_proj``), is drawn as + that expert's ``(out, in)`` weight and stored transposed, the down projection + at the residual std, so one seed gives both layouts the same weights. A DTensor + weight, as FSDP2 leaves it before a meta-device build under tensor parallelism + is initialized, cannot be written one expert at a time, so each projection is + then drawn whole at the same std. + """ + names = ("gate_w", "up_w", "down_w") if moe._is_swiglu else ("up_w", "down_w") + weights = [getattr(moe, name) for name in names] + stds = [residual_std if name == "down_w" else std for name in names] + if any(weight.is_meta for weight in weights): + return + if any(isinstance(weight, DTensor) for weight in weights): + for weight, weight_std in zip(weights, stds, strict=True): + nn.init.normal_(weight, mean=0.0, std=weight_std) + return + draws = [weight.new_empty(weight.shape[2], weight.shape[1]) for weight in weights] + with torch.no_grad(): + for expert in range(moe.down_w.shape[0]): + for weight, draw, weight_std in zip(weights, draws, stds, strict=True): + nn.init.normal_(draw, mean=0.0, std=weight_std) + weight[expert].copy_(draw.t()) def init_weights(model: nn.Module, config: ModelConfig) -> None: @@ -22,12 +65,20 @@ def init_weights(model: nn.Module, config: ModelConfig) -> None: - Linear layers: normal(0, 0.02) - Embedding layers: normal(0, 0.02) - - Residual output projections (o_proj, down_proj): scaled by 1/sqrt(2 * n_layers) + - Residual output projections (o_proj, down_proj, and a packed MoE layer's + down_w): scaled by 1/sqrt(2 * n_layers) - Cross-attention block residuals: zero-initialized (identity-at-init warm-start) - MoT per-modality residual projections: zero-initialized (identity-at-construction) - Norm layers and the sigmoid router's own state: reset to their construction-time values, which a meta-device build does not preserve + Parameters are drawn in ``named_parameters`` order, which lists a module's own + parameters before its submodules'. That order puts a packed MoE layer's expert + weights, which belong to the ``MoEMLP`` itself, before its router, so they are + drawn after the layer's last parameter instead, where the unpacked layout's + ``experts`` come, one expert at a time (see ``_init_packed_experts``): from one + seed, both layouts get the same weights. + Only the modules in ``_RESETS_OWN_STATE`` are reset, and only with deterministic fills: a blanket ``reset_parameters()`` would also run ``nn.Linear``'s kaiming init, which draws from the RNG and changes every weight drawn after it for the @@ -35,6 +86,7 @@ def init_weights(model: nn.Module, config: ModelConfig) -> None: """ std = config.init_std residual_scale = 1.0 / math.sqrt(2.0 * config.n_layers) + residual_std = std * residual_scale for module in model.modules(): if isinstance(module, _RESETS_OWN_STATE) and not any( @@ -42,20 +94,14 @@ def init_weights(model: nn.Module, config: ModelConfig) -> None: ): module.reset_parameters() + packed = [m for m in model.modules() if isinstance(m, MoEMLP) and m.packed_experts] + expert_weights = {id(weight) for moe in packed for weight in moe._expert_params()} + drawn_after = {id(list(moe.parameters())[-1]): moe for moe in packed} for name, param in model.named_parameters(): - if param.is_meta: - continue - if param.dim() < 2: - continue - - if name.startswith("cross_attention_layers.") and name.endswith( - ("o_proj.weight", "down_proj.weight") - ): - nn.init.zeros_(param) - elif name.endswith(("o_proj.weight", "down_proj.weight")): - nn.init.normal_(param, mean=0.0, std=std * residual_scale) - else: - nn.init.normal_(param, mean=0.0, std=std) + if id(param) not in expert_weights: + _init_parameter(name, param, std, residual_std) + if id(param) in drawn_after: + _init_packed_experts(drawn_after[id(param)], std, residual_std) for module in model.modules(): if isinstance(module, MoTAttention): diff --git a/tests/unit/test_model.py b/tests/unit/test_model.py index dec7f5117..eb1e1394a 100644 --- a/tests/unit/test_model.py +++ b/tests/unit/test_model.py @@ -9,9 +9,13 @@ import pytest import torch import torch.nn.functional as F +from torch.distributed.device_mesh import init_device_mesh +from torch.distributed.tensor import DTensor from torch.nn.attention.flex_attention import BlockMask, create_block_mask from kempnerforge.config.schema import ModelConfig +from kempnerforge.config.vlm import MoTConfig +from kempnerforge.distributed.parallel import apply_fsdp2 from kempnerforge.distributed.pipeline_parallel import PipelineStageModule from kempnerforge.distributed.tensor_parallel import apply_tensor_parallel from kempnerforge.model.attention import Attention, KVCache @@ -19,9 +23,11 @@ from kempnerforge.model.init import init_weights from kempnerforge.model.mlp import StandardMLP, SwiGLUMLP, build_mlp from kempnerforge.model.modality import ModalityContext +from kempnerforge.model.moe import MoEMLP from kempnerforge.model.norm import RMSNorm, build_norm from kempnerforge.model.position import apply_rope, precompute_rope_frequencies from kempnerforge.model.transformer import Transformer, TransformerBlock +from tests.gloo_ranks import gloo_group, spawn DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") @@ -1462,6 +1468,132 @@ def test_skips_meta_parameters(self): init_weights(model, _INIT_CONFIG) +_PACKED_INIT = dict( + dim=64, n_layers=8, n_heads=4, vocab_size=128, max_seq_len=16, num_experts=4, moe_top_k=2 +) +_PACKED_PROJECTIONS = {"gate_w": "gate_proj", "up_w": "up_proj", "down_w": "down_proj"} +_LAYOUT_CASES = pytest.mark.parametrize( + "overrides", + [ + {}, + {"activation": "gelu"}, + {"moe_router": "sigmoid_topk"}, + {"moe_shared_experts": 1}, + {"moe_frequency": 2}, + ], + ids=["swiglu", "gelu", "sigmoid_router", "shared_expert", "every_other_layer"], +) + + +def _both_layouts( + *, meta: bool = False, vlm_config: MoTConfig | None = None, **overrides +) -> tuple[Transformer, Transformer]: + """An unpacked and a packed model, each built from seed 0. + + With ``meta``, each is built on the meta device, materialized with ``to_empty``, filled + with NaN so a weight that init skips shows, and initialized with ``init_weights_and_freqs``. + """ + extra = {"vlm_config": vlm_config, "num_image_tokens": 4} if vlm_config else {} + models = [] + for packed in (False, True): + config = ModelConfig(**{**_PACKED_INIT, **overrides}, moe_packed_experts=packed) + torch.manual_seed(0) + if not meta: + models.append(Transformer(config, **extra)) + continue + with torch.device("meta"): + model = Transformer(config, **extra) + model.to_empty(device="cpu") + with torch.no_grad(): + for param in model.parameters(): + param.fill_(float("nan")) + model.init_weights_and_freqs() + models.append(model) + return models[0], models[1] + + +def _moe_layers(model: Transformer) -> list[tuple[str, MoEMLP]]: + return [(name, m) for name, m in model.named_modules() if isinstance(m, MoEMLP)] + + +def _assert_same_weights(unpacked: Transformer, packed: Transformer) -> None: + """Each expert's slice of a packed weight is that unpacked expert's weight transposed, + and every other parameter is equal.""" + reference = dict(unpacked.named_parameters()) + for name, param in packed.named_parameters(): + layer, _, attr = name.rpartition(".") + if attr not in _PACKED_PROJECTIONS: + assert torch.equal(param, reference[name]), name + continue + for expert in range(param.shape[0]): + weight = reference[f"{layer}.experts.{expert}.{_PACKED_PROJECTIONS[attr]}.weight"] + assert torch.equal(param[expert], weight.t()), f"{name}[{expert}]" + + +def _check_sharded_meta_build(rank: int, world: int, port: int) -> None: + with gloo_group(rank, world, port): + config = ModelConfig(**_PACKED_INIT, moe_packed_experts=True) + with torch.device("meta"): + model = Transformer(config) + apply_fsdp2(model, init_device_mesh("cpu", (world,), mesh_dim_names=("dp_shard",))) + model.to_empty(device="cpu") + model.init_weights_and_freqs() + residual = config.init_std / math.sqrt(2.0 * config.n_layers) + for name, moe in _moe_layers(model): + assert isinstance(moe.down_w, DTensor), name + down, up = moe.down_w.full_tensor(), moe.up_w.full_tensor() + assert down.std().item() == pytest.approx(residual, rel=0.05), f"{name}.down_w" + assert up.std().item() == pytest.approx(config.init_std, rel=0.05), f"{name}.up_w" + + +class TestPackedExpertInit: + """Packed experts start as the unpacked experts they stack (#779): the same draws, one + expert at a time after the layer's router and shared expert, with ``down_w`` at the + residual std ``init_std / sqrt(2 * n_layers)`` that each unpacked ``down_proj`` gets.""" + + @_LAYOUT_CASES + def test_down_w_gets_the_residual_std(self, overrides): + unpacked, packed = _both_layouts(**overrides) + config = packed.config + residual = config.init_std / math.sqrt(2.0 * config.n_layers) + layers = zip(_moe_layers(packed), _moe_layers(unpacked), strict=True) + for (name, moe), (_, reference) in layers: + down_proj = torch.stack([e.down_proj.weight for e in reference.experts]) + assert down_proj.std().item() == pytest.approx(residual, rel=0.05), name + for attr in _PACKED_PROJECTIONS: + if hasattr(moe, attr): + expected = residual if attr == "down_w" else config.init_std + std = getattr(moe, attr).std().item() + assert std == pytest.approx(expected, rel=0.05), f"{name}.{attr}" + + @_LAYOUT_CASES + def test_one_seed_gives_both_layouts_the_same_weights(self, overrides): + _assert_same_weights(*_both_layouts(**overrides)) + + def test_a_meta_build_gets_the_same_weights(self): + """The build under tensor parallelism: ``to_empty``, then ``init_weights_and_freqs``.""" + unpacked, packed = _both_layouts(meta=True, moe_router="sigmoid_topk", moe_shared_experts=1) + _assert_same_weights(unpacked, packed) + residual = packed.config.init_std / math.sqrt(2.0 * packed.config.n_layers) + for name, moe in _moe_layers(packed): + assert moe.down_w.std().item() == pytest.approx(residual, rel=0.05), f"{name}.down_w" + + def test_mot_experts_get_the_same_weights(self): + """A MoT layer holds one ``MoEMLP`` per modality.""" + _assert_same_weights(*_both_layouts(vlm_config=MoTConfig(max_text_len=8))) + + def test_a_meta_model_stays_on_the_meta_device(self): + with torch.device("meta"): + model = Transformer(ModelConfig(**_PACKED_INIT, moe_packed_experts=True)) + init_weights(model, model.config) + assert all(p.is_meta for p in model.parameters()) + + def test_a_sharded_meta_build_draws_down_w_at_the_residual_std(self): + """FSDP2 shards a meta build before init, as the build under tensor parallelism does, + so each packed weight is a DTensor that init draws whole.""" + spawn(_check_sharded_meta_build, 2) + + def _decoupled_config(**kw) -> ModelConfig: """dim=64, n_heads=8, head_dim=16 -> a 128-wide attention over a 64-wide residual. n_heads * head_dim (128) != dim (64) on purpose.""" From 5594867b3d35d326b7ed4592e5ac847bea08985e Mon Sep 17 00:00:00 2001 From: naeemkh Date: Sat, 5 Dec 2026 15:23:29 -0500 Subject: [PATCH 2/5] Document how packed experts are initialized --- docs/architecture/model.md | 9 +++++++++ docs/configuration/config-sections.md | 2 +- docs/moe/capacity-and-dispatch.md | 7 +++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/docs/architecture/model.md b/docs/architecture/model.md index 525cec373..8b9ee8e8b 100644 --- a/docs/architecture/model.md +++ b/docs/architecture/model.md @@ -340,6 +340,15 @@ applies the GPT-2 / Llama convention: - Parameters whose name ends in `o_proj.weight` or `down_proj.weight` get scaled by `1 / sqrt(2 * n_layers)`. Without this, the residual stream's variance grows linearly with depth. +- Packed experts (`moe_packed_experts = true`) are drawn as the unpacked + experts they stack: after the layer's router and shared expert, one + expert at a time, each projection drawn in a linear layer's `(out, in)` + layout and stored transposed, with `down_w` at the same + `1 / sqrt(2 * n_layers)` scale as `down_proj`. From one seed, both + layouts start with the same weights. The exception is a build under + tensor parallelism that also has a data-parallel dimension: FSDP2 shards + its meta-device model before init, so each packed weight is drawn whole, + at the same scales but with other values. - Biases and norm weights are left at their defaults (zeros and ones). - Meta-device parameters are skipped — `init_weights_and_freqs()` runs after materialization. diff --git a/docs/configuration/config-sections.md b/docs/configuration/config-sections.md index 79b9d8b49..0d679d118 100644 --- a/docs/configuration/config-sections.md +++ b/docs/configuration/config-sections.md @@ -94,7 +94,7 @@ Architecture hyperparameters and MoE knobs. | `moe_sequence_aux_loss_weight` | `float` | `0.0` | sequence-level balance loss (0 = off) | | `moe_gradient_scale` | `bool` | `False` | per-expert gradient normalization | | `moe_bias_schedule` | `str` | `"constant"` | `"constant"`, `"cosine_decay"`, `"linear_warmup"` | -| `moe_packed_experts` | `bool` | `False` | pack expert weights into one tensor per projection | +| `moe_packed_experts` | `bool` | `False` | pack expert weights into one tensor per projection; initialized as unpacked experts are, so from one seed both layouts start with the same weights (see [Model § Weight initialization](../architecture/model.md#weight-initialization)) | | `moe_expert_ffn_multiplier` | `float` | `1.0` | expert FFN hidden width relative to dense (`0.5` → fine-grained) | | `moe_router_z_loss_weight` | `float` | `0.0` | router-logit z-loss coefficient (`0` = off) | diff --git a/docs/moe/capacity-and-dispatch.md b/docs/moe/capacity-and-dispatch.md index d12e1d14f..8721d8f44 100644 --- a/docs/moe/capacity-and-dispatch.md +++ b/docs/moe/capacity-and-dispatch.md @@ -179,6 +179,13 @@ Grouped GEMM consumes these directly via `grouped_expert_forward_packed` — no per-step `torch.stack` over the `ModuleList`, and FSDP2 wraps three tensors instead of `3 × E`. +`init_weights` then draws the packed tensors as it draws unpacked +experts: one expert at a time, with `down_w` at the residual scale +`init_std / sqrt(2 * n_layers)`, so from one seed a packed model starts +with the weights of the unpacked one (see +[Model § Weight initialization](../architecture/model.md#weight-initialization) +for the one build where it does not). + Measured impact (see [Benchmark § MoE Expert Packing](https://github.com/KempnerInstitute/KempnerForge/tree/main/benchmarks/moe_packed)): From 80283cf992e63433586c98afaddcdaee68143cd5 Mon Sep 17 00:00:00 2001 From: naeemkh Date: Sat, 5 Dec 2026 16:51:18 -0500 Subject: [PATCH 3/5] Say that every tensor-parallel build draws packed experts whole --- docs/architecture/model.md | 7 ++++--- docs/configuration/config-sections.md | 2 +- tests/unit/test_model.py | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/architecture/model.md b/docs/architecture/model.md index 8b9ee8e8b..f5b3caa15 100644 --- a/docs/architecture/model.md +++ b/docs/architecture/model.md @@ -346,9 +346,10 @@ applies the GPT-2 / Llama convention: layout and stored transposed, with `down_w` at the same `1 / sqrt(2 * n_layers)` scale as `down_proj`. From one seed, both layouts start with the same weights. The exception is a build under - tensor parallelism that also has a data-parallel dimension: FSDP2 shards - its meta-device model before init, so each packed weight is drawn whole, - at the same scales but with other values. + tensor parallelism: its device mesh always has a `dp_shard` dimension + (of size 1 without data parallelism), so FSDP2 shards the meta-device + model before init, and each packed weight is drawn whole, at the same + scales but with other values. - Biases and norm weights are left at their defaults (zeros and ones). - Meta-device parameters are skipped — `init_weights_and_freqs()` runs after materialization. diff --git a/docs/configuration/config-sections.md b/docs/configuration/config-sections.md index 0d679d118..26a91c052 100644 --- a/docs/configuration/config-sections.md +++ b/docs/configuration/config-sections.md @@ -94,7 +94,7 @@ Architecture hyperparameters and MoE knobs. | `moe_sequence_aux_loss_weight` | `float` | `0.0` | sequence-level balance loss (0 = off) | | `moe_gradient_scale` | `bool` | `False` | per-expert gradient normalization | | `moe_bias_schedule` | `str` | `"constant"` | `"constant"`, `"cosine_decay"`, `"linear_warmup"` | -| `moe_packed_experts` | `bool` | `False` | pack expert weights into one tensor per projection; initialized as unpacked experts are, so from one seed both layouts start with the same weights (see [Model § Weight initialization](../architecture/model.md#weight-initialization)) | +| `moe_packed_experts` | `bool` | `False` | pack expert weights into one tensor per projection; initialized as unpacked experts are, so from one seed both layouts start with the same weights outside tensor-parallel builds (see [Model § Weight initialization](../architecture/model.md#weight-initialization)) | | `moe_expert_ffn_multiplier` | `float` | `1.0` | expert FFN hidden width relative to dense (`0.5` → fine-grained) | | `moe_router_z_loss_weight` | `float` | `0.0` | router-logit z-loss coefficient (`0` = off) | diff --git a/tests/unit/test_model.py b/tests/unit/test_model.py index eb1e1394a..6ef1f967a 100644 --- a/tests/unit/test_model.py +++ b/tests/unit/test_model.py @@ -1571,7 +1571,7 @@ def test_one_seed_gives_both_layouts_the_same_weights(self, overrides): _assert_same_weights(*_both_layouts(**overrides)) def test_a_meta_build_gets_the_same_weights(self): - """The build under tensor parallelism: ``to_empty``, then ``init_weights_and_freqs``.""" + """An unsharded meta-device build: ``to_empty``, then ``init_weights_and_freqs``.""" unpacked, packed = _both_layouts(meta=True, moe_router="sigmoid_topk", moe_shared_experts=1) _assert_same_weights(unpacked, packed) residual = packed.config.init_std / math.sqrt(2.0 * packed.config.n_layers) From b28793d1d34af17cb3bdc3f37b2289d2b3986687 Mon Sep 17 00:00:00 2001 From: naeemkh Date: Sat, 5 Dec 2026 16:53:24 -0500 Subject: [PATCH 4/5] Seed the ranks of the sharded packed-expert init test --- tests/unit/test_model.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/unit/test_model.py b/tests/unit/test_model.py index 6ef1f967a..ab146fa80 100644 --- a/tests/unit/test_model.py +++ b/tests/unit/test_model.py @@ -1532,6 +1532,7 @@ def _assert_same_weights(unpacked: Transformer, packed: Transformer) -> None: def _check_sharded_meta_build(rank: int, world: int, port: int) -> None: with gloo_group(rank, world, port): + torch.manual_seed(0) config = ModelConfig(**_PACKED_INIT, moe_packed_experts=True) with torch.device("meta"): model = Transformer(config) From c9833a33b1e42ee481756543cc01589b6c31a655 Mon Sep 17 00:00:00 2001 From: naeemkh Date: Sat, 5 Dec 2026 21:05:57 -0500 Subject: [PATCH 5/5] Check gate_w's std in the sharded packed-expert init test --- tests/unit/test_model.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/tests/unit/test_model.py b/tests/unit/test_model.py index ab146fa80..f0c5c72ab 100644 --- a/tests/unit/test_model.py +++ b/tests/unit/test_model.py @@ -1541,10 +1541,13 @@ def _check_sharded_meta_build(rank: int, world: int, port: int) -> None: model.init_weights_and_freqs() residual = config.init_std / math.sqrt(2.0 * config.n_layers) for name, moe in _moe_layers(model): - assert isinstance(moe.down_w, DTensor), name - down, up = moe.down_w.full_tensor(), moe.up_w.full_tensor() - assert down.std().item() == pytest.approx(residual, rel=0.05), f"{name}.down_w" - assert up.std().item() == pytest.approx(config.init_std, rel=0.05), f"{name}.up_w" + assert moe._is_swiglu, name + for attr in _PACKED_PROJECTIONS: + weight = getattr(moe, attr) + assert isinstance(weight, DTensor), f"{name}.{attr}" + expected = residual if attr == "down_w" else config.init_std + std = weight.full_tensor().std().item() + assert std == pytest.approx(expected, rel=0.05), f"{name}.{attr}" class TestPackedExpertInit: @@ -1591,7 +1594,8 @@ def test_a_meta_model_stays_on_the_meta_device(self): def test_a_sharded_meta_build_draws_down_w_at_the_residual_std(self): """FSDP2 shards a meta build before init, as the build under tensor parallelism does, - so each packed weight is a DTensor that init draws whole.""" + so each packed weight is a DTensor that init draws whole: ``down_w`` at the residual + std, ``gate_w`` and ``up_w`` at ``init_std``.""" spawn(_check_sharded_meta_build, 2)