Skip to content

feat(gguf): support Q6_K, fix byte-level tokenizers, emit loadable packages - #543

Merged
justinchuby merged 5 commits into
mainfrom
feat/gguf-q6k-and-bytelevel-tokenizer
Aug 22, 2026
Merged

justinchuby merged 5 commits into
mainfrom
feat/gguf-q6k-and-bytelevel-tokenizer

Conversation

@justinchuby

Copy link
Copy Markdown
Member

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

…ckages

Three defects blocked running a Q4_K_M GGUF (tencent/Hy-MT2-1.8B) end to end.

**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 holds 34% of the bytes including the
193 MB tied token_embd/lm_head matrix. `repack_dequantized_tensor` already
documented Q6_K as an expected input for exactly this reason, but no unpacker
existed, so the build failed. Adds `_repack_q6_k`, following ggml's
`dequantize_row_q6_K` interleave, verified bit-for-bit against gguf's own
dequantizer on six real tensors of 1M+ elements each.

**Byte-level tokenizers were decoded as SentencePiece.** The reconstructor
applied Metaspace ('U+2581') unconditionally, but this model declares
`tokenizer.ggml.model = gpt2`, whose vocabulary spells a leading space as
'U+0120'. Every inter-word space was dropped: "Hello, world!" round-tripped as
"Hello,!world!". The code warned and emitted the broken tokenizer anyway.
Now dispatches on the declared family.

Fixing the alphabet was not sufficient: `tokenizer.ggml.pre` names the *split*
rule, which the byte-level model does not imply, and families disagree on how
digits, CJK, and punctuation group. A mismatch still round-trips, so it is
only visible at the id level -- a tab case decomposed as [184, 25056] instead
of [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.

**The Python API could not produce a loadable package.** `--runtime onnx-genai`
emitted tokenizer + inference metadata, but `build_from_gguf` callers got a
bare graph that loads nowhere. Rather than document a second call sequence,
`write_gguf_runtime_package` now owns the full artifact set and the CLI routes
through it, so the two paths cannot disagree about what a complete package is.

Also adds Q6_K to `type_can_omit_zero_points`; its absence raised KeyError,
which the existing test caught. That test asserted Q6_K was unsupported, so it
is retargeted to Q5_K, which still is, preserving the "no silent float
fallback" guarantee it was written to protect.

Tests: 330 passed, 0 failed.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: d60eb808-7cc6-4abc-b48d-2a6dd3841624
@justinchuby
justinchuby requested review from a team and a lite review from Copilot August 22, 2026 01:58
@github-actions

github-actions Bot commented Aug 22, 2026 •

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing 9603636 → 82ccead

Model Sub-model Changes Status

No architecture changes detected. ✅


Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed)

@github-actions

github-actions Bot commented Aug 22, 2026 •

Copy link
Copy Markdown

Performance Comparison

Comparing 9603636 → 82ccead

Model Metric Baseline Current Delta
bert (feature-extraction) model_size_bytes 359 KB 359 KB +0.0% ⚪
bert (feature-extraction) num_nodes 68 68 +0.0% ⚪
falcon model_size_bytes 364 KB 364 KB +0.0% ⚪
falcon num_nodes 66 66 +0.0% ⚪
gemma2 model_size_bytes 428 KB 428 KB +0.0% ⚪
gemma2 num_nodes 105 105 +0.0% ⚪
gpt2 model_size_bytes 388 KB 388 KB +0.0% ⚪
gpt2 num_nodes 54 54 +0.0% ⚪
llama model_size_bytes 425 KB 425 KB +0.0% ⚪
llama num_nodes 60 60 +0.0% ⚪
llama (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
llama (static-cache) num_nodes 56 56 +0.0% ⚪
mamba (ssm-text-generation) model_size_bytes 296 KB 296 KB +0.0% ⚪
mamba (ssm-text-generation) num_nodes 94 94 +0.0% ⚪
phi3 model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 num_nodes 58 58 +0.0% ⚪
phi3 (static-cache) model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 (static-cache) num_nodes 54 54 +0.0% ⚪
qwen2 model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 num_nodes 60 60 +0.0% ⚪
qwen2 (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 (static-cache) num_nodes 56 56 +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) model_size_bytes 506 KB 506 KB +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) num_nodes 264 264 +0.0% ⚪
qwen3_5_text (hybrid-text-generation) model_size_bytes 458 KB 458 KB +0.0% ⚪
qwen3_5_text (hybrid-text-generation) num_nodes 126 126 +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) model_size_bytes 977 KB 977 KB +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) num_nodes 428 428 +0.0% ⚪
t5 (seq2seq) model_size_bytes 836 KB 836 KB +0.0% ⚪
t5 (seq2seq) num_nodes 166 166 +0.0% ⚪
whisper (speech-to-text) model_size_bytes 1008 KB 1008 KB +0.0% ⚪
whisper (speech-to-text) num_nodes 128 128 +0.0% ⚪

No performance regressions.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes end-to-end GGUF export/runtime packaging by (1) adding Q6_K repacking support, (2) correctly reconstructing byte-level (GPT-2 family) tokenizers from GGUF metadata, and (3) centralizing emission of a complete onnx-genai-loadable artifact set for both CLI and Python API paths.

Changes:

  • Add Q6_K (type 14) super-block dequantize + requantize path to the existing MatMulNBits 4-bit/32 repack target.
  • Dispatch tokenizer reconstruction based on tokenizer.ggml.model (byte-level vs SentencePiece semantics) and apply per-family split rules keyed by tokenizer.ggml.pre.
  • Introduce write_gguf_runtime_package() as the single “complete package” emitter and route the CLI runtime path through it.

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
src/mobius/integrations/gguf/_tokenizer.py Adds byte-level vs SentencePiece tokenizer-family dispatch and pre-split rules for byte-level tokenizers.
src/mobius/integrations/gguf/_tokenizer_test.py Adds coverage for byte-level space preservation and split-rule selection/fallback.
src/mobius/integrations/gguf/_runtime_package.py New shared writer that emits model + tokenizer + inference metadata for onnx-genai runtime loading.
src/mobius/integrations/gguf/_runtime_package_test.py Verifies runtime package emission behavior and save_model=False behavior for the CLI flow.
src/mobius/integrations/gguf/_repacker.py Adds Q6_K type constants/params and implements _repack_q6_k() using ggml-compatible interleave.
src/mobius/integrations/gguf/_repacker_test.py Adds Q6_K repack tests and updates coverage for block sizing and expected behavior.
src/mobius/integrations/gguf/_builder.py Ensures Q6_K is handled consistently when selecting whether zero_points can be omitted.
src/mobius/integrations/gguf/_builder_test.py Retargets “unsupported quant type” test to Q5_K and adds a Q6_K target-selection test.
src/mobius/integrations/gguf/init.py Exports write_gguf_runtime_package() and documents its use in the module docstring.
src/mobius/main.py Routes mobius build-gguf --runtime onnx-genai through the shared runtime package emitter.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines 154 to 158
@@ -145,7 +158,7 @@ def _reconstruct_tokenizer_from_ggml(gguf_path: Path, output_dir: str | Path) ->
round-trip fails.
Four review points.

**Support both runtimes (justinchuby).** `write_gguf_runtime_package` was
hardwired to onnx-genai. It now takes `runtime="onnx-genai"|"ort-genai"` and
dispatches to the matching writer, and the CLI passes the flag through. The
`build-gguf --runtime ort-genai` rejection is removed so mobius can emit for
both today rather than waiting on the other side to land; an unknown runtime
name still fails closed.

**Misleading test name (Copilot).** `test_dequantization_matches_gguf_reference_exactly`
claimed a bit-for-bit match but asserted a tolerance bound after a lossy 4-bit
requantization. The dequantization is now split into `_dequantize_q6_k`, so the
test compares the dequantized floats against gguf's reference with
`assert_array_equal` — which is what the name says and what was actually
verified by hand. The requantization bound moved to its own test.

**Stale docstring (Copilot).** `_reconstruct_tokenizer_from_ggml` said it
returns `None` when the round-trip fails; it warns and emits anyway, because
the ids are correct by construction from the ggml ordering. Docstring now
matches.

**CodeQL `__eq__` (github-code-quality).** `_FakePackage` subclassed `dict` and
added attributes without overriding `__eq__`. The emitter only calls `save()`
and reads `config`, so the mapping behaviour was unused state — dropped the
base class instead of adding an `__eq__` no caller needs.

Tests: 333 passed, 0 failed (330 before; +3 for the ort-genai path, the
unknown-runtime guard, and the split requantization bound).

Co-authored-by: Copilot <[email protected]>
Copilot-Session: d60eb808-7cc6-4abc-b48d-2a6dd3841624
@justinchuby

Copy link
Copy Markdown
Member Author

Addressed all four review points in 7e39032.

@justinchuby — support different backends. write_gguf_runtime_package was hardwired to onnx-genai. It now takes runtime="onnx-genai"|"ort-genai" and dispatches to the matching writer; the CLI passes the flag through. I also removed the build-gguf --runtime ort-genai rejection, so mobius can emit for both today rather than waiting on the other side to land — an unknown runtime name still fails closed.

@copilot — misleading test name. You were right, and this was the worst of the four: test_dequantization_matches_gguf_reference_exactly claimed bit-for-bit but asserted a tolerance bound after the lossy 4-bit requantization. Split the dequantization into _dequantize_q6_k so the test compares the dequantized floats against gguf's reference with assert_array_equal — which is what the name says, and what I had actually verified by hand on six real tensors. The requantization bound is now its own test under its own name.

@copilot — stale docstring. Fixed; it now states that a failed round-trip is reported but not fatal, and why (the ids are correct by construction from the ggml ordering, and a byte-incomplete vocab cannot necessarily represent arbitrary probe text).

@github-code-quality — CodeQL __eq__. _FakePackage subclassed dict and added attributes without overriding __eq__. The emitter only calls save() and reads config, so the mapping behaviour was unused state — dropped the base class rather than adding an __eq__ no caller needs.

Tests: 333 passed, 0 failed (330 before; +3 covering the ort-genai path, the unknown-runtime guard, and the split requantization bound).

The RUFF-FORMAT linter flagged two constructs in the previous commit that
ruff collapses onto a single line at the project's 95-character limit: the
unknown-runtime ValueError message in `write_gguf_runtime_package` and the
`write_onnx_genai_config` mock return value in its test. Formatting only; no
behaviour change. 333 tests still pass.

Co-authored-by: justinchuby <[email protected]>
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ justinchuby
❌ Copilot
You have signed the CLA already but the status is still pending? Let us recheck it.

@justinchuby
justinchuby merged commit eec8e3f into main Aug 22, 2026
6 of 7 checks passed
@justinchuby
justinchuby deleted the feat/gguf-q6k-and-bytelevel-tokenizer branch August 22, 2026 15:27
justinchuby added a commit that referenced this pull request Aug 22, 2026
Resolves 15 conflict blocks across 8 files.

Twelve were formatting-only: main had run ruff format over code this branch
also touched (quoted vs bare type annotations, list concat vs unpacking, line
wrapping, a docstring rewording). Took main's side so the formatter would not
immediately undo the merge. One of those blocks also dropped `_index_dim1`,
which was defined and never called.

Three were genuine two-sided changes and both sides are kept:

- `__main__.py`: this branch added the MTP sidecar save; main replaced the
  runtime dispatch with `write_gguf_runtime_package` (dual onnx-genai/ort-genai
  from #543). The code after the conflict already referenced both, so dropping
  either would not have compiled.
- `_group_query_attention.py` / its test: main added sliding-window support
  (`local_window_size` from the attention bias) plus a
  `TestSlidingWindowSurvivesFusion` suite; this branch had only a reformat
  there.

`inference_metadata_test.py` needed more than conflict resolution. The branch's
copy predates main's removal of `add_explicit_package_io` and referenced it
seven times, so taking the branch side broke collection for six modules. Took
main's file and re-applied this branch's `TestMtpSpeculatorMetadata` block
(with its `_MtpBackboneConfig` fixture and `_seed_backbone_metadata` helper),
plus the `write_mtp_speculator_metadata` import.

`_seed_backbone_metadata` seeded `{"model_type": "qwen3_5_text"}`, which the
runtime schema rejects as an unknown top-level property — a schema failure for
a reason unrelated to the speculator block under test. Seeded an empty document
instead; the writer only appends `speculative`.

Tests: gguf + rewrite_rules 475 passed / 1 skipped. In
inference_metadata_test.py, 4 pre-existing failures remain (reproduced on
origin/main using main's own test file) and `TestMtpSpeculatorMetadata`'s
schema case still fails — see the PR discussion, it is a stale committed schema
rather than a defect in this branch.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: d60eb808-7cc6-4abc-b48d-2a6dd3841624
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants