Skip to content

Commit 70de6ad

Browse files
committed
fix(qwen35): thread linear_class through self_attn/linear_attn/shared_expert
Qwen35Attention, GatedDeltaNet, and Qwen2MoELayer's shared_expert (reused by Qwen35MoEBlock) all hardcoded plain Linear regardless of config.quantization, unlike the generic Attention/MLP classes used elsewhere in Mobius. Since Mobius rebuilds the ONNX graph from scratch rather than tracing the PyTorch model, this meant the corresponding initializer slots were always built expecting dense float weights -- so a quantized checkpoint's packed uint8 tensors for these modules could never load, failing with a shape mismatch (or, before #491's suffix fix, "initializer without weights"). Fix: - Add an optional `linear_class` constructor parameter to Qwen35Attention (q/k/v/o_proj) and GatedDeltaNet (in_proj_qkv/z/b/a, out_proj), matching the pattern already used by the generic Attention/MLP classes. GatedDeltaNet's dt_bias/A_log/conv1d.weight are small recurrent-state parameters and are intentionally left unquantized regardless of this argument. - Add an optional `linear_class` parameter to Qwen2MoELayer for its shared_expert/shared_expert_gate (the routed experts are already quantized separately via the fused QMoE path, driven directly by config.quantization -- this only covers the always-active shared expert, which isn't part of that fused op). Defaults to None (plain Linear), so existing Qwen2MoEDecoderLayer callers are unaffected. - Add a `_linear_factory(config)` helper in qwen35.py (mirrors the existing pattern in deepseek.py) and thread it through Qwen35DecoderLayer/Qwen35MoEDecoderLayer's self_attn/linear_attn/mlp construction. Verified end-to-end: Olive Rtn(bits=4, group_size=16, sym=true, moe=true) -> MobiusBuilder against optimum-intel-internal-testing/tiny-random-qwen3.5-moe now succeeds without excluding linear_attn/shared_expert via modules_to_not_convert -- self_attn/linear_attn/shared_expert weights save as quantized u8 tensors and a full ONNX model + genai_config are produced. Fixes #492.
1 parent 1a88a3c commit 70de6ad

4 files changed

Lines changed: 83 additions & 22 deletions

File tree

‎src/mobius/components/_attention.py‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -467,13 +467,23 @@ class Qwen35Attention(nn.Module):
467467
- Per-head Q/K RMSNorm with +1 offset (OffsetRMSNorm)
468468
- Partial RoPE (rotary_embedding_dim < head_dim)
469469
- Output gating: attn_output * sigmoid(gate)
470+
471+
Args:
472+
config: Architecture configuration.
473+
linear_class: Factory callable ``(in_features, out_features, bias=...)``
474+
for creating projection layers. Defaults to ``Linear``. Pass a
475+
quantized-linear factory (see ``make_quantized_linear_factory``)
476+
to emit ``MatMulNBits`` for q/k/v/o projections instead.
470477
"""
471478

472479
def __init__(
473480
self,
474481
config: ArchitectureConfig,
482+
linear_class: type | None = None,
475483
):
476484
super().__init__()
485+
if linear_class is None:
486+
linear_class = Linear
477487
self.hidden_size = config.hidden_size
478488
self.head_dim = config.head_dim
479489
self.num_attention_heads = config.num_attention_heads
@@ -486,22 +496,22 @@ def __init__(
486496
self._rope_interleave = config.rope_interleave
487497

488498
q_dim = self.num_attention_heads * self.head_dim
489-
self.q_proj = Linear(
499+
self.q_proj = linear_class(
490500
self.hidden_size,
491501
q_dim * 2,
492502
bias=config.attn_qkv_bias,
493503
)
494-
self.k_proj = Linear(
504+
self.k_proj = linear_class(
495505
self.hidden_size,
496506
self.num_key_value_heads * self.head_dim,
497507
bias=config.attn_qkv_bias,
498508
)
499-
self.v_proj = Linear(
509+
self.v_proj = linear_class(
500510
self.hidden_size,
501511
self.num_key_value_heads * self.head_dim,
502512
bias=config.attn_qkv_bias,
503513
)
504-
self.o_proj = Linear(
514+
self.o_proj = linear_class(
505515
q_dim,
506516
self.hidden_size,
507517
bias=config.attn_o_bias,

‎src/mobius/components/_gated_deltanet.py‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -102,10 +102,23 @@ class GatedDeltaNet(nn.Module):
102102
The forward pass is a clean sequence of op calls.
103103
104104
The recurrent state replaces the KV cache for these layers.
105+
106+
Args:
107+
config: Architecture configuration.
108+
linear_class: Factory callable ``(in_features, out_features, bias=...)``
109+
for creating the ``in_proj_qkv``/``in_proj_z``/``in_proj_b``/
110+
``in_proj_a``/``out_proj`` projections. Defaults to ``Linear``.
111+
Pass a quantized-linear factory (see
112+
``make_quantized_linear_factory``) to emit ``MatMulNBits`` for
113+
these projections instead. ``dt_bias``, ``A_log``, and
114+
``conv1d.weight`` are small recurrent-state parameters and are
115+
never quantized regardless of this argument.
105116
"""
106117

107-
def __init__(self, config: ArchitectureConfig):
118+
def __init__(self, config: ArchitectureConfig, linear_class: type | None = None):
108119
super().__init__()
120+
if linear_class is None:
121+
linear_class = Linear
109122
self.hidden_size = config.hidden_size
110123
self._dtype = config.dtype
111124
self.num_v_heads = config.linear_num_value_heads
@@ -118,17 +131,17 @@ def __init__(self, config: ArchitectureConfig):
118131
self.conv_dim = self.key_dim * 2 + self.value_dim
119132

120133
# QKV projection (fused: Q, K, V in one linear)
121-
self.in_proj_qkv = Linear(
134+
self.in_proj_qkv = linear_class(
122135
self.hidden_size,
123136
self.key_dim * 2 + self.value_dim,
124137
bias=False,
125138
)
126139
# Gating projection (z for silu gating in output norm)
127-
self.in_proj_z = Linear(self.hidden_size, self.value_dim, bias=False)
140+
self.in_proj_z = linear_class(self.hidden_size, self.value_dim, bias=False)
128141
# Beta projection (forget gate)
129-
self.in_proj_b = Linear(self.hidden_size, self.num_v_heads, bias=False)
142+
self.in_proj_b = linear_class(self.hidden_size, self.num_v_heads, bias=False)
130143
# Alpha projection (decay control)
131-
self.in_proj_a = Linear(self.hidden_size, self.num_v_heads, bias=False)
144+
self.in_proj_a = linear_class(self.hidden_size, self.num_v_heads, bias=False)
132145

133146
# Causal depthwise Conv1D
134147
self.conv1d = _DepthwiseConv1d(self.conv_dim, self.conv_kernel_size)
@@ -141,7 +154,7 @@ def __init__(self, config: ArchitectureConfig):
141154
self.norm = PostGatedRMSNorm(self.head_v_dim, eps=config.rms_norm_eps)
142155

143156
# Output projection
144-
self.out_proj = Linear(self.value_dim, self.hidden_size, bias=False)
157+
self.out_proj = linear_class(self.value_dim, self.hidden_size, bias=False)
145158

146159
def forward(
147160
self,

‎src/mobius/models/moe.py‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -278,16 +278,23 @@ class Qwen2MoELayer(MoELayer):
278278
Replicates HuggingFace ``Qwen2MoeSparseMoeBlock``.
279279
"""
280280

281-
def __init__(self, config: ArchitectureConfig, gate: nn.Module | None = None):
281+
def __init__(
282+
self,
283+
config: ArchitectureConfig,
284+
gate: nn.Module | None = None,
285+
linear_class: type | None = None,
286+
):
282287
super().__init__(config, gate=gate)
283288
assert config.shared_expert_intermediate_size is not None, (
284289
"Qwen2MoELayer requires config.shared_expert_intermediate_size"
285290
)
291+
if linear_class is None:
292+
linear_class = Linear
286293
shared_config = dataclasses.replace(
287294
config, intermediate_size=config.shared_expert_intermediate_size
288295
)
289-
self.shared_expert = MLP(shared_config)
290-
self.shared_expert_gate = Linear(config.hidden_size, 1, bias=False)
296+
self.shared_expert = MLP(shared_config, linear_class=linear_class)
297+
self.shared_expert_gate = linear_class(config.hidden_size, 1, bias=False)
291298

292299
def forward(self, op: OpBuilder, hidden_states: ir.Value):
293300
# Routing expert output: top-k weighted sum [B, S, H]

‎src/mobius/models/qwen35.py‎

Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@
33

44
from __future__ import annotations
55

6-
from typing import TYPE_CHECKING
7-
6+
import onnx_ir as ir
87
import torch
98
from onnxscript import OpBuilder, nn
109

@@ -19,6 +18,7 @@
1918
from mobius.components._gated_deltanet import GatedDeltaNet
2019
from mobius.components._mlp import MLP
2120
from mobius.components._moe import _supported_qmoe_quantization
21+
from mobius.components._quantized_linear import make_quantized_linear_factory
2222
from mobius.components._rms_norm import OffsetRMSNorm
2323
from mobius.components._rotary_embedding import initialize_rope
2424
from mobius.models.base import CausalLMModel
@@ -30,14 +30,31 @@
3030
split_deepstack_embeds,
3131
)
3232

33-
if TYPE_CHECKING:
34-
import onnx_ir as ir
35-
3633
# ---------------------------------------------------------------------------
3734
# Qwen3.5 — hybrid linear/full attention
3835
# ---------------------------------------------------------------------------
3936

4037

38+
def _linear_factory(config: ArchitectureConfig) -> type | None:
39+
"""Build a quantized-linear factory from ``config.quantization``, or None.
40+
41+
Returns ``None`` (meaning "use plain ``Linear``") when the model is
42+
unquantized. Shared by the dense (:class:`Qwen35DecoderLayer`) and MoE
43+
(:class:`Qwen35MoEDecoderLayer`) variants so ``self_attn``/``linear_attn``/
44+
``mlp``/``shared_expert`` are all quantized consistently.
45+
"""
46+
quantization = config.quantization
47+
if quantization is None or quantization.quant_method == "none":
48+
return None
49+
zero_point_dtype = config.dtype if quantization.float_zero_point else ir.DataType.UINT8
50+
return make_quantized_linear_factory(
51+
bits=quantization.bits,
52+
block_size=quantization.group_size,
53+
has_zero_point=not quantization.sym,
54+
zero_point_dtype=zero_point_dtype,
55+
)
56+
57+
4158
class Qwen35DecoderLayer(nn.Module):
4259
"""Qwen3.5 decoder layer with hybrid attention.
4360
@@ -47,6 +64,12 @@ class Qwen35DecoderLayer(nn.Module):
4764
4865
Both variants use :class:`OffsetRMSNorm` (the *1 + weight* variant)
4966
for pre-attention and post-attention normalization.
67+
68+
When ``config.quantization`` is set, ``self_attn``/``linear_attn``/``mlp``
69+
projections are built with a quantized-linear factory (see
70+
:func:`_linear_factory`) so quantized checkpoints (e.g. Olive
71+
RTN/GPTQ) load correctly instead of hitting a dense-vs-packed shape
72+
mismatch.
5073
"""
5174

5275
def __init__(self, config: ArchitectureConfig, layer_idx: int):
@@ -55,13 +78,14 @@ def __init__(self, config: ArchitectureConfig, layer_idx: int):
5578
self.layer_type: str = (
5679
layer_types[layer_idx] if layer_idx < len(layer_types) else "full_attention"
5780
)
81+
linear_class = _linear_factory(config)
5882

5983
if self.layer_type == "linear_attention":
60-
self.linear_attn = GatedDeltaNet(config)
84+
self.linear_attn = GatedDeltaNet(config, linear_class=linear_class)
6185
else:
62-
self.self_attn = Qwen35Attention(config)
86+
self.self_attn = Qwen35Attention(config, linear_class=linear_class)
6387

64-
self.mlp = MLP(config)
88+
self.mlp = MLP(config, linear_class=linear_class)
6589
self.input_layernorm = OffsetRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
6690
self.post_attention_layernorm = OffsetRMSNorm(
6791
config.hidden_size, eps=config.rms_norm_eps
@@ -247,11 +271,18 @@ class Qwen35MoEDecoderLayer(Qwen35DecoderLayer):
247271
Same hybrid DeltaNet/full-attention architecture as
248272
:class:`Qwen35DecoderLayer`, but replaces the dense MLP with a
249273
:class:`Qwen35MoEBlock`.
274+
275+
The routed experts are quantized via the fused ``com.microsoft::QMoE``
276+
path (see :class:`~mobius.components._moe.MoELayer`), driven directly
277+
by ``config.quantization``. The always-active ``shared_expert``/
278+
``shared_expert_gate`` are not part of that fused op, so they are
279+
quantized separately via the same ``linear_class`` factory used for
280+
``self_attn``/``linear_attn``/dense ``mlp`` (see :func:`_linear_factory`).
250281
"""
251282

252283
def __init__(self, config: ArchitectureConfig, layer_idx: int):
253284
super().__init__(config, layer_idx)
254-
self.mlp = Qwen35MoEBlock(config)
285+
self.mlp = Qwen35MoEBlock(config, linear_class=_linear_factory(config))
255286

256287

257288
class Qwen35MoETextModel(nn.Module):

0 commit comments

Comments
 (0)