Skip to content

Commit 0768c8c

Browse files
committed
Tighten GGUF mmproj preflight guards
Preserve meaningful separators in source identities, distinguish missing metadata from empty values, and reject whitespace-only bindings while retaining conservative URL normalization.\n\nRequire Gemma4 RGB rank-4 patch weights exactly matching the exported graph and validate every pinned active Gemma4 audio field, including positive integer mel-bin metadata, before graph construction. Add collision, presence, shape, and audio metadata regressions.\n\nCo-authored-by: Copilot App <[email protected]>\nCopilot-Session: cc4ea80d-0194-436b-b31b-84a8a8a42a2a Signed-off-by: Justin Chu <[email protected]>
1 parent 48bb486 commit 0768c8c

4 files changed

Lines changed: 248 additions & 30 deletions

File tree

‎docs/api/build_from_gguf.md‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -590,11 +590,18 @@ and concatenate their feature rows in prompt media order.
590590
Pairing is fail-closed and independent of local filenames. Both GGUF files must
591591
carry matching non-empty `general.name` values. If either file declares
592592
`general.base_model.0.name` or `general.base_model.0.repo_url`, the other must
593-
declare the same normalized binding. Architecture and matching tensor dimensions
594-
alone are not accepted as source identity. The validator also inventories every
595-
sidecar tensor: Gemma4's exact deferred `gemma4a` companion closure is allowed
596-
when declared, but unknown top-level names, near-miss prefixes/suffixes, ranks,
597-
and packed projector tensors are rejected before graph construction.
593+
declare the same non-empty binding. Canonicalization is conservative: casing,
594+
outer whitespace, URL host syntax, a trailing slash, and a trailing `.git` are
595+
normalized, but meaningful name and path separators are preserved. Architecture
596+
and matching tensor dimensions alone are not accepted as source identity. The
597+
validator also inventories every sidecar tensor: Gemma4's exact deferred
598+
`gemma4a` companion closure is allowed only with all pinned active-audio
599+
metadata (including a positive integer `clip.audio.num_mel_bins`), but unknown
600+
top-level names, near-miss prefixes/suffixes, ranks, and packed projector
601+
tensors are rejected before graph construction. Gemma4 vision specifically
602+
requires an RGB Conv2d patch weight shaped `[hidden, 3, patch, patch]`; rank-5
603+
patch weights remain valid only for supported topologies whose graphs consume
604+
temporal patches.
598605

599606
Sharded GGUF files are rejected. A single shard has only part of the tensor
600607
table, and treating it as a complete checkpoint would create a corrupt model.

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

Lines changed: 88 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
from collections.abc import Callable
4747
from pathlib import Path
4848
from typing import Any
49+
from urllib.parse import urlsplit, urlunsplit
4950

5051
import numpy as np
5152

@@ -289,18 +290,35 @@ def _canonical_text_architecture(architecture: str) -> str:
289290

290291

291292
def _normalized_identity(value: object) -> str:
292-
return "".join(character for character in str(value).lower() if character.isalnum())
293+
if not isinstance(value, str):
294+
return ""
295+
return value.strip().casefold()
293296

294297

295298
def _normalized_repository(value: object) -> str:
296-
repository = str(value).strip().lower().rstrip("/")
297-
if repository.endswith(".git"):
299+
if not isinstance(value, str):
300+
return ""
301+
repository = value.strip()
302+
if not repository:
303+
return ""
304+
parsed = urlsplit(repository)
305+
if parsed.scheme:
306+
path = parsed.path.rstrip("/")
307+
if path.casefold().endswith(".git"):
308+
path = path[:-4]
309+
return urlunsplit(
310+
(
311+
parsed.scheme.casefold(),
312+
parsed.netloc.casefold(),
313+
path.casefold(),
314+
parsed.query,
315+
parsed.fragment,
316+
)
317+
)
318+
repository = repository.rstrip("/")
319+
if repository.casefold().endswith(".git"):
298320
repository = repository[:-4]
299-
for prefix in ("https://", "http://", "hf://"):
300-
if repository.startswith(prefix):
301-
repository = repository[len(prefix) :]
302-
break
303-
return repository
321+
return repository.casefold()
304322

305323

306324
def _validate_mmproj_source_identity(text_gguf: Any, mmproj_gguf: Any) -> None:
@@ -311,19 +329,30 @@ def _validate_mmproj_source_identity(text_gguf: Any, mmproj_gguf: Any) -> None:
311329
("general.base_model.0.repo_url", _normalized_repository),
312330
)
313331
for key, normalize in bindings:
314-
text_value = text_gguf.metadata.get(key)
315-
sidecar_value = mmproj_gguf.metadata.get(key)
316-
if key == "general.name" and (not text_value or not sidecar_value):
332+
text_present = key in text_gguf.metadata
333+
sidecar_present = key in mmproj_gguf.metadata
334+
if key == "general.name" and not (text_present and sidecar_present):
317335
raise ValueError(
318336
"Cannot establish a trusted text/mmproj pairing: both files must declare "
319337
"non-empty general.name metadata."
320338
)
321-
if bool(text_value) != bool(sidecar_value):
339+
if text_present != sidecar_present:
322340
raise ValueError(
323341
"Cannot establish a trusted text/mmproj pairing: identity binding "
324342
f"{key!r} is present on only one file."
325343
)
326-
if text_value and sidecar_value and normalize(text_value) != normalize(sidecar_value):
344+
if not text_present:
345+
continue
346+
text_value = text_gguf.metadata[key]
347+
sidecar_value = mmproj_gguf.metadata[key]
348+
text_identity = normalize(text_value)
349+
sidecar_identity = normalize(sidecar_value)
350+
if not text_identity or not sidecar_identity:
351+
raise ValueError(
352+
"Cannot establish a trusted text/mmproj pairing: identity binding "
353+
f"{key!r} must be a non-empty string on both files."
354+
)
355+
if text_identity != sidecar_identity:
327356
raise ValueError(
328357
"mmproj source identity does not match the text GGUF: "
329358
f"{key} is {sidecar_value!r} on the sidecar and {text_value!r} "
@@ -381,6 +410,35 @@ def _validate_block_tensor_set(
381410
)
382411

383412

413+
def _validate_gemma4_audio_metadata(metadata: dict[str, Any]) -> None:
414+
"""Validate every pinned field required by an active Gemma4 audio encoder."""
415+
if metadata["clip.has_audio_encoder"] is not True:
416+
raise ValueError("clip.has_audio_encoder must be boolean true for gemma4a.")
417+
positive_integer_keys = (
418+
"clip.audio.embedding_length",
419+
"clip.audio.feed_forward_length",
420+
"clip.audio.block_count",
421+
"clip.audio.projection_dim",
422+
"clip.audio.attention.head_count",
423+
"clip.audio.num_mel_bins",
424+
)
425+
for key in positive_integer_keys:
426+
value = metadata[key]
427+
if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or value <= 0:
428+
raise ValueError(f"{key} must be a positive integer, got {value!r}.")
429+
epsilon = metadata["clip.audio.attention.layer_norm_epsilon"]
430+
if (
431+
isinstance(epsilon, bool)
432+
or not isinstance(epsilon, (int, float, np.integer, np.floating))
433+
or not math.isfinite(float(epsilon))
434+
or epsilon <= 0
435+
):
436+
raise ValueError(
437+
"clip.audio.attention.layer_norm_epsilon must be a positive finite "
438+
f"number, got {epsilon!r}."
439+
)
440+
441+
384442
def _validate_mmproj_tensor_closure(mmproj_gguf: Any, spec: ProjectorSpec) -> None:
385443
"""Validate the complete sidecar inventory, including deferred companions."""
386444
names = set(mmproj_gguf.tensor_names)
@@ -412,6 +470,8 @@ def _validate_mmproj_tensor_closure(mmproj_gguf: Any, spec: ProjectorSpec) -> No
412470
f"{companion.projector_type} companion is missing required metadata: "
413471
f"{missing_metadata}"
414472
)
473+
if companion.projector_type == "gemma4a":
474+
_validate_gemma4_audio_metadata(mmproj_gguf.metadata)
415475
companion_top = set(companion.required_top_tensors)
416476
companion_blocks, companion_matched = _collect_block_tensors(
417477
names,
@@ -565,17 +625,13 @@ def _validate_supported_mmproj_shapes(mmproj_gguf: Any, spec: ProjectorSpec) ->
565625
)
566626

567627
patch_shape = mmproj_gguf.get_tensor_shape("v.patch_embd.weight")
568-
if len(patch_shape) not in (4, 5) or patch_shape[0] != hidden:
569-
raise ValueError(
570-
f"v.patch_embd.weight must be rank 4/5 with output {hidden}, got {patch_shape}."
571-
)
572-
if patch_shape[-2:] != (patch, patch):
573-
raise ValueError(
574-
f"v.patch_embd.weight spatial kernel {patch_shape[-2:]} does not match "
575-
f"clip.vision.patch_size={patch}."
576-
)
577-
578628
if spec.projector_type == "gemma4v":
629+
expected_patch_shape = (hidden, 3, patch, patch)
630+
if patch_shape != expected_patch_shape:
631+
raise ValueError(
632+
"Gemma4 v.patch_embd.weight must have graph-compatible shape "
633+
f"{expected_patch_shape}, got {patch_shape}."
634+
)
579635
position_shape = mmproj_gguf.get_tensor_shape("v.position_embd.weight")
580636
if len(position_shape) != 3 or position_shape[0] != 2 or position_shape[2] != hidden:
581637
raise ValueError(
@@ -619,6 +675,15 @@ def _validate_supported_mmproj_shapes(mmproj_gguf: Any, spec: ProjectorSpec) ->
619675
return
620676

621677
if spec.projector_type == "muse-glimmer":
678+
if (
679+
len(patch_shape) not in (4, 5)
680+
or patch_shape[0] != hidden
681+
or patch_shape[-2:] != (patch, patch)
682+
):
683+
raise ValueError(
684+
"Muse Glimmer v.patch_embd.weight must be rank 4/5 with output "
685+
f"{hidden} and a {patch}x{patch} spatial kernel, got {patch_shape}."
686+
)
622687
merge = int(md["clip.vision.spatial_merge_size"])
623688
position_shape = mmproj_gguf.get_tensor_shape("v.position_embd.weight")
624689
if len(position_shape) != 2 or position_shape[1] != hidden:

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,7 @@ class MMProjArtifactPin:
390390
"clip.audio.projection_dim",
391391
"clip.audio.attention.head_count",
392392
"clip.audio.attention.layer_norm_epsilon",
393+
"clip.audio.num_mel_bins",
393394
)
394395

395396

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

Lines changed: 147 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ def _write_clip_mmproj_gguf(
4545
extra_tensor: str | None = None,
4646
identity_name: str = "Gemma-4-E2B-It",
4747
identity_repo: str | None = "https://huggingface.co/google/gemma-4-E2B-it",
48+
patch_weight_shape: tuple[int, ...] | None = None,
49+
audio_num_mel_bins: int | None = _NUM_MEL_BINS,
4850
) -> None:
4951
"""Write a small synthetic Gemma4 ``clip`` mmproj GGUF for tests."""
5052
from gguf import GGUFWriter
@@ -75,7 +77,10 @@ def _f32(name: str, shape: tuple[int, ...]) -> None:
7577
writer.add_tensor(name, np.random.randn(*shape).astype(np.float32))
7678

7779
# patch embed (conv layout) + position table + projector.
78-
_f32("v.patch_embd.weight", (_VISION_HIDDEN, 3, _PATCH_SIZE, _PATCH_SIZE))
80+
_f32(
81+
"v.patch_embd.weight",
82+
patch_weight_shape or (_VISION_HIDDEN, 3, _PATCH_SIZE, _PATCH_SIZE),
83+
)
7984
_f32("v.position_embd.weight", (2, _POS_EMB_SIZE, _VISION_HIDDEN))
8085
_f32("mm.input_projection.weight", (_TEXT_HIDDEN, _VISION_HIDDEN))
8186
for layer in range(_VISION_LAYERS):
@@ -103,7 +108,8 @@ def _f32(name: str, shape: tuple[int, ...]) -> None:
103108
writer.add_uint32("clip.audio.feed_forward_length", _AUDIO_FFN)
104109
writer.add_uint32("clip.audio.block_count", _AUDIO_LAYERS)
105110
writer.add_uint32("clip.audio.attention.head_count", _AUDIO_HEADS)
106-
writer.add_uint32("clip.audio.num_mel_bins", _NUM_MEL_BINS)
111+
if audio_num_mel_bins is not None:
112+
writer.add_uint32("clip.audio.num_mel_bins", audio_num_mel_bins)
107113
writer.add_uint32("clip.audio.projection_dim", _TEXT_HIDDEN)
108114
writer.add_float32("clip.audio.attention.layer_norm_epsilon", 1e-6)
109115
_f32("a.conv1d.0.weight", (_AUDIO_CONV0, 1, 3, 3))
@@ -511,6 +517,145 @@ def test_matching_identity_survives_file_relocation(self, tmp_path: Path):
511517
resolved = _preflight_mmproj_pair(text, mmproj, modalities=(MMProjModality.VISION,))
512518
assert resolved[MMProjModality.VISION].projector_type == "gemma4v"
513519

520+
@pytest.mark.parametrize(
521+
("text_name", "sidecar_name"),
522+
[
523+
("Model-A", "ModelA"),
524+
("org/model", "orgmodel"),
525+
("model_a", "model-a"),
526+
],
527+
)
528+
def test_identity_normalization_preserves_meaningful_separators(
529+
self, tmp_path: Path, text_name: str, sidecar_name: str
530+
):
531+
from mobius.integrations.gguf._mmproj import _preflight_mmproj_pair
532+
from mobius.integrations.gguf._mmproj_registry import MMProjModality
533+
534+
text_path = tmp_path / "gemma4.gguf"
535+
mmproj_path = tmp_path / "mmproj.gguf"
536+
_write_minimal_gguf(text_path, "gemma4")
537+
_write_clip_mmproj_gguf(mmproj_path, with_audio=False)
538+
text, mmproj = self._load_pair(text_path, mmproj_path)
539+
text.metadata["general.name"] = text_name
540+
mmproj.metadata["general.name"] = sidecar_name
541+
542+
with pytest.raises(ValueError, match=r"general\.name"):
543+
_preflight_mmproj_pair(text, mmproj, modalities=(MMProjModality.VISION,))
544+
545+
@pytest.mark.parametrize("empty_value", ["", " \t "])
546+
def test_empty_identity_values_are_rejected(self, tmp_path: Path, empty_value: str):
547+
from mobius.integrations.gguf._mmproj import _preflight_mmproj_pair
548+
from mobius.integrations.gguf._mmproj_registry import MMProjModality
549+
550+
text_path = tmp_path / "gemma4.gguf"
551+
mmproj_path = tmp_path / "mmproj.gguf"
552+
_write_minimal_gguf(text_path, "gemma4")
553+
_write_clip_mmproj_gguf(mmproj_path, with_audio=False)
554+
text, mmproj = self._load_pair(text_path, mmproj_path)
555+
text.metadata["general.name"] = empty_value
556+
mmproj.metadata["general.name"] = empty_value
557+
558+
with pytest.raises(ValueError, match=r"non-empty string"):
559+
_preflight_mmproj_pair(text, mmproj, modalities=(MMProjModality.VISION,))
560+
561+
def test_one_sided_present_empty_optional_binding_is_not_treated_absent(
562+
self, tmp_path: Path
563+
):
564+
from mobius.integrations.gguf._mmproj import _preflight_mmproj_pair
565+
from mobius.integrations.gguf._mmproj_registry import MMProjModality
566+
567+
text_path = tmp_path / "gemma4.gguf"
568+
mmproj_path = tmp_path / "mmproj.gguf"
569+
_write_minimal_gguf(text_path, "gemma4")
570+
_write_clip_mmproj_gguf(mmproj_path, with_audio=False)
571+
text, mmproj = self._load_pair(text_path, mmproj_path)
572+
text.metadata["general.base_model.0.repo_url"] = ""
573+
mmproj.metadata.pop("general.base_model.0.repo_url")
574+
575+
with pytest.raises(ValueError, match=r"present on only one file"):
576+
_preflight_mmproj_pair(text, mmproj, modalities=(MMProjModality.VISION,))
577+
578+
def test_repository_canonicalization_only_normalizes_url_syntax(self, tmp_path: Path):
579+
from mobius.integrations.gguf._mmproj import _preflight_mmproj_pair
580+
from mobius.integrations.gguf._mmproj_registry import MMProjModality
581+
582+
text_path = tmp_path / "gemma4.gguf"
583+
mmproj_path = tmp_path / "mmproj.gguf"
584+
_write_minimal_gguf(text_path, "gemma4")
585+
_write_clip_mmproj_gguf(mmproj_path, with_audio=False)
586+
text, mmproj = self._load_pair(text_path, mmproj_path)
587+
text.metadata["general.base_model.0.repo_url"] = (
588+
"HTTPS://HUGGINGFACE.CO/Google/Gemma-4-E2B-It.git/"
589+
)
590+
591+
resolved = _preflight_mmproj_pair(text, mmproj, modalities=(MMProjModality.VISION,))
592+
assert resolved[MMProjModality.VISION].projector_type == "gemma4v"
593+
594+
@pytest.mark.parametrize(
595+
"patch_shape",
596+
[
597+
(_VISION_HIDDEN, 1, 3, _PATCH_SIZE, _PATCH_SIZE),
598+
(_VISION_HIDDEN, 1, _PATCH_SIZE, _PATCH_SIZE),
599+
(_VISION_HIDDEN, 3, _PATCH_SIZE, _PATCH_SIZE + 1),
600+
],
601+
)
602+
def test_gemma4_patch_shape_rejects_before_graph_build(
603+
self, tmp_path: Path, patch_shape: tuple[int, ...]
604+
):
605+
from mobius.integrations.gguf._mmproj import build_gemma4_vlm_from_gguf
606+
607+
text_path = tmp_path / "gemma4.gguf"
608+
mmproj_path = tmp_path / "mmproj.gguf"
609+
_write_minimal_gguf(text_path, "gemma4")
610+
_write_clip_mmproj_gguf(
611+
mmproj_path,
612+
with_audio=False,
613+
patch_weight_shape=patch_shape,
614+
)
615+
616+
with (
617+
mock.patch("mobius._builder.build_from_module") as build_graph,
618+
pytest.raises(ValueError, match=r"graph-compatible shape"),
619+
):
620+
build_gemma4_vlm_from_gguf(text_path, mmproj_path, image_token_id=0)
621+
build_graph.assert_not_called()
622+
623+
@pytest.mark.parametrize("num_mel_bins", [None, 0])
624+
def test_audio_num_mel_bins_rejects_before_graph_build(
625+
self, tmp_path: Path, num_mel_bins: int | None
626+
):
627+
from mobius.integrations.gguf._mmproj import build_gemma4_vlm_from_gguf
628+
629+
text_path = tmp_path / "gemma4.gguf"
630+
mmproj_path = tmp_path / "mmproj.gguf"
631+
_write_minimal_gguf(text_path, "gemma4")
632+
_write_clip_mmproj_gguf(
633+
mmproj_path,
634+
with_audio=True,
635+
audio_num_mel_bins=num_mel_bins,
636+
)
637+
638+
with (
639+
mock.patch("mobius._builder.build_from_module") as build_graph,
640+
pytest.raises(ValueError, match=r"clip\.audio\.num_mel_bins"),
641+
):
642+
build_gemma4_vlm_from_gguf(text_path, mmproj_path, image_token_id=0)
643+
build_graph.assert_not_called()
644+
645+
def test_audio_num_mel_bins_wrong_type_is_rejected(self, tmp_path: Path):
646+
from mobius.integrations.gguf._mmproj import _preflight_mmproj_pair
647+
from mobius.integrations.gguf._mmproj_registry import MMProjModality
648+
649+
text_path = tmp_path / "gemma4.gguf"
650+
mmproj_path = tmp_path / "mmproj.gguf"
651+
_write_minimal_gguf(text_path, "gemma4")
652+
_write_clip_mmproj_gguf(mmproj_path, with_audio=True)
653+
text, mmproj = self._load_pair(text_path, mmproj_path)
654+
mmproj.metadata["clip.audio.num_mel_bins"] = "8"
655+
656+
with pytest.raises(ValueError, match=r"positive integer"):
657+
_preflight_mmproj_pair(text, mmproj, modalities=(MMProjModality.VISION,))
658+
514659
def test_quantized_projector_weight_is_rejected_by_role(self, tmp_path: Path):
515660
from types import SimpleNamespace
516661

0 commit comments

Comments
 (0)