Skip to content

Commit aa93ab6

Browse files
justinchubyCopilot
andauthored
Fail closed on lossy GGUF quantization preservation (#609)
## Summary Fixes the preserved Q4_K_M/MatMulNBits correctness divergence exposed by #607. Q4_K_M is a model-level mixed preset, not a GGML tensor type. The pinned SmolLM artifact contains Q5_0=166, Q4_K=16, Q8_0=15, Q6_K=14, and F32=61 tensors. Mobius correctly decoded Q4_K's 144-byte/256-value layout, six-bit scale/min fields, nibble order, orientation, and signed minimum subtraction, and ORT correctly consumed the emitted affine packing. The divergence came earlier: the importer normalized the mixed Q5/Q4_K/Q6/Q8 source tensors into one four-bit MatMulNBits contract, adding a second lossy quantization. This change: - records which affine repacks preserve dequantized values and rejects lossy or incompatible routes under `keep_quantized=True`; - fails closed for unsupported projections, mixed float projections, embeddings/heads, multimodal builders, MTP sidecars/native blocks, and packed fused expert gate/up tensors; - retains explicit `keep_quantized=False` / `--dequantize` as the opt-in float route; - adds independent asymmetric Q4_K and ORT MatMulNBits value tests plus real SmolLM2 Q4_K_M prefill/decode/generation coverage. ## Root-cause evidence The first divergence is already present in layer 0 before ORT execution: | Tensor role | Source qtype | Relative L2 error after normalization | |---|---:|---:| | Q projection | Q5_0 | 0.09408 | | K projection | Q5_0 | 0.09410 | | V projection | Q8_0 -> Q4 | 0.08793 | | FFN down | Q6_K -> Q4 | 0.08310 | The Q4_K formula is `value = d * sub_scale * q - dmin * sub_min`. Although Q4_K itself can be represented by four-bit MatMulNBits with floating zero points, the full Q4_K_M mixture cannot be represented losslessly by one four-bit graph contract. ORT 1.29 also advertises 8-bit MatMulNBits in schema but the tested CPU unpacked path rejects it with `Only 2b and 4b quantization is supported for unpacked compute for now`. ## Validation - Final focused GGUF/quantization/MatMulNBits suite: **745 passed** - Real pinned SmolLM2 Q4_K_M test: **1 passed** - default API and CLI preservation reject before producing a model; - explicit dequantization builds, saves, reloads, and runs; - full prefill and ten cached-decode logits match the same-artifact Transformers GGUF reference; - maximum prefill absolute difference: **9.0599e-05**; - ten greedy tokens match exactly: `198, 198, 18, 504, 2388, 13685, 284, 5208, 28, 198`. - Earlier broad run: **7058 passed, 52 skipped**; the two remaining `glm_moe_dsa` shape/checker failures reproduce on the base and are unrelated. - Changed-file Ruff check and format check pass. - Two independent final review passes completed; all findings were addressed and the final MoE fix was re-reviewed with no findings. ## Verdict This is an importer preservation-policy bug, not an ORT Q4 packing bug. Preservation now succeeds only for value-equivalent routes and otherwise fails closed rather than emitting wrong logits. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 04c6641 commit aa93ab6

15 files changed

Lines changed: 1074 additions & 249 deletions

‎docs/api/build_from_gguf.md‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ def build_from_gguf(
181181
| `gguf_path` | `str \| Path` | (required) | Local `.gguf` path or `owner/repo:filename.gguf` Hub reference. |
182182
| `task` | `str \| None` | `None` | Override the model task (e.g. `"text-generation"`). When `None`, the task is auto-detected from the model type. |
183183
| `dtype` | `str \| None` | `None` | Override model dtype (e.g. `"f16"`). When `None`, defaults to float32. |
184-
| `keep_quantized` | `bool` | `True` | Preserve quantization when present. Supported affine blocks are repacked as `MatMulNBits`; in text-only builds, supported native IQ/MXFP4 projection blocks retain their bytes. Multimodal and mixed presets may require dequantization/requantization. Set to `False` to dequantize all weights. |
184+
| `keep_quantized` | `bool` | `True` | Preserve quantization when present. Supported affine blocks are repacked as `MatMulNBits`; in text-only builds, supported native IQ/MXFP4 projection blocks retain their bytes. Projection tensors that would require lossy requantization are rejected. Set to `False` to dequantize all weights. |
185185
| `execution_provider` | `str` | `"default"` | Target EP for EP-aware graph optimization. |
186186
| `mmproj` | `str \| Path \| None` | `None` | Optional companion multimodal-projector GGUF. |
187187
| `static_cache` | `bool` | `False` | Build a fixed-width KV cache when the architecture supports it. |
@@ -267,20 +267,23 @@ mobius build-gguf draft.gguf --target-config target/ --output output/draft/
267267

268268
1. Reads GGUF metadata to detect architecture and config
269269
2. Maps GGUF tensor names to HuggingFace weight names
270-
3. Preserves supported quantized tensors by default, using repacking,
271-
text-only native-block retention, or dequantize/requantize according to the
272-
source qtype and build path; `keep_quantized=False` dequantizes every tensor
270+
3. Preserves supported quantized tensors by default using value-preserving
271+
repacking or text-only native-block retention; any projection requiring
272+
lossy requantization fails closed, while `keep_quantized=False` explicitly
273+
dequantizes every tensor
273274
4. Applies architecture-specific tensor processors (e.g. Q/K permute)
274275
5. Builds the ONNX graph using the same pipeline as `build()`
275276
6. Runs `preprocess_weights()` (HF → ONNX name mapping)
276277
7. Applies weights to the graph
277278

278279
F32-, F16-, and BF16-only GGUFs use the normal float import path even though
279280
`keep_quantized=True` is the default: there is no quantization to preserve.
280-
Quantized GGUFs whose qtypes have no trustworthy decoder or compatible runtime
281-
kernel (currently `Q2_0`) fail with an actionable error. Decoder-backed formats
282-
such as `Q5_K` use the explicit dequantize/requantize route; they are not
283-
silently treated as preserved source quantization.
281+
Quantized GGUFs containing only qtypes with no supported preservation target
282+
(for example, pure Q5_K weights) fail with an actionable error rather
283+
than silently becoming float. Pass `keep_quantized=False` to request that float
284+
conversion explicitly.
285+
Mixed presets such as Q4_K_M also fail when their projection inventory includes
286+
Q5/Q6/Q8 tensors that cannot share one lossless MatMulNBits contract.
284287

285288
### Native blocks, conversion, and source-file reuse
286289

‎docs/cli_reference.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -323,9 +323,10 @@ mobius build --model Qwen/Qwen2.5-0.5B --output output_dir/ \
323323

324324
Build an ONNX model from a GGUF file (e.g. from llama.cpp). This is an explicit
325325
opt-in import path; `mobius build` does not auto-discover or select GGUF files.
326-
Supported GGUF quantization is preserved by default. This can involve
327-
byte-preserving native blocks in text-only builds, affine repacking, or
328-
dequantize/requantize for multimodal and mixed source qtypes.
326+
Supported GGUF quantization is preserved by default through byte-preserving
327+
native blocks or value-preserving affine repacking. Mixed source qtypes that
328+
would require lossy dequantization/requantization, including Q4_K_M presets,
329+
fail closed and require `--dequantize`.
329330

330331
> **Note**: Requires the optional `gguf` package: `pip install mobius-onnx[gguf]`
331332
@@ -377,6 +378,8 @@ contain no quantization to preserve.
377378
Quantized files containing only qtypes with no supported preservation target
378379
(for example, pure Q5_K weights) fail instead of silently becoming
379380
float. Re-run with `--dequantize` to request explicit float conversion.
381+
The same rule applies when only some projection tensors are incompatible with
382+
the selected affine target; Mobius does not silently requantize those tensors.
380383

381384
Encoder-only BERT and ModernBERT GGUF backbones auto-select
382385
`feature-extraction` and output `last_hidden_state`; they do not produce logits

‎docs/model-catalog.md‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -267,11 +267,10 @@ All decoder-only LLMs and MoE models support quantized weight loading:
267267
| **AWQ** | HuggingFace (e.g. `-AWQ` suffix models) | `build("TheBloke/Llama-2-7B-AWQ")` |
268268
| **GGUF** | Local `.gguf` files | `build_from_gguf("model.gguf")` |
269269

270-
GGUF import preserves supported quantization by default using affine repacking
271-
or, for supported text-only inputs, native quantized ops. Multimodal and mixed
272-
source qtypes can require dequantization/requantization, so this does not imply
273-
byte preservation for every tensor. Use `--dequantize` for an explicitly float
274-
model.
270+
GGUF import preserves supported quantization by default using value-preserving
271+
affine repacking or, for supported text-only inputs, native quantized ops.
272+
Projection tensors that would require lossy dequantization/requantization fail
273+
closed. Use `--dequantize` for an explicitly float model.
275274

276275
Encoder GGUF imports for `bert` and `modern-bert` select
277276
`feature-extraction` and expose token-level `last_hidden_state` only. Pooling,

‎src/mobius/functions/matmul_nbits_test.py‎

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,12 @@ def _const(name: str, arr: np.ndarray) -> ir.Value:
4646

4747

4848
def _build_matmulnbits_model(
49-
n_out: int, k_in: int, block: int, seed: int = 0
49+
n_out: int,
50+
k_in: int,
51+
block: int,
52+
seed: int = 0,
53+
*,
54+
accuracy_level: int | None = None,
5055
) -> tuple[ir.Model, dict, np.ndarray, np.ndarray, np.ndarray]:
5156
"""Build a single-node MatMulNBits model with random 4-bit weights.
5257
@@ -67,14 +72,15 @@ def _build_matmulnbits_model(
6772
sc_c = _const("scales", scales)
6873
zp_c = _const("zero_points", zero_points)
6974
y = ir.Value(name="Y")
75+
attributes = {"K": k_in, "N": n_out, "bits": 4, "block_size": block}
76+
if accuracy_level is not None:
77+
attributes["accuracy_level"] = accuracy_level
7078
node = ir.Node(
7179
"com.microsoft",
7280
"MatMulNBits",
7381
inputs=[a_val, b_c, sc_c, zp_c],
7482
outputs=[y],
75-
attributes=ir.convenience.convert_attributes(
76-
{"K": k_in, "N": n_out, "bits": 4, "block_size": block}
77-
),
83+
attributes=ir.convenience.convert_attributes(attributes),
7884
)
7985
graph = ir.Graph(
8086
inputs=[a_val],
@@ -118,6 +124,30 @@ def test_inline_matches_native_op(self):
118124

119125
np.testing.assert_allclose(got, reference, rtol=0, atol=0)
120126

127+
def test_accuracy_four_matches_explicit_asymmetric_dequantization(self):
128+
"""The CPU kernel consumes Mobius's packed weights and zero points correctly."""
129+
model, feeds, packed, scales, packed_zero_points = _build_matmulnbits_model(
130+
n_out=8,
131+
k_in=64,
132+
block=32,
133+
seed=11,
134+
accuracy_level=4,
135+
)
136+
got = _run(model, feeds)
137+
138+
quants = np.empty((8, 2, 32), dtype=np.float32)
139+
quants[..., 0::2] = packed & 0x0F
140+
quants[..., 1::2] = packed >> 4
141+
zero_points = np.empty((8, 2), dtype=np.float32)
142+
zero_points[..., 0::2] = packed_zero_points & 0x0F
143+
zero_points[..., 1::2] = packed_zero_points >> 4
144+
weights = ((quants - zero_points[..., None]) * scales[..., None]).reshape(8, 64)
145+
expected = feeds["A"] @ weights.T
146+
147+
error = got - expected
148+
assert float(np.max(np.abs(error))) < 0.1
149+
assert float(np.linalg.norm(error) / np.linalg.norm(expected)) < 0.02
150+
121151
def test_inline_matches_native_op_odd_blocks(self):
122152
"""Odd n_blocks exercises the zero-point nibble slice (ceil(nb/2))."""
123153
# K=96, block=32 → nb=3 (odd)

0 commit comments

Comments
 (0)