Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions codebase-map.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down Expand Up @@ -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": [
Expand Down
10 changes: 10 additions & 0 deletions docs/architecture/model.md
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,16 @@ 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: 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.
Expand Down
2 changes: 1 addition & 1 deletion docs/configuration/config-sections.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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) |

Expand Down
7 changes: 7 additions & 0 deletions docs/moe/capacity-and-dispatch.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)):

Expand Down
74 changes: 60 additions & 14 deletions kempnerforge/model/init.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -22,40 +65,43 @@ 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
same seed.
"""
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(
t.is_meta for t in (*module.parameters(recurse=False), *module.buffers(recurse=False))
):
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):
Expand Down
137 changes: 137 additions & 0 deletions tests/unit/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,25 @@
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
from kempnerforge.model.embedding import OutputHead, TokenEmbedding
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")

Expand Down Expand Up @@ -1462,6 +1468,137 @@ 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):
torch.manual_seed(0)
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 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:
"""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):
"""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)
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: ``down_w`` at the residual
std, ``gate_w`` and ``up_w`` at ``init_std``."""
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."""
Expand Down
Loading