Skip to content

Commit e8dc837

Browse files
justinchubyCopilot
andauthored
Quantized token embedding via GatherBlockQuantized (272MB→76MB) (#400)
The token-embedding table was emitted as fp16 `[151936,896]` ≈ 272 MB (a plain Gather) even in Q4 models — larger than WebGPU's 256 MiB buffer limit and a big bandwidth cost. This keeps it quantized: - Emits `com.microsoft.GatherBlockQuantized` with Q4 packed data `[151936,448]` + fp16 scales. - Size: **272.27 MB → 68.07 MB data + 8.51 MB scales**. - Tied LM head continues to share the table via MatMulNBits. - Verified: CPU EP coherent ('Paris'); WebGPU EP places GatherBlockQuantized on `WebGpuExecutionProvider` (on-device) with coherent output. Note: a runtime-side WebGPU stability issue (stale KV validation) is tracked separately in onnx-genai. lintrunner clean; gguf pytest 153 passed. Co-authored-by: Copilot <[email protected]>
1 parent 227be23 commit e8dc837

6 files changed

Lines changed: 200 additions & 34 deletions

File tree

‎src/mobius/__main__.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,10 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
351351
raise SystemExit(1)
352352

353353
if args.keep_quantized:
354-
print("Quantized mode: preserving GGUF quantization as MatMulNBits...")
354+
print(
355+
"Quantized mode: preserving GGUF quantization as "
356+
"MatMulNBits/GatherBlockQuantized..."
357+
)
355358

356359
gguf_path = args.gguf_path
357360
output_dir = args.output or os.path.splitext(gguf_path)[0] + "_onnx"
@@ -594,7 +597,10 @@ def main(argv: list[str] | None = None) -> None:
594597
gguf_parser.add_argument(
595598
"--keep-quantized",
596599
action="store_true",
597-
help="Preserve quantization via MatMulNBits (Q4_0/Q4_1/Q8_0).",
600+
help=(
601+
"Preserve supported projection and embedding quantization via "
602+
"MatMulNBits/GatherBlockQuantized."
603+
),
598604
)
599605
gguf_parser.add_argument(
600606
"--dtype",

‎src/mobius/_configs/_quantization.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,11 @@ class QuantizationConfig:
2727
# (e.g. Tencent SEQ uses 1.5).
2828
float_zero_point: bool = False
2929
# When True, the input embedding table is block-wise quantized and is
30-
# looked up with GatherBlockQuantized instead of a plain Gather. Set by
31-
# Olive RTN exports that pass ``embeds: true``.
30+
# looked up with GatherBlockQuantized instead of a plain Gather. Used by
31+
# Olive RTN exports and quantized GGUF imports.
3232
quantize_embeddings: bool = False
3333
# When True, the LM head projection is block-wise quantized (MatMulNBits).
34-
# Set by Olive RTN exports that pass ``lm_head: true``.
34+
# Used by Olive RTN exports and tied quantized GGUF imports.
3535
quantize_lm_head: bool = False
3636
# When True, the input embedding and LM head share one weight table. Olive
3737
# RTN records this in its own config (``tie_word_embeddings``) and may clear

‎src/mobius/integrations/gguf/_builder.py‎

Lines changed: 74 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@
99
- **Dequantized** (default): All quantized tensors are dequantized to
1010
float. Simple, but loses the compression benefit of quantization.
1111
- **Quantized** (``keep_quantized=True``): Linear-layer weights that
12-
use supported GGUF types (Q4_0, Q4_1, Q8_0) are repacked into
13-
MatMulNBits format. Other tensors (norms, embeddings) are
14-
dequantized as usual.
12+
use supported GGUF types are repacked into MatMulNBits format.
13+
Quantized token embeddings are repacked for GatherBlockQuantized.
14+
Other tensors (norms and unsupported quant types) are dequantized.
1515
"""
1616

1717
from __future__ import annotations
@@ -169,6 +169,12 @@ def build_from_gguf(
169169
bits, block_size, is_sym = _detect_quant_params(gguf_model, gguf_arch)
170170
# Float zero-point only when actually using Tencent's native 2-bit form.
171171
float_zp = is_tencent_q1_0_layout(gguf_model) and flags.tencent_q1_0_use_native_2bit
172+
quantize_embeddings = _can_quantize_embedding(
173+
gguf_model,
174+
gguf_arch,
175+
bits=bits,
176+
block_size=block_size,
177+
)
172178
config = dataclasses.replace(
173179
config,
174180
quantization=QuantizationConfig(
@@ -177,14 +183,18 @@ def build_from_gguf(
177183
quant_method="gguf",
178184
sym=is_sym,
179185
float_zero_point=float_zp,
186+
quantize_embeddings=quantize_embeddings,
187+
quantize_lm_head=quantize_embeddings and config.tie_word_embeddings,
188+
tie_word_embeddings=quantize_embeddings and config.tie_word_embeddings,
180189
),
181190
)
182191
logger.info(
183-
"Quantized mode: bits=%d, block_size=%d, symmetric=%s, float_zp=%s",
192+
"Quantized mode: bits=%d, block_size=%d, symmetric=%s, float_zp=%s, embedding=%s",
184193
bits,
185194
block_size,
186195
is_sym,
187196
float_zp,
197+
quantize_embeddings,
188198
)
189199

190200
# 4. Look up module class and resolve task
@@ -331,26 +341,26 @@ def _detect_quant_params(gguf_model, gguf_arch: str) -> tuple[int, int, bool]:
331341
"""
332342
from gguf import GGMLQuantizationType
333343

334-
from mobius.integrations.gguf._repacker import can_repack
344+
from mobius.integrations.gguf._repacker import can_repack, repack_quant_params
335345
from mobius.integrations.gguf._tencent_q1_0 import is_tencent_q1_0_layout
336346
from mobius.integrations.gguf._tensor_mapping import (
337347
map_gguf_to_hf_names,
338348
)
339349

340-
# Per-type parameters: (bits, block_size, is_symmetric).
350+
# Symmetry of each supported GGUF quantization type.
341351
#
342352
# Mainline Q1_0 (1-bit binary) is repacked into 2-bit MatMulNBits
343353
# with zp=1 — see _repack_q1_0. Tencent's custom Q1_0 (2-bit SEQ,
344354
# 512-elt blocks) is inflated to 4-bit MatMulNBits with zp=3 — see
345355
# parse_tencent_q1_0_tensor — because the ORT CPU unpacked-float-zp
346356
# path is currently only implemented for bits=4, and the half-integer
347357
# SEQ offset 1.5 cannot be expressed with integer zp at bits=2.
348-
type_params: dict = {
349-
GGMLQuantizationType.Q4_0: (4, 32, True),
350-
GGMLQuantizationType.Q4_1: (4, 32, False),
351-
GGMLQuantizationType.Q4_K: (4, 32, False),
352-
GGMLQuantizationType.Q8_0: (8, 32, True),
353-
GGMLQuantizationType.Q1_0: (2, 128, False),
358+
type_symmetry: dict = {
359+
GGMLQuantizationType.Q4_0: True,
360+
GGMLQuantizationType.Q4_1: False,
361+
GGMLQuantizationType.Q4_K: False,
362+
GGMLQuantizationType.Q8_0: True,
363+
GGMLQuantizationType.Q1_0: False,
354364
}
355365

356366
counts: Counter = Counter()
@@ -368,7 +378,10 @@ def _detect_quant_params(gguf_model, gguf_arch: str) -> tuple[int, int, bool]:
368378
)
369379

370380
dominant = counts.most_common(1)[0][0]
371-
bits, block_size, is_sym = type_params[dominant]
381+
params = repack_quant_params(dominant.value)
382+
assert params is not None
383+
bits, block_size = params
384+
is_sym = type_symmetry[dominant]
372385

373386
# Tencent Q1_0 files reuse the Q1_0 type id but ship a different
374387
# on-disk layout (2-bit SEQ, 512-element blocks, fp16 scale per block).
@@ -395,6 +408,40 @@ def _detect_quant_params(gguf_model, gguf_arch: str) -> tuple[int, int, bool]:
395408
return bits, block_size, is_sym
396409

397410

411+
def _can_quantize_embedding(
412+
gguf_model,
413+
gguf_arch: str,
414+
*,
415+
bits: int,
416+
block_size: int,
417+
) -> bool:
418+
"""Return whether the token embedding can use GatherBlockQuantized.
419+
420+
The graph has one quantization configuration shared by its quantized
421+
modules. Preserve the GGUF embedding only when its repacked representation
422+
uses the same bit width and block size as the projection weights.
423+
"""
424+
from mobius.integrations.gguf._repacker import repack_quant_params
425+
from mobius.integrations.gguf._tencent_q1_0 import is_tencent_q1_0_layout
426+
from mobius.integrations.gguf._tensor_mapping import map_gguf_to_hf_names
427+
428+
# Tencent files reuse the Q1_0 type id for a custom layout that gguf-py
429+
# cannot size correctly. Embeddings from those files must stay dequantized.
430+
if is_tencent_q1_0_layout(gguf_model):
431+
return False
432+
433+
for tensor in gguf_model._reader.tensors:
434+
if map_gguf_to_hf_names(tensor.name, gguf_arch) != "model.embed_tokens.weight":
435+
continue
436+
shape = tuple(reversed(tensor.shape))
437+
if len(shape) != 2:
438+
return False
439+
qtype = tensor.tensor_type
440+
qtype_val = qtype.value if hasattr(qtype, "value") else qtype
441+
return repack_quant_params(qtype_val) == (bits, block_size)
442+
return False
443+
444+
398445
def _load_dequantized_state_dict(
399446
gguf_model,
400447
gguf_arch: str,
@@ -434,8 +481,9 @@ def _load_quantized_state_dict(
434481
"""Load tensors, repacking supported quantized types.
435482
436483
Projection weights (Q/K/V/O and MLP) that use repackable GGUF
437-
types are converted to MatMulNBits format. All other tensors
438-
(norms, embeddings, unsupported quant types) are dequantized.
484+
types are converted to MatMulNBits format. Quantized embeddings
485+
are converted to GatherBlockQuantized format. All other tensors
486+
(norms and unsupported quant types) are dequantized.
439487
440488
For llama-family models, quantized Q/K weights receive the
441489
row-level reverse-permutation that ``process_tensors`` would
@@ -445,7 +493,7 @@ def _load_quantized_state_dict(
445493
import torch
446494
from gguf import GGMLQuantizationType, dequantize
447495

448-
from mobius.components import QuantizedLinear
496+
from mobius.components import QuantizedEmbedding, QuantizedLinear
449497
from mobius.integrations.gguf._repacker import (
450498
can_repack,
451499
repack_gguf_tensor,
@@ -464,9 +512,12 @@ def _load_quantized_state_dict(
464512
# Collect module paths that use QuantizedLinear so we know
465513
# which .weight parameters should receive repacked data.
466514
quantized_stems = set()
515+
quantized_embedding_stems = set()
467516
for mod_name, mod in module.named_modules():
468517
if isinstance(mod, QuantizedLinear):
469518
quantized_stems.add(mod_name)
519+
elif isinstance(mod, QuantizedEmbedding):
520+
quantized_embedding_stems.add(mod_name)
470521

471522
num_heads = getattr(config, "num_attention_heads", None)
472523
num_kv_heads = getattr(config, "num_key_value_heads", None)
@@ -505,9 +556,10 @@ def _load_quantized_state_dict(
505556
# parameter is from a QuantizedLinear module.
506557
stem = hf_name[: -len(".weight")] if hf_name.endswith(".weight") else None
507558
is_tencent_q1_0_tensor = tencent_q1_0 and qtype == GGMLQuantizationType.Q1_0
559+
is_quantized_embedding = stem in quantized_embedding_stems
508560
should_repack = (
509561
stem is not None
510-
and stem in quantized_stems
562+
and (stem in quantized_stems or is_quantized_embedding)
511563
and (can_repack(qtype_val) or is_tencent_q1_0_tensor)
512564
)
513565

@@ -541,7 +593,10 @@ def _load_quantized_state_dict(
541593
w = _reverse_permute(w, n_head)
542594
s = _reverse_permute(s, n_head)
543595

544-
state_dict[hf_name] = w
596+
if is_quantized_embedding:
597+
state_dict[f"{stem}.qweight"] = w.reshape(w.shape[0], -1)
598+
else:
599+
state_dict[hf_name] = w
545600
state_dict[f"{stem}.scales"] = s
546601
if repacked.zero_points is not None:
547602
zp = torch.from_numpy(repacked.zero_points)
@@ -564,7 +619,7 @@ def _load_quantized_state_dict(
564619
state_dict[hf_name] = torch.from_numpy(arr)
565620

566621
logger.info(
567-
"Loaded %d tensors (%d repacked as MatMulNBits, %d dequantized)",
622+
"Loaded %d tensors (%d repacked for quantized ops, %d dequantized)",
568623
len(state_dict),
569624
n_repacked,
570625
len(state_dict) - n_repacked,

‎src/mobius/integrations/gguf/_builder_test.py‎

Lines changed: 92 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,14 @@ def _write_quantized_gguf(
2020
num_kv_heads: int = 2,
2121
intermediate_size: int = 128,
2222
vocab_size: int = 256,
23+
quantize_embedding: bool = False,
24+
tie_embeddings: bool = False,
2325
) -> None:
2426
"""Write a GGUF file with Q4_0 quantized projection weights.
2527
26-
Norms and embeddings are float32; all linear-layer weights in
27-
decoder blocks are Q4_0 (4-bit symmetric, block_size=32).
28+
Norms are float32; all linear-layer weights in decoder blocks are
29+
Q4_0 (4-bit symmetric, block_size=32). The embedding can optionally
30+
be Q4_0 and tied to the LM head.
2831
"""
2932
from gguf import GGMLQuantizationType, GGUFWriter
3033

@@ -63,8 +66,10 @@ def _add_q4_0(name: str, n_out: int, k_in: int) -> None:
6366
)
6467
writer.add_tensor(name, raw, raw_dtype=GGMLQuantizationType.Q4_0)
6568

66-
# Embeddings (float32)
67-
_add_f32("token_embd.weight", (vocab_size, hidden_size))
69+
if quantize_embedding:
70+
_add_q4_0("token_embd.weight", vocab_size, hidden_size)
71+
else:
72+
_add_f32("token_embd.weight", (vocab_size, hidden_size))
6873

6974
for i in range(num_layers):
7075
# Projection weights (Q4_0)
@@ -95,9 +100,10 @@ def _add_q4_0(name: str, n_out: int, k_in: int) -> None:
95100
_add_f32(f"blk.{i}.attn_norm.weight", (hidden_size,))
96101
_add_f32(f"blk.{i}.ffn_norm.weight", (hidden_size,))
97102

98-
# Output norm + lm_head (float32)
103+
# Output norm + optional untied lm_head (float32)
99104
_add_f32("output_norm.weight", (hidden_size,))
100-
_add_f32("output.weight", (vocab_size, hidden_size))
105+
if not tie_embeddings:
106+
_add_f32("output.weight", (vocab_size, hidden_size))
101107

102108
writer.write_header_to_file()
103109
writer.write_kv_data_to_file()
@@ -113,6 +119,22 @@ def q4_0_gguf(tmp_path: Path) -> Path:
113119
return path
114120

115121

122+
@pytest.fixture
123+
def q4_0_embedding_gguf(tmp_path: Path) -> Path:
124+
"""Create a GGUF with a Q4_0 token embedding."""
125+
path = tmp_path / "test_q4_0_embedding.gguf"
126+
_write_quantized_gguf(path, quantize_embedding=True)
127+
return path
128+
129+
130+
@pytest.fixture
131+
def q4_0_tied_embedding_gguf(tmp_path: Path) -> Path:
132+
"""Create a GGUF with one Q4_0 table shared by embedding and LM head."""
133+
path = tmp_path / "test_q4_0_tied_embedding.gguf"
134+
_write_quantized_gguf(path, quantize_embedding=True, tie_embeddings=True)
135+
return path
136+
137+
116138
class TestBuildQuantizedGguf:
117139
"""Tests for build_from_gguf(keep_quantized=True)."""
118140

@@ -136,6 +158,39 @@ def test_model_has_matmulnbits_ops(self, q4_0_gguf: Path):
136158
f"Expected MatMulNBits in ops, got: {sorted(op_types)}"
137159
)
138160

161+
def test_quantized_embedding_uses_gatherblockquantized(self, q4_0_embedding_gguf: Path):
162+
"""A quantized GGUF embedding remains packed in the ONNX graph."""
163+
import onnx_ir as ir
164+
165+
from mobius.integrations.gguf import build_from_gguf
166+
167+
model = build_from_gguf(q4_0_embedding_gguf, keep_quantized=True)["model"]
168+
gather_nodes = [node for node in model.graph if node.op_type == "GatherBlockQuantized"]
169+
assert len(gather_nodes) == 1
170+
assert gather_nodes[0].domain == "com.microsoft"
171+
172+
qweight = model.graph.initializers["model.embed_tokens.qweight"]
173+
assert qweight.dtype == ir.DataType.UINT8
174+
assert list(qweight.shape) == [256, 32]
175+
assert list(model.graph.initializers["model.embed_tokens.scales"].shape) == [
176+
256,
177+
2,
178+
]
179+
assert "model.embed_tokens.weight" not in model.graph.initializers
180+
181+
def test_tied_quantized_embedding_drives_matmulnbits_head(
182+
self, q4_0_tied_embedding_gguf: Path
183+
):
184+
"""Tied embedding/head share one packed table across both contrib ops."""
185+
from mobius.integrations.gguf import build_from_gguf
186+
187+
model = build_from_gguf(q4_0_tied_embedding_gguf, keep_quantized=True)["model"]
188+
op_types = [node.op_type for node in model.graph]
189+
assert op_types.count("GatherBlockQuantized") == 1
190+
assert "MatMulNBits" in op_types
191+
assert "model.embed_tokens.qweight" in model.graph.initializers
192+
assert not any(name.startswith("lm_head.") for name in model.graph.initializers)
193+
139194
def test_norms_are_float(self, q4_0_gguf: Path):
140195
"""Norm weights remain float, not quantized."""
141196
import onnx_ir as ir
@@ -175,6 +230,37 @@ def test_detect_quant_params(self, q4_0_gguf: Path):
175230
assert block_size == 32
176231
assert is_sym is True
177232

233+
def test_embedding_quantization_check_is_metadata_only(self, monkeypatch):
234+
"""Embedding compatibility does not read or repack tensor data."""
235+
from types import SimpleNamespace
236+
237+
from gguf import GGMLQuantizationType
238+
239+
from mobius.integrations.gguf import _tencent_q1_0
240+
from mobius.integrations.gguf._builder import _can_quantize_embedding
241+
242+
monkeypatch.setattr(_tencent_q1_0, "is_tencent_q1_0_layout", lambda _model: False)
243+
tensor = SimpleNamespace(
244+
name="token_embd.weight",
245+
tensor_type=GGMLQuantizationType.Q4_0,
246+
shape=(64, 256),
247+
)
248+
model = SimpleNamespace(_reader=SimpleNamespace(tensors=[tensor]))
249+
250+
assert _can_quantize_embedding(model, "llama", bits=4, block_size=32)
251+
252+
def test_tencent_q1_0_embedding_is_not_quantized(self, monkeypatch):
253+
"""Tencent Q1_0 detection short-circuits before inspecting tensors."""
254+
from types import SimpleNamespace
255+
256+
from mobius.integrations.gguf import _tencent_q1_0
257+
from mobius.integrations.gguf._builder import _can_quantize_embedding
258+
259+
monkeypatch.setattr(_tencent_q1_0, "is_tencent_q1_0_layout", lambda _model: True)
260+
model = SimpleNamespace()
261+
262+
assert not _can_quantize_embedding(model, "llama", bits=4, block_size=128)
263+
178264

179265
class TestRawTensorIterator:
180266
"""Tests for GGUFModel.tensor_items_raw()."""

0 commit comments

Comments
 (0)