Repository navigation
feat(gguf): support Q6_K, fix byte-level tokenizers, emit loadable packages - #543
Conversation
…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
Performance Comparison
|
There was a problem hiding this comment.
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 bytokenizer.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.
| @@ -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
|
Addressed all four review points in 7e39032. @justinchuby — support different backends. @copilot — misleading test name. You were right, and this was the worst of the four: @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 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]>
|
|
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
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.weightthat this model also uses as itslm_head(there is nooutput.weight).repack_dequantized_tensoralready 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'sdequantize_row_q6_Kinterleave: each 128-element half consumes 64qlbytes, 32qhbytes and 8 scales, emitting four 32-element groups withis = 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 declarestokenizer.ggml.model = gpt2, whose vocabulary spells a leading space asĠ— a different alphabet. Every inter-word space was dropped: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.prenames 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-genaiemitted tokenizer + inference metadata, butbuild_from_ggufcallers 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_packagenow 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 raisedKeyError— 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: