Skip to content

Commit 42573f4

Browse files
justinchubyCopilotgithub-code-quality[bot]
authored
Add Q1_0 GGUF support (mainline + Tencent SEQ 2-bit variant) (#302)
## Summary Adds two paths through the GGUF loader for GGML type 41 so mobius can ingest both standard and Tencent's custom variants of Q1_0. ### 1. Mainline Q1_0 — 1-bit binary Layout (18 bytes / 128 elements): `[fp16 d][16B packed 1-bit signs]`. Dequant: `bit ? +d : -d`. Used by [prism-ml/Bonsai](https://huggingface.co/collections/prism-ml/bonsai) checkpoints. Mapped to `MatMulNBits` `bits=2`, `zero_point=1`, codes ∈ {0, 2}, scale=d. ### 2. Tencent custom Q1_0 — 2-bit SEQ Used by [`AngelSlim/Hy-MT1.5-1.8B-2bit-GGUF`](https://huggingface.co/AngelSlim/Hy-MT1.5-1.8B-2bit-GGUF). Per-row layout: `[fp16 stored_scale][2-bit codes packed LSB-first]`, native block size 512, codebook `{−3, −1, +1, +3} · stored_scale`. Mainline llama.cpp **refuses to load** these files because every tensor after the first Q1_0 entry lands at the wrong offset. We bypass the size calculation by reading each tensor from its explicit GGUF offset. Two `MatMulNBits` representations, selected by a flag: | | default | `MOBIUS_TENCENT_Q1_0_USE_NATIVE_2BIT=1` | |---|---|---| | ORT bits | 4 (inflated `2c ∈ {0,2,4,6}`, integer zp=3) | 2 (codes pass-through, float zp=1.5) | | on-disk weight bpw | 4 (2× the source) | 2 (matches source) | | CPU decode throughput | **~32 tok/s** | **~0.24 tok/s** | | ORT version | any | **≥ 1.27** ([#28354](https://github.com/microsoft/onnxruntime/pull/28354)) | Both representations produce **bit-identical dequantized weights** matching HF safetensors to bf16 rounding (`max_abs ≈ 2.5e-3` vs HF reference matmul). The 130× decode speed difference is purely the ORT CPU kernel: the bits=4 path is the mature MLAS fused path, the bits=2 + float-zp path is the kernel's own self-described "naive implementation, need to be optimized" scalar fallback. Tracked in [microsoft/onnxruntime#28552](https://github.com/microsoft/onnxruntime/issues/28552); once that lands the default can flip. **Block-size workaround:** ORT silently returns zeros for `block_size > 256` ([#28551](https://github.com/microsoft/onnxruntime/issues/28551)). Both representations therefore expose `block_size = 128` by replicating each native 512-element scale across 4 sub-blocks. ## Other infrastructure changes - New flag [`tencent_q1_0_use_native_2bit`](src/mobius/_flags.py) (default `False`). - `QuantizedLinear` accepts `bits ∈ {2, 4, 8}` and a new `zero_point_dtype` argument. `UINT8` (default) keeps the bit-packed integer form; float dtypes produce one un-packed value per block. - `QuantizationConfig` gains `float_zero_point`; `TextModel` passes `config.dtype` as the zp dtype when it is set. - GGUF → `ArchitectureConfig` derivation now sets `rope_type` from `<arch>.rope.scaling.type` (defaulting to `"default"` when `rope.freq_base` is present). Without this fix, models with `rope.scaling.type = "none"` were built with no RoPE at all. - For `hunyuan-dense` GGUFs whose `rope.freq_base` exceeds `1e6` (Tencent's pipeline bakes the dynamic-NTK exponent into a static value), the original HF config is restored: `rope_type="dynamic"`, `rope_theta=10000`, `alpha=1000`. Otherwise long prompts diverge. - New GGUF arch mapping `hunyuan-dense → hunyuan_v1_dense` with `attn_q_norm`/`attn_k_norm` tensor name mappings. - `_detect_quant_params` returns `block_size` explicitly so the `QuantizationConfig` matches the actual per-type group size. ## Verification End-to-end on `tencent/Hy-MT1.5-1.8B-2bit`: - **Per-tensor dequantization** matches HF safetensors to bf16-rounding precision (max abs `2.3e-5`). - **Single-layer ORT matmul** vs HF dequantized matmul: max abs `2.5e-3`, mean `2.8e-4`. - **Short-prompt greedy generation** with the chat template produces `Hello, world!<EOS>` token-for-token identical to HF. - **Throughput** with default flag: 0.13 s prefill, 32.8 tok/s decode on CPU EP. Tests: - Split into `TestTencentQ10DefaultInflated4Bit`, `TestTencentQ10NativeBits2`, and `TestTencentQ10Shared` covering both flag values + shape/error invariants. - Full test suite (`tests/build_graph_test.py src/`): **2752 passed, 0 failures**. ## Out of scope / follow-ups - 1.25-bit Sherry (`AngelSlim/Hy-MT1.5-1.8B-1.25bit-GGUF`, [llama.cpp PR #22836](ggml-org/llama.cpp#22836) `STQ1_0`): needs a ternary-with-structured-sparsity codebook that doesn't map cleanly to `MatMulNBits`. Tracked in [microsoft/onnxruntime#28549](https://github.com/microsoft/onnxruntime/issues/28549). - ORT MLAS fast path for `bits=2` + float zp: [microsoft/onnxruntime#28552](https://github.com/microsoft/onnxruntime/issues/28552). When that lands, flip the flag default and remove the bits=4 inflation path. - ORT silent zero output for `block_size > 256`: [microsoft/onnxruntime#28551](https://github.com/microsoft/onnxruntime/issues/28551). --------- Signed-off-by: Justin Chu <[email protected]> Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot <[email protected]> Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com>
1 parent 114a1bc commit 42573f4

18 files changed

Lines changed: 1410 additions & 89 deletions

‎examples/hy_mt1_5.py‎

Lines changed: 239 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,239 @@
1+
# ruff: noqa: RUF002
2+
r"""End-to-end translation example for Hy-MT1.5-1.8B via ORT GenAI.
3+
4+
Demonstrates loading a mobius-built Hy-MT1.5 export with
5+
``onnxruntime-genai`` (no PyTorch at inference time). The HF model_type
6+
``hunyuan_v1_dense`` is mapped to ORT GenAI's generic ``decoder`` LLM
7+
type (see ``onnxruntime-genai/src/models/model_type.h``); this script
8+
verifies that the resulting ``genai_config.json`` loads and that
9+
``Generator`` produces real translations end-to-end.
10+
11+
Two model variants are supported, selected by ``--variant``:
12+
13+
* ``bf16`` - full-precision export from the HuggingFace safetensors.
14+
Note: BF16 MatMul isn't implemented on the ORT CPU EP, so this
15+
variant only runs on CUDA / DML / WebGPU.
16+
* ``Q1_0`` - 2-bit-quantized export from the AngelSlim GGUF (Tencent
17+
SEQ codebook; default mobius packing is ``MatMulNBits bits=4``
18+
inflated form for fast CPU decode).
19+
20+
Tokenizer caveat: the Hy-MT1.5 BPE vocab uses a custom regex
21+
pre-tokenizer that ort-extensions does not currently round-trip
22+
(``"Hello, world!"`` tokenizes to a single space token, ``"你好"``
23+
tokenizes to an empty sequence). By default this example tokenizes
24+
and detokenizes with the HuggingFace tokenizer and feeds raw token
25+
IDs to ``og.Generator``, which still exercises the full ORT GenAI
26+
inference path. Pass ``--use-ort-tokenizer`` to force the broken
27+
``og.Tokenizer`` path for reproduction / debugging.
28+
29+
Expected output (Q1_0 on CPU EP)::
30+
31+
$ python examples/hy_mt1_5.py --variant Q1_0 --out ./hy-mt-q1_0-onnx \\
32+
--prompt 'Translate to Spanish: The cat is sleeping on the chair.'
33+
El gato está durmiendo en la silla.
34+
35+
$ python examples/hy_mt1_5.py --variant Q1_0 --out ./hy-mt-q1_0-onnx \\
36+
--prompt 'Translate to French: Knowledge is power.'
37+
La connaissance est puissance.
38+
39+
$ python examples/hy_mt1_5.py --variant Q1_0 --out ./hy-mt-q1_0-onnx
40+
# default prompt: Translate the following Chinese text to English: 你好,世界!
41+
Hello, world!
42+
43+
Usage::
44+
45+
# Build + run the Q1_0 quantized variant on CPU
46+
huggingface-cli download AngelSlim/Hy-MT1.5-1.8B-2bit-GGUF \\
47+
Hy-MT1.5-1.8B-2bit.gguf --local-dir ./gguf
48+
python examples/hy_mt1_5.py --variant Q1_0 --build \\
49+
--gguf ./gguf/Hy-MT1.5-1.8B-2bit.gguf --out ./hy-mt-q1_0-onnx
50+
51+
# Reuse an existing build (no --build)
52+
python examples/hy_mt1_5.py --variant Q1_0 --out ./hy-mt-q1_0-onnx
53+
"""
54+
55+
from __future__ import annotations
56+
57+
import argparse
58+
import sys
59+
from pathlib import Path
60+
61+
HF_MODEL_ID = "tencent/Hy-MT1.5-1.8B-2bit"
62+
63+
_DEFAULT_PROMPT = "Translate the following Chinese text to English: 你好,世界!" # noqa: RUF001
64+
65+
66+
def _build_bf16(output_dir: Path) -> None:
67+
"""Build the BF16 ONNX model + ORT-GenAI config in-process."""
68+
import mobius
69+
from mobius.integrations.ort_genai.auto_export import write_ort_genai_config
70+
71+
print(f"Building bf16 -> {output_dir}")
72+
pkg = mobius.build(HF_MODEL_ID, dtype="bf16", load_weights=True)
73+
pkg.save(str(output_dir))
74+
write_ort_genai_config(pkg, str(output_dir), hf_model_id=HF_MODEL_ID, ep="cpu")
75+
print(" genai_config.json + tokenizer files written")
76+
77+
78+
def _build_q1_0(gguf_path: Path, output_dir: Path) -> None:
79+
"""Build the 2-bit Q1_0 ONNX model + ORT-GenAI config in-process."""
80+
from mobius.integrations.gguf._builder import build_from_gguf
81+
from mobius.integrations.ort_genai.auto_export import write_ort_genai_config
82+
83+
print(f"Building Q1_0 -> {output_dir}")
84+
# ep='cpu' applies the GroupQueryAttention rewrite. With standard
85+
# opset 23 Attention (ep='default'), ORT GenAI's
86+
# past_present_share_buffer mode cannot be used; mobius's
87+
# write_ort_genai_config inspects the resulting graph and turns
88+
# share_buffer off automatically when GQA is absent.
89+
pkg = build_from_gguf(
90+
str(gguf_path), keep_quantized=True, dtype="f32", execution_provider="cpu"
91+
)
92+
pkg.save(str(output_dir))
93+
write_ort_genai_config(pkg, str(output_dir), hf_model_id=HF_MODEL_ID, ep="cpu")
94+
print(" genai_config.json + tokenizer files written")
95+
96+
97+
def _ensure_built(args: argparse.Namespace) -> Path:
98+
out = Path(args.out).resolve()
99+
if args.build:
100+
out.mkdir(parents=True, exist_ok=True)
101+
if args.variant == "bf16":
102+
_build_bf16(out)
103+
elif args.variant == "Q1_0":
104+
if not args.gguf:
105+
sys.exit("--gguf is required for --variant Q1_0 --build")
106+
_build_q1_0(Path(args.gguf), out)
107+
if not (out / "genai_config.json").exists():
108+
sys.exit(
109+
f"{out}/genai_config.json missing. Re-run with --build or point --out "
110+
"at a directory produced by `mobius build --runtime ort-genai`."
111+
)
112+
return out
113+
114+
115+
def run_translation(
116+
model_dir: Path,
117+
prompt: str,
118+
max_new_tokens: int,
119+
use_hf_tokenizer: bool,
120+
) -> str:
121+
"""Run a single greedy generation through ORT GenAI."""
122+
import onnxruntime_genai as og
123+
124+
print(f"\nLoading ORT GenAI model from {model_dir}")
125+
model = og.Model(str(model_dir))
126+
127+
# Apply the chat template from the model dir (works either way).
128+
chat_template_path = model_dir / "chat_template.jinja"
129+
if chat_template_path.exists():
130+
from jinja2 import Environment
131+
132+
template = Environment().from_string(chat_template_path.read_text())
133+
full_prompt = template.render(
134+
messages=[{"role": "user", "content": prompt}],
135+
add_generation_prompt=True,
136+
)
137+
else:
138+
full_prompt = prompt
139+
140+
print(f"\nPrompt:\n {prompt!r}")
141+
142+
if use_hf_tokenizer:
143+
# Tokenize and detokenize via HuggingFace. ORT-extensions' BPE
144+
# tokenizer does not currently round-trip the Hy-MT1.5 vocab's
145+
# custom regex pre-tokenizer, so we bypass og.Tokenizer here
146+
# while still exercising the ORT GenAI inference path.
147+
import transformers
148+
149+
hf_tok = transformers.AutoTokenizer.from_pretrained(HF_MODEL_ID)
150+
input_tokens = hf_tok.encode(full_prompt, add_special_tokens=False)
151+
152+
params = og.GeneratorParams(model)
153+
params.set_search_options(
154+
max_length=len(input_tokens) + max_new_tokens, do_sample=False
155+
)
156+
generator = og.Generator(model, params)
157+
generator.append_tokens(input_tokens)
158+
159+
print("Generating: ", end="", flush=True)
160+
generated_ids: list[int] = []
161+
while not generator.is_done() and len(generated_ids) < max_new_tokens:
162+
generator.generate_next_token()
163+
new_token = int(generator.get_next_tokens()[0])
164+
generated_ids.append(new_token)
165+
# Decode incrementally; some tokens are multi-byte and only
166+
# render when combined with neighbours, so we re-decode the
167+
# accumulated tail and print the delta.
168+
text_so_far = hf_tok.decode(generated_ids, skip_special_tokens=False)
169+
print(text_so_far, end="\r", flush=True)
170+
print()
171+
return hf_tok.decode(generated_ids, skip_special_tokens=False)
172+
173+
tokenizer = og.Tokenizer(model)
174+
tokenizer_stream = tokenizer.create_stream()
175+
input_tokens = tokenizer.encode(full_prompt)
176+
177+
params = og.GeneratorParams(model)
178+
params.set_search_options(max_length=len(input_tokens) + max_new_tokens, do_sample=False)
179+
generator = og.Generator(model, params)
180+
generator.append_tokens(input_tokens)
181+
182+
print("Generating: ", end="", flush=True)
183+
chunks: list[str] = []
184+
while not generator.is_done():
185+
generator.generate_next_token()
186+
new_token = generator.get_next_tokens()[0]
187+
chunk = tokenizer_stream.decode(new_token)
188+
chunks.append(chunk)
189+
print(chunk, end="", flush=True)
190+
print()
191+
return "".join(chunks)
192+
193+
194+
def main() -> None:
195+
parser = argparse.ArgumentParser(
196+
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
197+
)
198+
parser.add_argument("--variant", choices=("bf16", "Q1_0"), default="bf16")
199+
parser.add_argument(
200+
"--out", default=None, help="ONNX model directory (will be created with --build)"
201+
)
202+
parser.add_argument("--build", action="store_true", help="Build the model before running")
203+
parser.add_argument(
204+
"--gguf",
205+
default=None,
206+
help="Path to the Tencent SEQ GGUF (required with --variant Q1_0 --build)",
207+
)
208+
parser.add_argument("--prompt", default=_DEFAULT_PROMPT)
209+
parser.add_argument("--max-new-tokens", type=int, default=64)
210+
parser.add_argument(
211+
"--use-ort-tokenizer",
212+
action="store_true",
213+
help=(
214+
"Use ort-extensions' tokenizer (og.Tokenizer) instead of the "
215+
"HuggingFace one. The Hy-MT1.5 vocab's custom regex pre-tokenizer "
216+
"is not currently round-tripped by ort-extensions, so by default "
217+
"we tokenize with HF and feed raw token IDs to og.Generator. "
218+
"Enable this flag to exercise the full og.Tokenizer path."
219+
),
220+
)
221+
args = parser.parse_args()
222+
223+
if args.out is None:
224+
args.out = f"./hy-mt-{args.variant.lower()}-onnx"
225+
226+
out = _ensure_built(args)
227+
text = run_translation(
228+
out,
229+
args.prompt,
230+
args.max_new_tokens,
231+
use_hf_tokenizer=not args.use_ort_tokenizer,
232+
)
233+
234+
print("\n--- Full response ---")
235+
print(text)
236+
237+
238+
if __name__ == "__main__":
239+
main()

‎src/mobius/__main__.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,7 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
324324
gguf_path,
325325
dtype=args.dtype,
326326
keep_quantized=args.keep_quantized,
327+
execution_provider=args.execution_provider,
327328
)
328329

329330
pkg.save(
@@ -558,6 +559,18 @@ def main(argv: list[str] | None = None) -> None:
558559
default="onnx",
559560
help="External data format (default: onnx).",
560561
)
562+
gguf_parser.add_argument(
563+
"--ep",
564+
"--execution-provider",
565+
dest="execution_provider",
566+
default="default",
567+
metavar="EP",
568+
help=(
569+
"Target execution provider for EP-aware graph optimisations "
570+
"(e.g. 'cpu' to apply the GroupQueryAttention rewrite). "
571+
"Defaults to 'default' (portable ONNX, no vendor fusions)."
572+
),
573+
)
561574
gguf_parser.set_defaults(func=_cmd_build_gguf)
562575

563576
# --- list ---

‎src/mobius/_configs.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -798,6 +798,10 @@ class QuantizationConfig:
798798
group_size: int = 128
799799
quant_method: str = "none"
800800
sym: bool = True
801+
# When True, zero_points is a per-block float tensor rather than a
802+
# bit-packed uint8. Required for codebooks with non-integer offsets
803+
# (e.g. Tencent SEQ uses 1.5).
804+
float_zero_point: bool = False
801805

802806
@classmethod
803807
def from_transformers(cls, hf_config) -> QuantizationConfig | None:

‎src/mobius/_flags.py‎

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,13 @@ class _Flags:
8383
- ``MOBIUS_ORT_LOWER_OPSET_FOR_EP``
8484
- ``False``
8585
- Lower the ONNX opset declaration to 23 for non-CPU EPs
86-
(ORT ≤1.24.x workaround). Disabled by default.
86+
(ORT <=1.24.x workaround). Disabled by default.
87+
* - ``tencent_q1_0_use_native_2bit``
88+
- ``MOBIUS_TENCENT_Q1_0_USE_NATIVE_2BIT``
89+
- ``False``
90+
- Use native ``MatMulNBits bits=2`` for Tencent SEQ Q1_0
91+
(smaller, semantically faithful, but ~20x slower on CPU EP
92+
pending an MLAS fast path).
8793
"""
8894

8995
suppress_dedup_warning: bool = dataclasses.field(
@@ -99,7 +105,7 @@ class _Flags:
99105
default_factory=lambda: _env_bool("MOBIUS_ORT_CUDA_GROUPED_RMSNORM_WORKAROUND", False)
100106
)
101107
"""Decompose grouped RMSNormalization into basic ops to work around an
102-
ORT ≤1.24.4 CUDA kernel bug that produces wrong results when scale is 2D.
108+
ORT <=1.24.4 CUDA kernel bug that produces wrong results when scale is 2D.
103109
Set ``MOBIUS_ORT_CUDA_GROUPED_RMSNORM_WORKAROUND=1`` when targeting CUDA.
104110
"""
105111

@@ -109,13 +115,41 @@ class _Flags:
109115
"""Lower the ONNX default-domain opset declaration to 23 when creating
110116
ORT sessions on non-CPU execution providers (CUDA, TRT, etc.).
111117
112-
ORT ≤1.24.x EPs didn't register kernels for opset 24 standard ops
118+
ORT <=1.24.x EPs didn't register kernels for opset 24 standard ops
113119
(Squeeze, Reshape, etc.) even though the semantics are unchanged.
114120
Lowering the import declaration lets the EP find its existing kernels.
115121
Set ``MOBIUS_ORT_LOWER_OPSET_FOR_EP=1`` to re-enable if running on
116122
an older ORT build without opset 24 kernel registration.
117123
"""
118124

125+
tencent_q1_0_use_native_2bit: bool = dataclasses.field(
126+
default_factory=lambda: _env_bool("MOBIUS_TENCENT_Q1_0_USE_NATIVE_2BIT", False)
127+
)
128+
"""Emit Tencent custom Q1_0 (2-bit SEQ) tensors using native
129+
``MatMulNBits bits=2`` + float ``zero_point = 1.5`` instead of the
130+
``bits=4`` inflation that defaults today.
131+
132+
Pros (when set to ``True``):
133+
Halves the on-disk weight bytes (2 bpw vs 4 bpw inflated).
134+
Semantically faithful to the source quantization layout.
135+
136+
Cons (default ``False``):
137+
ORT's CPU ``bits=2`` + float-zp dequant path is currently a
138+
naive scalar fallback (~20x slower than the ``bits=4`` packed
139+
path on the same weights). See
140+
`microsoft/onnxruntime#28552
141+
<https://github.com/microsoft/onnxruntime/issues/28552>`_.
142+
Also requires ORT >=1.27 (the float-zp path was added in
143+
`microsoft/onnxruntime#28354
144+
<https://github.com/microsoft/onnxruntime/pull/28354>`_).
145+
146+
The ``bits=4`` default inflates each 2-bit code ``c in {0..3}`` to
147+
a 4-bit slot ``2c in {0,2,4,6}`` paired with integer ``zero_point=3``;
148+
dequant gives the same SEQ codebook values, just at twice the
149+
weight storage. Set ``MOBIUS_TENCENT_Q1_0_USE_NATIVE_2BIT=1`` to
150+
opt in to the smaller native form once kernel performance lands.
151+
"""
152+
119153

120154
# Global singleton — import and use this directly.
121155
flags = _Flags()

0 commit comments

Comments
 (0)