Skip to content

Commit b4f9338

Browse files
justinchubyCopilot
andcommitted
Fix GGUF fidelity report edge cases
Align preflight and loading with actual float graph targets, classify Tencent Q1_0 layouts using their exact storage geometry, and record every mapped tensor. Merge Gemma4 mmproj dispositions into package reports and reject stale report files during report-less saves. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 99b3ba15-953f-4f2b-8238-7b3581075947 Signed-off-by: Justin Chu <[email protected]>
1 parent d5d25e7 commit b4f9338

8 files changed

Lines changed: 895 additions & 43 deletions

File tree

‎src/mobius/_model_package.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,12 @@ def _validate_mtp_save_paths(
176176
os.path.islink(report_path) or not os.path.isfile(report_path)
177177
):
178178
raise ValueError("ModelPackage quantization report output must be a real file.")
179+
if package.gguf_quantization_report is None and os.path.isfile(report_path):
180+
raise ValueError(
181+
"ModelPackage output contains a stale quantization_report.json, but the "
182+
"package being saved has no GGUF quantization report. Remove or clean the "
183+
"output directory before saving."
184+
)
179185
previous_sidecar_name = _read_mtp_sidecar_name(directory)
180186
selected = [name for name in package if components is None or components(name)]
181187
if len(selected) > 1:
@@ -431,8 +437,6 @@ def save(
431437
quantization_report_path = os.path.join(directory, _QUANTIZATION_REPORT)
432438
if self.gguf_quantization_report is not None:
433439
self.gguf_quantization_report.write_json(quantization_report_path)
434-
elif os.path.isfile(quantization_report_path):
435-
os.remove(quantization_report_path)
436440
selected = {
437441
name: model
438442
for name, model in self.data.items()

‎src/mobius/_model_package_test.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,17 @@ def test_roundtrip(self, tmp_path):
353353
assert pkg["model"].graph is not None
354354
assert loaded["model"].graph.num_nodes() == pkg["model"].graph.num_nodes()
355355

356+
def test_save_without_report_rejects_stale_report(self, tmp_path):
357+
report_path = tmp_path / "quantization_report.json"
358+
report_path.write_text('{"user": "owned"}\n', encoding="utf-8")
359+
pkg = ModelPackage({"model": _make_simple_model("model")})
360+
361+
with pytest.raises(ValueError, match=r"stale quantization_report.json"):
362+
pkg.save(str(tmp_path))
363+
364+
assert report_path.read_text(encoding="utf-8") == '{"user": "owned"}\n'
365+
assert not (tmp_path / "model.onnx").exists()
366+
356367
def test_load_multiple(self, tmp_path):
357368
pkg = ModelPackage(
358369
{

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

Lines changed: 67 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -6179,7 +6179,7 @@ def _preflight_quantization_report(
61796179
emit_warning: bool = True,
61806180
include_tensor: Callable[[str], bool] | None = None,
61816181
):
6182-
"""Classify every mapped weight from header metadata before payload conversion."""
6182+
"""Classify every mapped tensor from header metadata before payload conversion."""
61836183
from mobius.components import (
61846184
BlockQuantizedLinear,
61856185
Embedding,
@@ -6204,6 +6204,11 @@ def _preflight_quantization_report(
62046204
Support,
62056205
TensorRole,
62066206
)
6207+
from mobius.integrations.gguf._tencent_q1_0 import (
6208+
is_tencent_q1_0_layout,
6209+
tencent_q1_0_source_nbytes,
6210+
tencent_q1_0_target_bits,
6211+
)
62076212
from mobius.integrations.gguf._tensor_mapping import map_gguf_to_hf_names
62086213

62096214
if name_mapper is None:
@@ -6231,6 +6236,7 @@ def _preflight_quantization_report(
62316236
embedding_stems.add(module_name)
62326237

62336238
float_type_ids = float_storage_type_ids()
6239+
tencent_q1_0 = is_tencent_q1_0_layout(gguf_model)
62346240
source_qtypes: list[tuple[str, int]] = []
62356241
records: list[QuantizationTensorRecord] = []
62366242
rejected: list[QuantizationTensorRecord] = []
@@ -6241,12 +6247,17 @@ def _preflight_quantization_report(
62416247
qtype_name = (
62426248
quant_spec.name if quant_spec is not None else str(getattr(qtype, "name", qtype))
62436249
)
6244-
source_bytes = int(tensor.n_bytes)
6250+
is_tencent_q1_0_tensor = tencent_q1_0 and qtype_name == "Q1_0"
6251+
source_bytes = (
6252+
tencent_q1_0_source_nbytes(tensor)
6253+
if is_tencent_q1_0_tensor
6254+
else int(tensor.n_bytes)
6255+
)
62456256
source_qtypes.append((qtype_name, source_bytes))
62466257
if include_tensor is not None and not include_tensor(tensor.name):
62476258
continue
62486259
hf_name = name_mapper(tensor.name, gguf_arch)
6249-
if hf_name is None or not hf_name.endswith(".weight"):
6260+
if hf_name is None:
62506261
continue
62516262
shape = tuple(int(dim) for dim in reversed(tensor.shape))
62526263
module_hf_name = target_name_mapper(hf_name) if target_name_mapper else hf_name
@@ -6321,7 +6332,6 @@ def _preflight_quantization_report(
63216332
module_stem in float_stems
63226333
or module_stem in embedding_stems
63236334
or module_hf_name in parameter_names
6324-
or len(shape) < 2
63256335
):
63266336
role = TensorRole.NON_MATMUL
63276337
else:
@@ -6335,14 +6345,30 @@ def _preflight_quantization_report(
63356345
or module_stem in embedding_stems
63366346
or target_is_quantized
63376347
or known_float_route
6338-
or len(shape) < 2
63396348
):
6340-
route, exactness, reason = quant_import_decision(
6341-
qtype,
6342-
role,
6343-
target_bits=target_bits,
6344-
target_block_size=target_block_size,
6345-
)
6349+
if is_tencent_q1_0_tensor and role is not TensorRole.NON_MATMUL:
6350+
selected_bits = tencent_q1_0_target_bits()
6351+
if (target_bits, target_block_size) == (selected_bits, 128):
6352+
route = QuantImportRoute.AFFINE_REPACK
6353+
exactness = RepackExactness.EXACT
6354+
reason = (
6355+
"Tencent Q1_0 2-bit/512 blocks are exactly represented as "
6356+
f"INT{selected_bits} affine block-128."
6357+
)
6358+
else:
6359+
route = QuantImportRoute.REJECTED
6360+
exactness = None
6361+
reason = (
6362+
"Tencent Q1_0 requires the selected exact "
6363+
f"INT{selected_bits} affine block-128 target."
6364+
)
6365+
else:
6366+
route, exactness, reason = quant_import_decision(
6367+
qtype,
6368+
role,
6369+
target_bits=target_bits,
6370+
target_block_size=target_block_size,
6371+
)
63466372
is_kimi_reshaped_projection = gguf_arch in {
63476373
"kimi-linear",
63486374
"kimi-k3",
@@ -7025,7 +7051,6 @@ def _load_quantized_state_dict(
70257051
from mobius.components import (
70267052
BlockQuantizedLinear,
70277053
Embedding,
7028-
Linear,
70297054
QuantizedEmbedding,
70307055
QuantizedLinear,
70317056
)
@@ -7061,7 +7086,6 @@ def _load_quantized_state_dict(
70617086
quantized_output_sizes: dict[str, int] = {}
70627087
native_block_stems: dict[str, str] = {}
70637088
quantized_embedding_stems = set()
7064-
float_linear_stems = set()
70657089
embedding_stems = set()
70667090
for mod_name, mod in module.named_modules():
70677091
if isinstance(mod, QuantizedLinear) or getattr(mod, "_gguf_quantized_linear", False):
@@ -7072,8 +7096,6 @@ def _load_quantized_state_dict(
70727096
elif isinstance(mod, QuantizedEmbedding):
70737097
quantized_embedding_stems.add(mod_name)
70747098
embedding_stems.add(mod_name)
7075-
elif isinstance(mod, Linear):
7076-
float_linear_stems.add(mod_name)
70777099
elif isinstance(mod, Embedding):
70787100
embedding_stems.add(mod_name)
70797101

@@ -7214,7 +7236,7 @@ def _load_quantized_state_dict(
72147236
module_stem = (
72157237
module_hf_name[: -len(".weight")] if module_hf_name.endswith(".weight") else None
72167238
)
7217-
is_tencent_q1_0_tensor = tencent_q1_0 and qtype == GGMLQuantizationType.Q1_0
7239+
is_tencent_q1_0_tensor = tencent_q1_0 and qtype_val == GGMLQuantizationType.Q1_0.value
72187240
is_quantized_embedding = (
72197241
module_stem is not None and module_stem in quantized_embedding_stems
72207242
)
@@ -7232,6 +7254,11 @@ def _load_quantized_state_dict(
72327254
np_shape,
72337255
quantized_stems,
72347256
)
7257+
if is_tencent_q1_0_tensor:
7258+
# Tencent tensors are ordinary rank-2 projections. Route them
7259+
# through the custom 130-byte-block parser below rather than the
7260+
# generic target-splitting path, which assumes mainline Q1_0 bytes.
7261+
affine_targets = []
72357262
is_kimi_reshaped_projection = gguf_arch in {
72367263
"kimi-linear",
72377264
"kimi-k3",
@@ -7251,22 +7278,22 @@ def _load_quantized_state_dict(
72517278
"bert",
72527279
"modern-bert",
72537280
}
7281+
is_float_embedding = is_embedding_tensor and not is_quantized_embedding
7282+
output_targets_quantized = module_stem is not None and (
7283+
module_stem in quantized_stems or module_stem in native_block_stems
7284+
)
72547285
tensor_role = (
72557286
TensorRole.EMBEDDING
72567287
if is_embedding_tensor
72577288
else TensorRole.EXPERT
72587289
if len(np_shape) == 3 and ".experts." in hf_name
72597290
else TensorRole.OUTPUT
7260-
if hf_name == "lm_head.weight"
7291+
if hf_name == "lm_head.weight" and output_targets_quantized
72617292
else TensorRole.PROJECTION
72627293
if fused_projection_targets
72637294
or (
72647295
module_stem is not None
7265-
and (
7266-
module_stem in quantized_stems
7267-
or module_stem in native_block_stems
7268-
or module_stem in float_linear_stems
7269-
)
7296+
and (module_stem in quantized_stems or module_stem in native_block_stems)
72707297
)
72717298
else TensorRole.NON_MATMUL
72727299
)
@@ -7278,6 +7305,12 @@ def _load_quantized_state_dict(
72787305
target_bits=target_bits,
72797306
target_block_size=target_block_size,
72807307
)
7308+
if is_tencent_q1_0_tensor and tensor_role is not TensorRole.NON_MATMUL:
7309+
route = QuantImportRoute.AFFINE_REPACK
7310+
reason = (
7311+
"Tencent Q1_0 uses the selected exact "
7312+
f"INT{target_bits} affine block-{target_block_size} representation."
7313+
)
72817314
explicitly_dequantized = (
72827315
dequantize_float_linear_types is not None
72837316
and module_stem in dequantize_float_linear_types
@@ -7292,7 +7325,9 @@ def _load_quantized_state_dict(
72927325
"the stored format has no supported dequantization route."
72937326
)
72947327
route = QuantImportRoute.DEQUANTIZE_REQUANTIZE
7295-
if is_encoder_embedding and quant_spec.dequantize is Support.SUPPORTED:
7328+
if (
7329+
is_encoder_embedding or is_float_embedding
7330+
) and quant_spec.dequantize is Support.SUPPORTED:
72967331
route = QuantImportRoute.DEQUANTIZE_FLOAT
72977332
if route is QuantImportRoute.REJECTED:
72987333
raise ValueError(
@@ -7538,6 +7573,15 @@ def _load_quantized_state_dict(
75387573
data_section_offset,
75397574
tensors_by_name[gguf_name],
75407575
)
7576+
if (repacked.bits, repacked.block_size) != (
7577+
target_bits,
7578+
target_block_size,
7579+
):
7580+
raise ValueError(
7581+
f"Tencent Q1_0 parser produced INT{repacked.bits} "
7582+
f"block-{repacked.block_size} for {hf_name}, but the graph "
7583+
f"expects INT{target_bits} block-{target_block_size}."
7584+
)
75417585
elif is_kimi_reshaped_projection:
75427586
values = gguf_model.dequantize_raw_tensor(raw, qtype, np_shape)
75437587
if hf_name.endswith(".k_b_proj.weight"):

0 commit comments

Comments
 (0)