Skip to content

Commit 5b0467f

Browse files
justinchubyCopilot
andcommitted
Add Q4_K_M GGUF conversion support
Co-authored-by: Copilot <[email protected]>
1 parent e8dc837 commit 5b0467f

5 files changed

Lines changed: 323 additions & 170 deletions

File tree

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

Lines changed: 76 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@
88
99
- **Dequantized** (default): All quantized tensors are dequantized to
1010
float. Simple, but loses the compression benefit of quantization.
11-
- **Quantized** (``keep_quantized=True``): Linear-layer weights that
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.
11+
- **Quantized** (``keep_quantized=True``): Linear-layer weights are
12+
normalized to a common MatMulNBits layout, including mixed presets
13+
such as Q4_K_M. Compatible quantized token embeddings are repacked
14+
for GatherBlockQuantized. Other tensors are dequantized.
1515
"""
1616

1717
from __future__ import annotations
@@ -108,9 +108,9 @@ def build_from_gguf(
108108
model type.
109109
dtype: Override model dtype (e.g. ``"f16"``). When ``None``,
110110
defaults to float32.
111-
keep_quantized: When ``True``, preserve quantization for
112-
supported GGUF types (Q4_0, Q4_1, Q8_0) by repacking
113-
linear-layer weights into MatMulNBits format.
111+
keep_quantized: When ``True``, preserve quantized linear-layer
112+
weights in MatMulNBits format. Mixed Q4_K_M source types are
113+
normalized to 4-bit, block-32 weights.
114114
execution_provider: Target execution provider for EP-aware
115115
optimisations (e.g. ``"cpu"`` to apply the
116116
GroupQueryAttention rewrite). Defaults to ``"default"``
@@ -328,16 +328,16 @@ def _normalize_gguf_weights(
328328

329329

330330
def _detect_quant_params(gguf_model, gguf_arch: str) -> tuple[int, int, bool]:
331-
"""Detect bits, block size, and symmetry from dominant GGUF quant type.
331+
"""Detect the common MatMulNBits target for GGUF projection weights.
332332
333-
Scans block-level (projection) tensors and returns the bit-width,
334-
block size, and symmetry flag of the most common repackable type.
333+
Q4_K-containing mixed presets target 4-bit, block-32 asymmetric
334+
MatMulNBits. Other files use the most common directly repackable type.
335335
336336
Returns:
337337
``(bits, block_size, is_symmetric)`` tuple.
338338
339339
Raises:
340-
ValueError: If no repackable quantized tensors are found.
340+
ValueError: If no mapped or repackable weight tensors are found.
341341
"""
342342
from gguf import GGMLQuantizationType
343343

@@ -366,19 +366,39 @@ def _detect_quant_params(gguf_model, gguf_arch: str) -> tuple[int, int, bool]:
366366
counts: Counter = Counter()
367367
for name, _raw, qtype, _shape in gguf_model.tensor_items_raw():
368368
hf_name = map_gguf_to_hf_names(name, gguf_arch)
369-
if hf_name is None:
369+
if hf_name is None or not hf_name.endswith(".weight"):
370370
continue
371-
if can_repack(qtype.value if hasattr(qtype, "value") else qtype):
372-
counts[qtype] += 1
371+
counts[qtype] += 1
373372

374373
if not counts:
375374
raise ValueError(
376-
"No repackable quantized tensors found in GGUF file. "
375+
"No mapped weight tensors found in GGUF file. "
377376
"Use keep_quantized=False for dequantized import."
378377
)
379378

380-
dominant = counts.most_common(1)[0][0]
381-
params = repack_quant_params(dominant.value)
379+
# Q4_K_M is deliberately a mixed preset. Depending on tensor dimensions
380+
# and importance it may contain mostly Q5_0 plus Q4_K, Q6_K, and Q8_0.
381+
# The presence of Q4_K identifies the desired 4-bit MatMulNBits target;
382+
# choosing only among already-repackable types would incorrectly select
383+
# Q8_0 for the official Qwen2.5-0.5B Q4_K_M file.
384+
if GGMLQuantizationType.Q4_K in counts:
385+
dominant = GGMLQuantizationType.Q4_K
386+
else:
387+
repackable_counts = Counter(
388+
{
389+
qtype: count
390+
for qtype, count in counts.items()
391+
if can_repack(qtype.value if hasattr(qtype, "value") else qtype)
392+
}
393+
)
394+
if not repackable_counts:
395+
raise ValueError(
396+
"No repackable quantized tensors found in GGUF file. "
397+
"Use keep_quantized=False for dequantized import."
398+
)
399+
dominant = repackable_counts.most_common(1)[0][0]
400+
dominant_value = dominant.value if hasattr(dominant, "value") else dominant
401+
params = repack_quant_params(dominant_value)
382402
assert params is not None
383403
bits, block_size = params
384404
is_sym = type_symmetry[dominant]
@@ -478,12 +498,13 @@ def _load_quantized_state_dict(
478498
module,
479499
config,
480500
) -> dict:
481-
"""Load tensors, repacking supported quantized types.
501+
"""Load tensors, normalizing quantized projections to MatMulNBits.
482502
483-
Projection weights (Q/K/V/O and MLP) that use repackable GGUF
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.
503+
Projection weights (Q/K/V/O and MLP) are converted to the graph's
504+
common MatMulNBits format. Mixed source types are dequantized and
505+
requantized when they do not already match that target. Compatible
506+
quantized embeddings are converted for GatherBlockQuantized. Norms
507+
and other non-linear tensors remain dequantized.
487508
488509
For llama-family models, quantized Q/K weights receive the
489510
row-level reverse-permutation that ``process_tensors`` would
@@ -496,6 +517,7 @@ def _load_quantized_state_dict(
496517
from mobius.components import QuantizedEmbedding, QuantizedLinear
497518
from mobius.integrations.gguf._repacker import (
498519
can_repack,
520+
repack_dequantized_tensor,
499521
repack_gguf_tensor,
500522
)
501523
from mobius.integrations.gguf._tencent_q1_0 import (
@@ -538,6 +560,10 @@ def _load_quantized_state_dict(
538560

539561
state_dict: dict[str, torch.Tensor] = {}
540562
n_repacked = 0
563+
n_requantized = 0
564+
target_bits = config.quantization.bits
565+
target_block_size = config.quantization.group_size
566+
target_symmetric = config.quantization.sym
541567

542568
for gguf_name, raw, qtype, np_shape in tqdm.tqdm(
543569
gguf_model.tensor_items_raw(),
@@ -552,15 +578,14 @@ def _load_quantized_state_dict(
552578
# Determine the int value of the quant type for can_repack
553579
qtype_val = qtype.value if hasattr(qtype, "value") else qtype
554580

555-
# Repack if the tensor is repackable AND its target ONNX
556-
# parameter is from a QuantizedLinear module.
581+
# Repack every target QuantizedLinear weight. Mixed GGUF presets
582+
# otherwise leave unsupported source types as full float matrices,
583+
# which cannot fit the graph's packed MatMulNBits initializer shape.
557584
stem = hf_name[: -len(".weight")] if hf_name.endswith(".weight") else None
558585
is_tencent_q1_0_tensor = tencent_q1_0 and qtype == GGMLQuantizationType.Q1_0
559-
is_quantized_embedding = stem in quantized_embedding_stems
560-
should_repack = (
561-
stem is not None
562-
and (stem in quantized_stems or is_quantized_embedding)
563-
and (can_repack(qtype_val) or is_tencent_q1_0_tensor)
586+
is_quantized_embedding = stem is not None and stem in quantized_embedding_stems
587+
should_repack = stem is not None and (
588+
stem in quantized_stems or is_quantized_embedding
564589
)
565590

566591
if should_repack:
@@ -570,13 +595,31 @@ def _load_quantized_state_dict(
570595
data_section_offset,
571596
tensors_by_name[gguf_name],
572597
)
573-
else:
598+
elif can_repack(qtype_val):
574599
shape_2d = (int(np_shape[0]), int(np_shape[1]))
575600
repacked = repack_gguf_tensor(
576601
raw.ravel().view(np.uint8),
577602
qtype_val,
578603
shape_2d,
579604
)
605+
if repacked.bits != target_bits or repacked.block_size != target_block_size:
606+
values = gguf_model.dequantize_raw_tensor(raw, qtype, np_shape)
607+
repacked = repack_dequantized_tensor(
608+
values,
609+
bits=target_bits,
610+
block_size=target_block_size,
611+
symmetric=target_symmetric,
612+
)
613+
n_requantized += 1
614+
else:
615+
values = gguf_model.dequantize_raw_tensor(raw, qtype, np_shape)
616+
repacked = repack_dequantized_tensor(
617+
values,
618+
bits=target_bits,
619+
block_size=target_block_size,
620+
symmetric=target_symmetric,
621+
)
622+
n_requantized += 1
580623
w = torch.from_numpy(repacked.weight)
581624
s = torch.from_numpy(repacked.scales)
582625

@@ -619,10 +662,11 @@ def _load_quantized_state_dict(
619662
state_dict[hf_name] = torch.from_numpy(arr)
620663

621664
logger.info(
622-
"Loaded %d tensors (%d repacked for quantized ops, %d dequantized)",
665+
"Loaded %d state_dict entries (%d GGUF tensors repacked for quantized ops, "
666+
"%d requantized from mixed source types)",
623667
len(state_dict),
624668
n_repacked,
625-
len(state_dict) - n_repacked,
669+
n_requantized,
626670
)
627671
return state_dict
628672

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

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,31 @@ def test_tencent_q1_0_embedding_is_not_quantized(self, monkeypatch):
261261

262262
assert not _can_quantize_embedding(model, "llama", bits=4, block_size=128)
263263

264+
def test_detect_q4_k_m_mixed_profile(self):
265+
"""Q4_K presence selects a 4-bit target despite more Q5_0 tensors."""
266+
from gguf import GGMLQuantizationType
267+
268+
from mobius.integrations.gguf._builder import _detect_quant_params
269+
270+
class _MixedModel:
271+
def tensor_items_raw(self):
272+
for i in range(5):
273+
yield (
274+
f"blk.{i}.attn_q.weight",
275+
np.empty(0, dtype=np.uint8),
276+
GGMLQuantizationType.Q5_0,
277+
(64, 64),
278+
)
279+
yield (
280+
"blk.0.ffn_down.weight",
281+
np.empty(0, dtype=np.uint8),
282+
GGMLQuantizationType.Q4_K,
283+
(64, 128),
284+
)
285+
286+
bits, block_size, is_sym = _detect_quant_params(_MixedModel(), "llama")
287+
assert (bits, block_size, is_sym) == (4, 32, False)
288+
264289

265290
class TestRawTensorIterator:
266291
"""Tests for GGUFModel.tensor_items_raw()."""
@@ -298,3 +323,14 @@ def test_float_tensors_have_correct_type(self, q4_0_gguf: Path):
298323
assert len(f32_items) > 0
299324
for _name, _raw, qtype, _shape in f32_items:
300325
assert qtype == GGMLQuantizationType.F32
326+
327+
def test_dequantize_raw_tensor_matches_get_tensor(self, q4_0_gguf: Path):
328+
from mobius.integrations.gguf._reader import GGUFModel
329+
330+
model = GGUFModel(q4_0_gguf)
331+
name, raw, qtype, shape = next(
332+
item for item in model.tensor_items_raw() if len(item[3]) == 2
333+
)
334+
expected = model.get_tensor(name)
335+
actual = model.dequantize_raw_tensor(raw, qtype, shape)
336+
np.testing.assert_array_equal(actual, expected)

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

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -226,21 +226,32 @@ def _dequantize_tensor(self, tensor) -> np.ndarray:
226226
Returns:
227227
Numpy array in row-major shape order.
228228
"""
229-
from gguf import GGMLQuantizationType, dequantize
230-
231-
data = tensor.data
232-
qtype = tensor.tensor_type
233229
# GGUF stores shape in GGML (column-major) order; reverse
234230
# to get numpy (row-major) shape.
235231
np_shape = tuple(reversed(tensor.shape))
232+
return self.dequantize_raw_tensor(tensor.data, tensor.tensor_type, np_shape)
233+
234+
def dequantize_raw_tensor(
235+
self,
236+
raw_data: np.ndarray,
237+
quant_type: Any,
238+
np_shape: tuple[int, ...],
239+
) -> np.ndarray:
240+
"""Dequantize raw GGUF tensor data into its logical numpy shape.
241+
242+
K-quant blocks are contiguous over the flattened tensor and may cross
243+
logical row boundaries. Delegating the complete raw array to gguf's
244+
reference dequantizer before reshaping preserves that layout.
245+
"""
246+
from gguf import GGMLQuantizationType, dequantize
236247

237-
if qtype in (GGMLQuantizationType.F32, GGMLQuantizationType.F16):
238-
return data.reshape(np_shape)
248+
if quant_type in (GGMLQuantizationType.F32, GGMLQuantizationType.F16):
249+
return raw_data.reshape(np_shape)
239250
# All other types (quantized, BF16) go through dequantize().
240251
# BF16 is intentionally NOT in the fast path above because
241252
# numpy has no native bfloat16 dtype — the gguf library's
242253
# dequantize() converts BF16 bytes to float32.
243-
return dequantize(data, qtype).reshape(np_shape)
254+
return dequantize(raw_data, quant_type).reshape(np_shape)
244255

245256
def tensor_items(self) -> Iterator[tuple[str, np.ndarray]]:
246257
"""Iterate over ``(name, dequantized_array)`` pairs.
@@ -268,7 +279,9 @@ def tensor_items_raw(
268279
Tuples of ``(name, raw_data, quant_type, np_shape)`` where:
269280
270281
- *name*: GGUF tensor name
271-
- *raw_data*: Raw bytes as uint8 numpy array (flat)
282+
- *raw_data*: Raw tensor storage. Quantized K-blocks are
283+
contiguous over the flattened logical tensor and are not
284+
independently padded at row boundaries.
272285
- *quant_type*: :class:`gguf.GGMLQuantizationType` value
273286
- *np_shape*: Logical shape in numpy (row-major) order
274287
"""

0 commit comments

Comments
 (0)