Skip to content

Commit eec8e3f

Browse files
justinchubyCopilotCopilot
authored
feat(gguf): support Q6_K, fix byte-level tokenizers, emit loadable packages (#543)
Three defects blocked running a Q4_K_M GGUF (`tencent/Hy-MT2-1.8B`) end to end. ## 1. Q6_K was unsupported Q4_K_M is a **mixed** preset. This file is 192 × Q4_K, 33 × Q6_K, 129 × F32, and the Q6_K third is not a rounding error — it holds **34% of the bytes**, including the 193 MB `token_embd.weight` that this model also uses as its `lm_head` (there is no `output.weight`). `repack_dequantized_tensor` already named Q6_K as an expected input for exactly this reason, but no unpacker existed, so the build failed outright. Adds `_repack_q6_k`, following ggml's `dequantize_row_q6_K` interleave: each 128-element half consumes 64 `ql` bytes, 32 `qh` bytes and 8 scales, emitting four 32-element groups with `is = l // 16`. **Verified bit-for-bit** against `gguf`'s own dequantizer on six real tensors, ~1M elements each — zero differing elements. This matters because every plausible-but-wrong permutation of that interleave still yields finite values of the right magnitude; only exact comparison distinguishes correct from subtly transposed. ## 2. Byte-level tokenizers were decoded as SentencePiece The reconstructor applied Metaspace (`▁`) unconditionally. This model declares `tokenizer.ggml.model = gpt2`, whose vocabulary spells a leading space as `Ġ` — a different alphabet. Every inter-word space was dropped: ``` "Hello, world!" -> "Hello,!world!" ``` The code detected the bad round-trip, **warned, and emitted the broken tokenizer anyway**. Now it dispatches on the declared family. Fixing the alphabet alone was not enough. `tokenizer.ggml.pre` names the *split* rule, which the byte-level model does not imply — llama.cpp keeps per-family regexes because families disagree on how digits, CJK and punctuation group. A mismatch **still round-trips**, so it is invisible to a round-trip check and only shows at the id level: a tab sample decomposed as `[184, 25056]` where the reference gives `[20061, 421]`. Adds the family split table. All six samples — ASCII, CJK, emoji, repeated spaces, tabs/newlines — now match the HF tokenizer **id-for-id** as well as round-tripping exactly. ## 3. The Python API could not produce a loadable package `mobius build-gguf --runtime onnx-genai` emitted tokenizer + inference metadata, but `build_from_gguf` callers got a bare graph that loads nowhere — the model directory was missing both artifacts. Rather than document a second call sequence for API users, `write_gguf_runtime_package` now owns the full artifact set, and the CLI routes through it. One function knows what a complete package is, so the two paths cannot drift. ## Incidental Q6_K was missing from `type_can_omit_zero_points`, which raised `KeyError` — caught by the existing suite. That test asserted Q6_K was *unsupported*, which is no longer true, so it is retargeted to Q5_K (still unsupported), preserving the "no silent float fallback" guarantee it was written to protect. A new test covers Q6_K selecting the asymmetric 4-bit target. ## Validation `python -m pytest src/mobius/integrations/gguf/ -q` — **330 passed, 0 failed**. End-to-end, the Python API now emits a complete package with no tokenizer warning: ``` tokenizer: ...\tokenizer.json inference_metadata: ...\inference_metadata.yaml model.onnx.data 989.74 MB ``` --------- Co-authored-by: Copilot <[email protected]> Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: justinchuby <[email protected]> Copilot-Session: d60eb808-7cc6-4abc-b48d-2a6dd3841624
1 parent 9603636 commit eec8e3f

10 files changed

Lines changed: 613 additions & 48 deletions

File tree

‎src/mobius/__main__.py‎

Lines changed: 9 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -531,15 +531,6 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
531531
)
532532
raise SystemExit(1)
533533

534-
if getattr(args, "runtime", None) == "ort-genai":
535-
raise SystemExit(
536-
"Error: mobius build-gguf does not yet support --runtime ort-genai. "
537-
"The command cannot emit a valid genai_config.json until the selected "
538-
"GGUF architecture's cache and tokenizer contracts have passed real "
539-
"ORT GenAI generation. Use --runtime onnx-genai where supported, or "
540-
"omit --runtime and run the ONNX model directly."
541-
)
542-
543534
mmproj_path = getattr(args, "mmproj", None)
544535
keep_quantized = not args.dequantize
545536

@@ -584,18 +575,15 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
584575
path = os.path.join(output_dir, "model.onnx")
585576
print(f"Saved {name} to {path}")
586577

587-
if getattr(args, "runtime", None) == "onnx-genai":
588-
from mobius.integrations.gguf import write_gguf_tokenizer_json
589-
from mobius.integrations.onnx_genai import write_onnx_genai_config
590-
591-
# A GGUF checkpoint has no Hugging Face source directory, so the
592-
# tokenizer is reconstructed from the file's embedded ggml metadata
593-
# rather than copied from a `source`.
594-
tokenizer_path = write_gguf_tokenizer_json(gguf_path, output_dir)
595-
if tokenizer_path is not None:
596-
print(f" tokenizer: {tokenizer_path}")
597-
artifacts = write_onnx_genai_config(
598-
pkg, output_dir, config=getattr(pkg, "config", None), source=None
578+
runtime = getattr(args, "runtime", None)
579+
if runtime in ("onnx-genai", "ort-genai"):
580+
from mobius.integrations.gguf import write_gguf_runtime_package
581+
582+
# The graph is already saved above; this adds the tokenizer (rebuilt
583+
# from the GGUF's embedded ggml metadata, since a GGUF checkpoint has
584+
# no Hugging Face source directory) and the runtime's own contract.
585+
artifacts = write_gguf_runtime_package(
586+
pkg, gguf_path, output_dir, runtime=runtime, save_model=False
599587
)
600588
for name, path in artifacts.items():
601589
print(f" {name}: {path}")

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@
1818
# Multimodal (text + companion mmproj vision/audio encoder)
1919
pkg = build_from_gguf("path/to/model.gguf", mmproj="path/to/mmproj.gguf")
2020
21+
# Write a directory the runtime can actually load (graph + tokenizer +
22+
# inference metadata). Saving only the graph produces a package that
23+
# loads nowhere.
24+
write_gguf_runtime_package(pkg, "path/to/model.gguf", "out_dir")
25+
2126
:func:`build_from_gguf` is the single entry point; passing ``mmproj`` delegates
2227
to :func:`build_gemma4_vlm_from_gguf` for the multimodal assembly.
2328
"""
@@ -26,10 +31,12 @@
2631

2732
from mobius.integrations.gguf._builder import build_from_gguf
2833
from mobius.integrations.gguf._mmproj import build_gemma4_vlm_from_gguf
34+
from mobius.integrations.gguf._runtime_package import write_gguf_runtime_package
2935
from mobius.integrations.gguf._tokenizer import write_gguf_tokenizer_json
3036

3137
__all__ = [
3238
"build_from_gguf",
3339
"build_gemma4_vlm_from_gguf",
40+
"write_gguf_runtime_package",
3441
"write_gguf_tokenizer_json",
3542
]

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -964,10 +964,17 @@ def _detect_quant_params(gguf_model, gguf_arch: str) -> tuple[int, int, bool]:
964964
# Emit those zero_points explicitly: GatherBlockQuantized has diverging
965965
# CPU/CUDA defaults when the input is omitted, which corrupts embeddings
966966
# on CUDA before the first decoder layer runs.
967+
# Whether the repacked form can omit zero points. Every entry here is a
968+
# *repack target* property, not a source-format property: Q4_K and Q6_K both
969+
# requantize through the asymmetric affine path, so both need zero points
970+
# even though Q6_K's source form is symmetric around 32.
971+
# Keep in sync with `_REPACK_PARAMS` in `_repacker.py` — a type that can be
972+
# repacked but is missing here raises `KeyError` at build time.
967973
type_can_omit_zero_points: dict = {
968974
GGMLQuantizationType.Q4_0: False,
969975
GGMLQuantizationType.Q4_1: False,
970976
GGMLQuantizationType.Q4_K: False,
977+
GGMLQuantizationType.Q6_K: False,
971978
GGMLQuantizationType.Q8_0: False,
972979
GGMLQuantizationType.Q1_0: False,
973980
}

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

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -702,7 +702,7 @@ def tensor_items_raw(self):
702702
bits, block_size, is_sym = _detect_quant_params(_MixedModel(), "llama")
703703
assert (bits, block_size, is_sym) == (4, 32, False)
704704

705-
def test_pure_q6_k_requires_explicit_dequantization(self):
705+
def test_unsupported_quant_type_requires_explicit_dequantization(self):
706706
"""Unsupported quantized inputs fail instead of silently becoming float."""
707707
from gguf import GGMLQuantizationType
708708

@@ -713,20 +713,46 @@ def tensor_items_raw(self):
713713
yield (
714714
"blk.0.ffn_down.weight",
715715
np.empty(0, dtype=np.uint8),
716-
GGMLQuantizationType.Q6_K,
716+
GGMLQuantizationType.Q5_K,
717717
(64, 128),
718718
)
719719

720720
with pytest.raises(
721721
ValueError,
722722
match=(
723723
r"No supported quantized preservation target for GGUF weight "
724-
r"types: Q6_K. Use keep_quantized=False \(API\) or "
724+
r"types: Q5_K. Use keep_quantized=False \(API\) or "
725725
r"--dequantize \(CLI\) for explicit float import."
726726
),
727727
):
728728
_detect_quant_params(_UnsupportedModel(), "llama")
729729

730+
def test_q6_k_selects_the_asymmetric_four_bit_repack_target(self):
731+
"""Q6_K repacks to the same 4-bit/32 target as Q4_K, with zero points.
732+
733+
Q6_K's source form is symmetric around 32, but it reaches MatMulNBits
734+
through the asymmetric affine requantizer, so zero points are required.
735+
A missing entry in `type_can_omit_zero_points` raises `KeyError` here
736+
rather than producing a wrong model.
737+
"""
738+
from gguf import GGMLQuantizationType
739+
740+
from mobius.integrations.gguf._builder import _detect_quant_params
741+
742+
class _Q6KModel:
743+
def tensor_items_raw(self):
744+
yield (
745+
"blk.0.ffn_down.weight",
746+
np.empty(0, dtype=np.uint8),
747+
GGMLQuantizationType.Q6_K,
748+
(64, 128),
749+
)
750+
751+
bits, block_size, is_sym = _detect_quant_params(_Q6KModel(), "llama")
752+
753+
assert (bits, block_size) == (4, 32)
754+
assert is_sym is False
755+
730756
def test_runtime_unsupported_format_does_not_select_native_op(self):
731757
"""A GGUF type outside the runtime contract remains on the fallback."""
732758
from gguf import GGMLQuantizationType

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

Lines changed: 98 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
_GGUF_Q4_1 = 3
3939
_GGUF_Q8_0 = 8
4040
_GGUF_Q4_K = 12
41+
_GGUF_Q6_K = 14
4142
_GGUF_IQ2_XXS = 16
4243
_GGUF_IQ2_XS = 17
4344
_GGUF_IQ3_XXS = 18
@@ -56,6 +57,7 @@
5657
_GGUF_Q4_1: 20, # 2B scale + 2B min + 16B quants
5758
_GGUF_Q8_0: 34, # 2B scale + 32B int8 values
5859
_GGUF_Q4_K: 144, # 2B d + 2B dmin + 12B scales + 128B quants
60+
_GGUF_Q6_K: 210, # 128B low nibbles + 64B high bits + 16B scales + 2B d
5961
_GGUF_Q1_0: 18, # 2B scale + 16B packed bits (128 elements)
6062
}
6163

@@ -67,6 +69,7 @@
6769
_GGUF_Q4_1: 32,
6870
_GGUF_Q8_0: 32,
6971
_GGUF_Q4_K: 256,
72+
_GGUF_Q6_K: 256,
7073
_GGUF_Q1_0: 128,
7174
}
7275

@@ -78,6 +81,7 @@
7881
_GGUF_Q4_1: (4, 32),
7982
_GGUF_Q8_0: (8, 32),
8083
_GGUF_Q4_K: (4, 32),
84+
_GGUF_Q6_K: (4, 32),
8185
_GGUF_Q1_0: (2, 128),
8286
}
8387

@@ -199,11 +203,11 @@ def repack_gguf_tensor(
199203
block_bytes = _BLOCK_BYTES[gguf_type]
200204
gguf_block_elems = _GGUF_BLOCK_ELEMENTS[gguf_type]
201205
n_blocks_per_row = math.ceil(k_in / gguf_block_elems)
202-
if gguf_type == _GGUF_Q4_K:
206+
if gguf_type in (_GGUF_Q4_K, _GGUF_Q6_K):
203207
# K-quant super-blocks are laid out over the flattened tensor, not
204208
# independently padded at each logical row boundary. This matters for
205209
# dimensions such as Qwen2's K=896: rows end halfway through a
206-
# 256-element Q4_K super-block, while they still align perfectly to
210+
# 256-element super-block, while they still align perfectly to
207211
# MatMulNBits' 32-element blocks.
208212
total_blocks = math.ceil(n_out * k_in / gguf_block_elems)
209213
else:
@@ -226,6 +230,8 @@ def repack_gguf_tensor(
226230
return _repack_q4_1(blocks, n_out, n_blocks_per_row)
227231
elif gguf_type == _GGUF_Q4_K:
228232
return _repack_q4_k(blocks, n_out, k_in)
233+
elif gguf_type == _GGUF_Q6_K:
234+
return _repack_q6_k(blocks, n_out, k_in)
229235
elif gguf_type == _GGUF_Q1_0:
230236
return _repack_q1_0(blocks, n_out, n_blocks_per_row)
231237
else:
@@ -503,6 +509,96 @@ def _repack_q4_k(
503509
return repack_dequantized_tensor(values, bits=4, block_size=_BLOCK_SIZE)
504510

505511

512+
def _dequantize_q6_k(blocks: np.ndarray) -> np.ndarray:
513+
"""Reconstruct float values from Q6_K super-blocks.
514+
515+
Q6_K stores 256-element super-blocks as
516+
``[ql: 128B][qh: 64B][scales: 16B int8][d: 2B fp16]`` and reconstructs
517+
``value = d * scales[is] * (q - 32)`` where the 6-bit ``q`` is assembled
518+
from a low nibble in ``ql`` and a high 2-bit field in ``qh``.
519+
520+
The element interleave follows ggml's ``dequantize_row_q6_K`` exactly: each
521+
128-element half consumes 64 ``ql`` bytes, 32 ``qh`` bytes and 8 scales,
522+
and emits four 32-element groups whose scales are ``sc[is], sc[is+2],
523+
sc[is+4], sc[is+6]`` with ``is = l // 16``.
524+
525+
Split out from [`_repack_q6_k`] so the interleave can be compared against
526+
the reference dequantizer *exactly*. Every plausible-but-wrong permutation
527+
of this layout still yields finite values of the right magnitude, so an
528+
approximate check cannot tell a correct unpack from a transposed one, and
529+
the lossy requantization that follows would mask the difference.
530+
531+
Args:
532+
blocks: uint8 array, shape ``(total_super_blocks, 210)``.
533+
534+
Returns:
535+
Flat float32 array of ``total_super_blocks * 256`` values.
536+
"""
537+
total = blocks.shape[0]
538+
539+
ql = blocks[:, :128] # (total, 128)
540+
qh = blocks[:, 128:192] # (total, 64)
541+
scales = blocks[:, 192:208].copy().view(np.int8).astype(np.float32)
542+
d = blocks[:, 208:210].copy().view(np.float16).astype(np.float32).ravel()
543+
544+
# Two 128-element halves per super-block; each takes 64 ql, 32 qh, 8 scales.
545+
ql_h = ql.reshape(total, 2, 64)
546+
qh_h = qh.reshape(total, 2, 32)
547+
sc_h = scales.reshape(total, 2, 8)
548+
549+
lo = ql_h[:, :, :32] # ql[l + 0]
550+
hi = ql_h[:, :, 32:] # ql[l + 32]
551+
552+
q1 = (lo & 0x0F) | (((qh_h >> 0) & 0x03) << 4)
553+
q2 = (hi & 0x0F) | (((qh_h >> 2) & 0x03) << 4)
554+
q3 = (lo >> 4) | (((qh_h >> 4) & 0x03) << 4)
555+
q4 = (hi >> 4) | (((qh_h >> 6) & 0x03) << 4)
556+
557+
# (total, 2, 4, 32) in emission order y[l+0], y[l+32], y[l+64], y[l+96].
558+
q = np.stack([q1, q2, q3, q4], axis=2).astype(np.float32) - 32.0
559+
560+
# `is = l // 16` splits each 32-element group into two 16-element halves
561+
# taking consecutive scales; group g uses sc[is + 2*g].
562+
sc_idx = np.array([[0, 1], [2, 3], [4, 5], [6, 7]], dtype=np.intp)
563+
sub_scales = np.repeat(sc_h[:, :, sc_idx], 16, axis=3) # (total, 2, 4, 32)
564+
565+
return (d[:, None, None, None] * sub_scales * q).reshape(-1)
566+
567+
568+
def _repack_q6_k(
569+
blocks: np.ndarray,
570+
n_out: int,
571+
k_in: int,
572+
) -> RepackedTensor:
573+
"""Dequantize Q6_K super-blocks and requantize to MatMulNBits.
574+
575+
The 6-bit width has no MatMulNBits equivalent, and a mixed preset such as
576+
Q4_K_M must use one MatMulNBits configuration across the whole graph, so
577+
the super-blocks are reference-dequantized (see [`_dequantize_q6_k`]) and
578+
affine-requantized to the model's common 4-bit/32 layout — the same
579+
treatment Q4_K already receives. The requantization is lossy.
580+
581+
Args:
582+
blocks: uint8 array, shape ``(total_super_blocks, 210)``.
583+
n_out: Number of output rows (N dimension).
584+
k_in: Number of input columns (K dimension).
585+
586+
Returns:
587+
A ``RepackedTensor`` with ``block_size=32`` and ``bits=4``.
588+
"""
589+
dequantized = _dequantize_q6_k(blocks)
590+
591+
logical_elements = n_out * k_in
592+
if dequantized.size < logical_elements:
593+
raise ValueError(
594+
f"Q6_K data has {dequantized.size} elements, "
595+
f"but shape ({n_out}, {k_in}) requires {logical_elements}"
596+
)
597+
598+
values = dequantized[:logical_elements].reshape(n_out, k_in)
599+
return repack_dequantized_tensor(values, bits=4, block_size=_BLOCK_SIZE)
600+
601+
506602
def repack_dequantized_tensor(
507603
values: np.ndarray,
508604
*,

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

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -700,6 +700,76 @@ def test_q4_k_in_can_repack(self):
700700
assert can_repack(12) is True
701701

702702

703+
class TestRepackQ6K:
704+
"""Q6_K (type 14) -> MatMulNBits 4-bit repacking."""
705+
706+
def test_in_can_repack(self):
707+
"""Q6_K (type 14) is recognized as repackable."""
708+
assert can_repack(14) is True
709+
710+
def test_dequantization_matches_gguf_reference_exactly(self):
711+
"""Our unpack must equal ggml's ``dequantize_row_q6_K``, bit for bit.
712+
713+
Q6_K interleaves each 256-element super-block across two halves, four
714+
emission groups, and a 16-entry scale table. Every plausible-looking
715+
wrong permutation still produces finite numbers of the right magnitude,
716+
so only an exact comparison against the reference implementation can
717+
distinguish a correct unpack from a subtly transposed one -- and the
718+
lossy requantization that follows would mask the difference, which is
719+
why this compares the dequantized floats directly.
720+
"""
721+
gguf_quants = pytest.importorskip("gguf.quants")
722+
from gguf.constants import GGMLQuantizationType
723+
724+
from mobius.integrations.gguf._repacker import _dequantize_q6_k
725+
726+
rng = np.random.default_rng(0)
727+
n_super = 8
728+
blocks = rng.integers(0, 256, size=(n_super, 210), dtype=np.uint8)
729+
# Keep `d` finite and non-denormal so the comparison is about layout.
730+
blocks[:, 208:210] = np.frombuffer(
731+
np.float16([1.5] * n_super).tobytes(), dtype=np.uint8
732+
).reshape(n_super, 2)
733+
734+
expected = gguf_quants.dequantize(
735+
blocks.reshape(-1).copy(), GGMLQuantizationType.Q6_K
736+
).astype(np.float32).ravel()
737+
got = _dequantize_q6_k(blocks)
738+
739+
np.testing.assert_array_equal(got, expected)
740+
741+
def test_repack_stays_within_half_a_block_scale(self):
742+
"""The 4-bit requantization is lossy, but bounded by its own scale."""
743+
from mobius.integrations.gguf._repacker import _dequantize_q6_k, _repack_q6_k
744+
745+
rng = np.random.default_rng(1)
746+
n_out, k_in = 4, 256
747+
n_super = n_out * k_in // 256
748+
blocks = rng.integers(0, 256, size=(n_super, 210), dtype=np.uint8)
749+
blocks[:, 208:210] = np.frombuffer(
750+
np.float16([1.5] * n_super).tobytes(), dtype=np.uint8
751+
).reshape(n_super, 2)
752+
753+
reference = _dequantize_q6_k(blocks)[: n_out * k_in].reshape(n_out, k_in)
754+
result = _repack_q6_k(blocks, n_out, k_in)
755+
got = _dequantize_repacked_q4(result, k_in)
756+
757+
assert result.weight.shape[0] == n_out
758+
max_scale = float(result.scales.max())
759+
assert np.max(np.abs(got - reference)) <= max_scale * 0.51 + 1e-6
760+
761+
def test_super_block_byte_and_element_counts(self):
762+
"""Q6_K is 210 bytes per 256 elements; a wrong size mis-slices silently."""
763+
from mobius.integrations.gguf._repacker import (
764+
_BLOCK_BYTES,
765+
_GGUF_BLOCK_ELEMENTS,
766+
_GGUF_Q6_K,
767+
)
768+
769+
assert _BLOCK_BYTES[_GGUF_Q6_K] == 210
770+
assert _GGUF_BLOCK_ELEMENTS[_GGUF_Q6_K] == 256
771+
772+
703773
class TestRepackDequantizedTensor:
704774
def test_asymmetric_q4_round_trip_bound(self):
705775
rng = np.random.default_rng(0)

0 commit comments

Comments
 (0)