Skip to content

Commit 8693678

Browse files
justinchubyCopilot
andauthored
refactor: keep gate_up_proj fused, split activations in MLP forward (#155)
## Problem `split_gate_up_proj` in `preprocess_weights` assumes an uncompressed weight tensor. For GPTQ int32-packed weights, `dim 0 = original_dim / pack_factor`, causing a build failure: ``` gate_up weight dim 0 is 2048, expected 16384 ``` ## Solution Instead of fixing the split logic, remove all weight splitting entirely. The `gate_up_proj` weight stays fused; activations are split after the matmul: ```python gate_up = gate_up_proj(x) # [*, 2 * intermediate_size] gate, up = Split(gate_up, axis=-1) # each [*, intermediate_size] return down_proj(act(gate) * up) ``` This is cleaner, future-proof, and matches HuggingFace weight names exactly — no `preprocess_weights` renames needed for `gate_up_proj`. ## Changes - **`components/_mlp.py`**: Add `FusedGateUpMLP` — single `gate_up_proj` param, split activations in forward - **`components/_decoder.py`**: Add `mlp_class` param to `DecoderLayer` / `create_decoder_layer` - **`models/base.py`**: Add `FusedGateUpCausalLMModel`; `TextModel` accepts `mlp_class` - **`models/phi3.py`**: Extend `FusedGateUpCausalLMModel`; remove gate_up split from `preprocess_weights` - **`models/phi.py`**: Remove gate_up_proj split from `_preprocess_phi4mm_weights`; all LoRA decoder layers use `FusedGateUpMLP`; fix `num_kv_heads` → `num_key_value_heads` bug in LoRA B split - **`models/glm.py`**: Remove `_split_gate_up_proj` private function; `GlmCausalLMModel` extends `FusedGateUpCausalLMModel`; `Glm4DecoderLayer` uses `FusedGateUpMLP` - **`models/__init__.py`**: Export `FusedGateUpCausalLMModel` ## Testing 2352 tests pass, 29 skipped. Lintrunner clean. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot <[email protected]>
1 parent 170f28a commit 8693678

9 files changed

Lines changed: 184 additions & 98 deletions

File tree

‎src/mobius/components/__init__.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
"EncoderDecoderAttention",
3030
"EncoderLayer",
3131
"FCMLP",
32+
"FusedGateUpMLP",
3233
"GatedDeltaNet",
3334
"GatedMLP",
3435
"GatedRMSNorm",
@@ -175,7 +176,7 @@
175176
from mobius.components._lightning_attention import LightningAttention
176177
from mobius.components._lora import LoRALinear
177178
from mobius.components._mamba_block import Mamba2Block, MambaBlock
178-
from mobius.components._mlp import FCMLP, MLP, GatedMLP
179+
from mobius.components._mlp import FCMLP, MLP, FusedGateUpMLP, GatedMLP
179180
from mobius.components._moe import (
180181
MoELayer,
181182
SigmoidTopKGate,

‎src/mobius/components/_decoder.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,10 @@ class DecoderLayer(nn.Module):
4141
linear_class: Factory callable ``(in_features, out_features, bias=...)``
4242
for creating projection layers in Attention and MLP. Defaults to
4343
``Linear``. Pass a LoRA factory for LoRA-adapted layers.
44+
mlp_class: MLP module class to use (default: :class:`~mobius.components.MLP`).
45+
Pass :class:`~mobius.components.FusedGateUpMLP` for models that store
46+
the gate and up projections as a single fused ``gate_up_proj`` weight
47+
(e.g. Phi-3, Phi-4, GLM).
4448
"""
4549

4650
def __init__(
@@ -52,10 +56,13 @@ def __init__(
5256
attention_scale: float | None = None,
5357
post_norm: bool = False,
5458
linear_class: type | None = None,
59+
mlp_class: type | None = None,
5560
):
5661
super().__init__()
5762
if norm_class is None:
5863
norm_class = RMSNorm
64+
if mlp_class is None:
65+
mlp_class = MLP
5966

6067
self._post_norm = post_norm
6168
self._residual_multiplier = residual_multiplier
@@ -66,7 +73,7 @@ def __init__(
6673
scale=attention_scale,
6774
linear_class=linear_class,
6875
)
69-
self.mlp = MLP(config, linear_class=linear_class)
76+
self.mlp = mlp_class(config, linear_class=linear_class)
7077

7178
if post_norm:
7279
self.post_attention_layernorm = norm_class(
@@ -185,6 +192,7 @@ def create_decoder_layer(
185192
norm_class: type[nn.Module] | None = None,
186193
post_norm: bool = False,
187194
linear_class: type | None = None,
195+
mlp_class: type | None = None,
188196
) -> DecoderLayer:
189197
"""Config-driven factory for creating decoder layers.
190198
@@ -200,6 +208,8 @@ def create_decoder_layer(
200208
post_norm: If True, use post-norm residual connections (OLMo-2 style).
201209
linear_class: Factory callable for projection layers. Pass a LoRA
202210
factory for LoRA-adapted layers.
211+
mlp_class: MLP module class override (default: MLP). Pass
212+
FusedGateUpMLP for models with fused gate_up_proj weights.
203213
204214
Returns:
205215
A configured DecoderLayer instance.
@@ -214,6 +224,7 @@ def create_decoder_layer(
214224
attention_scale=attention_scale,
215225
post_norm=post_norm,
216226
linear_class=linear_class,
227+
mlp_class=mlp_class,
217228
)
218229

219230

‎src/mobius/components/_mlp.py‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,53 @@ def forward(self, op: builder.OpBuilder, x: ir.Value) -> ir.Value:
9898
return self.down_proj(op, op.Mul(gate, self.up_proj(op, x)))
9999

100100

101+
class FusedGateUpMLP(nn.Module):
102+
"""Gated MLP that keeps gate and up projections as one fused weight.
103+
104+
The ``gate_up_proj`` tensor (shape ``[2*intermediate_size, hidden_size]``)
105+
is stored as a single parameter, matching HuggingFace checkpoints for
106+
Phi-3, Phi-4, and GLM family models. Activations are split after the
107+
fused MatMul — no weight splitting is required in ``preprocess_weights``.
108+
109+
Forward pass::
110+
111+
gate_up = gate_up_proj(x) # [*, 2 * intermediate_size]
112+
gate, up = split(gate_up, axis=-1) # each [*, intermediate_size]
113+
return down_proj(act(gate) * up)
114+
115+
Use this instead of :class:`MLP` when the HuggingFace checkpoint stores
116+
gate and up projections as a single fused ``gate_up_proj`` weight. This
117+
avoids splitting the weight tensor at load time, which fails for GPTQ
118+
int32-packed weights where dim 0 is ``original / pack_factor``.
119+
120+
Args:
121+
config: Architecture configuration.
122+
linear_class: Factory callable ``(in_features, out_features, bias=...)``
123+
for creating projection layers. Defaults to ``Linear``.
124+
"""
125+
126+
def __init__(self, config: ArchitectureConfig, linear_class: type | None = None):
127+
super().__init__()
128+
if linear_class is None:
129+
linear_class = Linear
130+
# Single fused weight: [2*intermediate_size, hidden_size]
131+
self.gate_up_proj = linear_class(
132+
config.hidden_size, 2 * config.intermediate_size, bias=config.mlp_bias
133+
)
134+
self.down_proj = linear_class(
135+
config.intermediate_size, config.hidden_size, bias=config.mlp_bias
136+
)
137+
self.act_fn = get_activation(config.hidden_act)
138+
139+
def forward(self, op: builder.OpBuilder, x: ir.Value) -> ir.Value:
140+
# Fused matmul → [*, 2 * intermediate_size]
141+
gate_up = self.gate_up_proj(op, x)
142+
# Split activations at intermediate_size boundary
143+
gate, up = op.Split(gate_up, axis=-1, num_outputs=2, _outputs=2)
144+
# gated activation (e.g. SiLU(gate) * up) → down_proj
145+
return self.down_proj(op, op.Mul(self.act_fn(op, gate), up))
146+
147+
101148
class FCMLP(nn.Module):
102149
"""Two-layer fully-connected MLP: ``up_proj → activation → down_proj``.
103150

‎src/mobius/components/_mlp_test.py‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
create_test_input,
1212
make_config,
1313
)
14-
from mobius.components._mlp import FCMLP, MLP, GatedMLP
14+
from mobius.components._mlp import FCMLP, MLP, FusedGateUpMLP, GatedMLP
1515

1616

1717
class TestMLP:
@@ -230,3 +230,58 @@ def __init__(self, *args, **kwargs):
230230
assert isinstance(mlp.gate_proj, TrackingLinear)
231231
assert isinstance(mlp.up_proj, TrackingLinear)
232232
assert isinstance(mlp.down_proj, TrackingLinear)
233+
234+
235+
class TestFusedGateUpMLP:
236+
"""Tests for FusedGateUpMLP (fused gate_up_proj, split activations)."""
237+
238+
def test_projection_shapes(self):
239+
config = make_config(hidden_size=64, intermediate_size=128)
240+
mlp = FusedGateUpMLP(config)
241+
# gate_up_proj: [2*intermediate, hidden]
242+
assert list(mlp.gate_up_proj.weight.shape) == [256, 64]
243+
assert list(mlp.down_proj.weight.shape) == [64, 128]
244+
245+
def test_parameter_count(self):
246+
config = make_config(hidden_size=64, intermediate_size=128)
247+
mlp = FusedGateUpMLP(config)
248+
# gate_up_proj.weight + down_proj.weight = 2 (no bias by default)
249+
assert len(list(mlp.parameters())) == 2
250+
251+
def test_forward_builds_graph(self):
252+
config = make_config(hidden_size=64, intermediate_size=128)
253+
mlp = FusedGateUpMLP(config)
254+
builder, op, graph = create_test_builder()
255+
x = create_test_input(builder, "x", [1, 8, 64])
256+
result = mlp(op, x)
257+
builder._adapt_outputs([result])
258+
assert graph.num_nodes() > 0
259+
# gate_up_proj MatMul + down_proj MatMul = 2
260+
assert count_op_type(graph, "MatMul") == 2
261+
# Split activations along last axis
262+
assert count_op_type(graph, "Split") == 1
263+
264+
def test_forward_uses_silu_by_default(self):
265+
config = make_config(hidden_size=64, intermediate_size=128, hidden_act="silu")
266+
mlp = FusedGateUpMLP(config)
267+
builder, op, graph = create_test_builder()
268+
x = create_test_input(builder, "x", [1, 8, 64])
269+
mlp(op, x)
270+
# SiLU = x * sigmoid(x)
271+
assert count_op_type(graph, "Sigmoid") >= 1
272+
273+
def test_linear_class_applied(self):
274+
from mobius.components._common import Linear
275+
276+
created = []
277+
278+
class TrackingLinear(Linear):
279+
def __init__(self, *args, **kwargs):
280+
super().__init__(*args, **kwargs)
281+
created.append(self)
282+
283+
config = make_config(hidden_size=64, intermediate_size=128)
284+
mlp = FusedGateUpMLP(config, linear_class=TrackingLinear)
285+
assert len(created) == 2
286+
assert isinstance(mlp.gate_up_proj, TrackingLinear)
287+
assert isinstance(mlp.down_proj, TrackingLinear)

‎src/mobius/models/__init__.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
"CLIPVisionModel",
1717
"CTRLCausalLMModel",
1818
"CausalLMModel",
19+
"FusedGateUpCausalLMModel",
1920
"ChatGLMCausalLMModel",
2021
"CodeGenCausalLMModel",
2122
"CogVideoXTransformer3DModel",
@@ -125,7 +126,7 @@
125126
from mobius.models.arcee import ArceeCausalLMModel
126127
from mobius.models.bamba import BambaCausalLMModel
127128
from mobius.models.bart import BartForConditionalGeneration
128-
from mobius.models.base import CausalLMModel, LayerNormCausalLMModel
129+
from mobius.models.base import CausalLMModel, FusedGateUpCausalLMModel, LayerNormCausalLMModel
129130
from mobius.models.bert import BertModel
130131
from mobius.models.blip2 import Blip2Model
131132
from mobius.models.chatglm import ChatGLMCausalLMModel

‎src/mobius/models/base.py‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
from mobius.components import (
2929
DecoderLayer,
3030
Embedding,
31+
FusedGateUpMLP,
3132
LayerNorm,
3233
Linear,
3334
RMSNorm,
@@ -42,7 +43,7 @@
4243
class TextModel(nn.Module):
4344
"""Base text model with embedding, decoder layers, and final norm."""
4445

45-
def __init__(self, config: ArchitectureConfig):
46+
def __init__(self, config: ArchitectureConfig, mlp_class: type | None = None):
4647
super().__init__()
4748
self._dtype = config.dtype
4849

@@ -62,7 +63,7 @@ def __init__(self, config: ArchitectureConfig):
6263
)
6364
self.layers = nn.ModuleList(
6465
[
65-
DecoderLayer(config, linear_class=linear_class)
66+
DecoderLayer(config, linear_class=linear_class, mlp_class=mlp_class)
6667
for _ in range(config.num_hidden_layers)
6768
]
6869
)
@@ -277,3 +278,24 @@ def __init__(self, config: ArchitectureConfig):
277278
super().__init__(config)
278279
# Replace TextModel with the LayerNorm-based variant.
279280
self.model = LayerNormTextModel(config)
281+
282+
283+
class FusedGateUpCausalLMModel(CausalLMModel):
284+
"""CausalLM variant that keeps gate_up_proj fused (no weight splitting).
285+
286+
Use this instead of ``CausalLMModel`` for architectures where HuggingFace
287+
stores the gate and up projections as a single fused ``gate_up_proj``
288+
weight — e.g. Phi-3, Phi-4, and GLM.
289+
290+
The MLP forward pass does a single ``gate_up_proj`` MatMul and splits the
291+
resulting activations, rather than splitting the weights at load time.
292+
This is robust to GPTQ int32-packed weights where dimension 0 is
293+
``original / pack_factor`` and weight splitting would fail.
294+
295+
``preprocess_weights`` does NOT need to split ``gate_up_proj``.
296+
"""
297+
298+
def __init__(self, config: ArchitectureConfig):
299+
super().__init__(config)
300+
# Parameterize TextModel to use FusedGateUpMLP for each decoder layer.
301+
self.model = TextModel(config, mlp_class=FusedGateUpMLP)

‎src/mobius/models/glm.py‎

Lines changed: 11 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -24,57 +24,29 @@
2424

2525
from typing import TYPE_CHECKING
2626

27-
import torch
2827
from onnxscript import nn
2928
from onnxscript._internal import builder
3029

3130
from mobius._configs import ArchitectureConfig
3231
from mobius.components._attention import StaticCacheState
3332
from mobius.components._decoder import DecoderLayer
33+
from mobius.components._mlp import FusedGateUpMLP
3434
from mobius.components._rms_norm import RMSNorm
35-
from mobius.models.base import CausalLMModel, TextModel
35+
from mobius.models.base import CausalLMModel, FusedGateUpCausalLMModel, TextModel
3636

3737
if TYPE_CHECKING:
3838
import onnx_ir as ir
3939

4040

41-
def _split_gate_up_proj(
42-
state_dict: dict[str, torch.Tensor],
43-
) -> dict[str, torch.Tensor]:
44-
"""Split fused ``gate_up_proj`` into separate ``gate_proj`` + ``up_proj``.
45-
46-
HF GLM/GLM4 store: ``mlp.gate_up_proj.weight`` [2*intermediate, hidden]
47-
ONNX MLP expects: ``mlp.gate_proj.weight`` [intermediate, hidden]
48-
``mlp.up_proj.weight`` [intermediate, hidden]
49-
"""
50-
new_state_dict: dict[str, torch.Tensor] = {}
51-
for key, value in state_dict.items():
52-
if ".mlp.gate_up_proj." in key:
53-
# Split along dim 0: first half = gate, second half = up
54-
mid = value.shape[0] // 2
55-
gate_key = key.replace(".gate_up_proj.", ".gate_proj.")
56-
up_key = key.replace(".gate_up_proj.", ".up_proj.")
57-
new_state_dict[gate_key] = value[:mid]
58-
new_state_dict[up_key] = value[mid:]
59-
else:
60-
new_state_dict[key] = value
61-
return new_state_dict
62-
63-
64-
class GlmCausalLMModel(CausalLMModel):
41+
class GlmCausalLMModel(FusedGateUpCausalLMModel):
6542
"""GLM text model (standard pre-norm + fused gate_up_proj).
6643
6744
GLM is architecturally identical to LLaMA except for the fused
68-
``gate_up_proj`` in the MLP. ``preprocess_weights`` splits it into
69-
separate ``gate_proj`` + ``up_proj`` tensors.
45+
``gate_up_proj`` in the MLP. The weight stays fused; activations
46+
are split in the MLP forward pass (see
47+
:class:`~mobius.models.base.FusedGateUpCausalLMModel`).
7048
"""
7149

72-
def preprocess_weights(
73-
self, state_dict: dict[str, torch.Tensor]
74-
) -> dict[str, torch.Tensor]:
75-
state_dict = _split_gate_up_proj(state_dict)
76-
return super().preprocess_weights(state_dict)
77-
7850

7951
# ---------------------------------------------------------------------------
8052
# GLM4: 4-norm decoder layer (pre+post norm on both attention and MLP)
@@ -102,9 +74,8 @@ class Glm4DecoderLayer(DecoderLayer):
10274
"""
10375

10476
def __init__(self, config: ArchitectureConfig):
105-
# Initialize the base DecoderLayer (pre-norm mode) to get
106-
# input_layernorm, post_attention_layernorm, self_attn, mlp.
107-
super().__init__(config)
77+
# Initialize the base DecoderLayer with FusedGateUpMLP
78+
super().__init__(config, mlp_class=FusedGateUpMLP)
10879

10980
# Add the two extra post-sub-layer norms
11081
self.post_self_attn_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
@@ -156,8 +127,9 @@ def forward(
156127
class Glm4CausalLMModel(CausalLMModel):
157128
"""GLM4 text model (4-norm decoder + fused gate_up_proj).
158129
159-
Uses ``Glm4DecoderLayer`` with pre+post norms on both sub-layers,
160-
and splits the fused ``gate_up_proj`` in ``preprocess_weights``.
130+
Uses ``Glm4DecoderLayer`` with pre+post norms on both sub-layers.
131+
``gate_up_proj`` is kept fused — activations are split in the MLP
132+
forward pass (via :class:`FusedGateUpMLP` in ``Glm4DecoderLayer``).
161133
"""
162134

163135
def __init__(self, config: ArchitectureConfig):
@@ -169,12 +141,6 @@ def __init__(self, config: ArchitectureConfig):
169141

170142
self.lm_head = Linear(config.hidden_size, config.vocab_size, bias=False)
171143

172-
def preprocess_weights(
173-
self, state_dict: dict[str, torch.Tensor]
174-
) -> dict[str, torch.Tensor]:
175-
state_dict = _split_gate_up_proj(state_dict)
176-
return super().preprocess_weights(state_dict)
177-
178144

179145
class Glm4TextModel(TextModel):
180146
"""GLM4 text model backbone using 4-norm decoder layers."""

0 commit comments

Comments
 (0)