Skip to content

Commit f462c4e

Browse files
justinchubyCopilot
andauthored
Strengthen GGUF and model contract validation (#628)
## Summary - fail closed on missing/non-positive/non-divisible BERT and ModernBERT GGUF geometry before graph construction - give non-cached seq2seq encoder masks the encoder sequence length while retaining cross-cache accumulation shapes - prefer modality-specific mmproj projector metadata over the documented global fallback - exclude intentionally skipped tokenizer/RoPE tensors from dense C01 exact closure while retaining unknown-tensor rejection - preserve explicit Falcon-H1 projection-bias enables with the global `attention_bias` compatibility fallback - default missing trailing Cohere `no_rope_layers` entries to RoPE instead of indexing past the schedule ## Audited finding disposition | Finding | Disposition | |---|---| | Encoder metadata/geometry | Retained; missing keys now raise precise `ValueError`, all dimensions must be positive, and hidden size must divide head count | | Seq2seq mask shape | Retained; no-cache uses `encoder_sequence_len`, cross-cache uses `cross_past_sequence_len + encoder_sequence_len` | | mmproj override precedence | Retained; modality key wins, global key remains fallback, missing both fails closed | | Known-skip tensor closure | Retained; known skips are excluded, unknown extras still fail exact closure | | Falcon-H1 bias precedence | Retained; explicit per-projection enables survive and global bias remains backward-compatible | | Cohere bounds | Retained; short schedules no longer raise and unspecified trailing layers use RoPE | ## Validation - final base/head: `0432dab09fe44fc2600f37b2b7d6117a8cbcf619` / `9346006c1549bada7622934c7b74ee573520cdd5` - focused adversarial/positive contract tests: 15 passed - final shared GGUF/config/model/graph suite, including #625–#627 coverage: 3,384 passed, 46 skipped - broad non-integration suite on the immediately preceding rebased main: 7,786 passed, 56 skipped, 1 subtest passed - generated GGUF docs check: passed in shared suite - `lintrunner f --output oneline --all-files`: passed - GPT-5.6 Sol, medium review against final exact base: no significant issues This is one signed-off commit replayed directly on current main. No merge requested; CI is intentionally not awaited. Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 0432dab commit f462c4e

12 files changed

Lines changed: 200 additions & 8 deletions

File tree

‎src/mobius/_configs/_base.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3045,8 +3045,10 @@ class FalconH1Config(ArchitectureConfig):
30453045
ssm_out_multiplier: float = 1.0
30463046

30473047
def __post_init__(self) -> None:
3048-
self.attn_qkv_bias = self.attention_bias
3049-
self.attn_o_bias = self.attention_bias
3048+
# Architecture-specific fields win when enabled; attention_bias remains
3049+
# the Hugging Face compatibility fallback for callers that only expose it.
3050+
self.attn_qkv_bias = self.attn_qkv_bias or self.attention_bias
3051+
self.attn_o_bias = self.attn_o_bias or self.attention_bias
30503052
if self.hidden_act != "silu":
30513053
raise ValueError("Falcon-H1 supports only hidden_act='silu'")
30523054
if (

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

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1169,6 +1169,8 @@ def _raise_for_invalid_dense_c01_tensor_contract(gguf_model) -> None:
11691169
"""Validate the exact pinned C01 dense profiles before config extraction."""
11701170
import numpy as np
11711171

1172+
from mobius.integrations.gguf._tensor_mapping import is_known_skip
1173+
11721174
architecture = gguf_model.architecture
11731175
if architecture not in {"baichuan", "chatglm", "phi2", "seed_oss"}:
11741176
return
@@ -1267,6 +1269,7 @@ def _raise_for_invalid_dense_c01_tensor_contract(gguf_model) -> None:
12671269
actual = {
12681270
name: tuple(int(dimension) for dimension in shape)
12691271
for name, _raw, _qtype, shape in items
1272+
if not is_known_skip(name)
12701273
}
12711274
required: dict[str, tuple[int, ...]] = {
12721275
"token_embd.weight": (vocab, hidden),
@@ -2112,10 +2115,35 @@ def _raise_for_invalid_encoder_tensor_contract(gguf_model) -> None:
21122115
return
21132116

21142117
metadata = gguf_model.metadata
2118+
required_geometry = (
2119+
"context_length",
2120+
"embedding_length",
2121+
"feed_forward_length",
2122+
"block_count",
2123+
"attention.head_count",
2124+
)
2125+
missing_geometry = [
2126+
f"{architecture}.{suffix}"
2127+
for suffix in required_geometry
2128+
if f"{architecture}.{suffix}" not in metadata
2129+
]
2130+
if missing_geometry:
2131+
raise ValueError(
2132+
f"{architecture} GGUF is missing required encoder metadata: {missing_geometry}"
2133+
)
21152134
hidden = int(metadata[f"{architecture}.embedding_length"])
21162135
intermediate = int(metadata[f"{architecture}.feed_forward_length"])
21172136
layers = int(metadata[f"{architecture}.block_count"])
21182137
num_heads = int(metadata[f"{architecture}.attention.head_count"])
2138+
context = int(metadata[f"{architecture}.context_length"])
2139+
if min(hidden, intermediate, layers, num_heads, context) <= 0 or hidden % num_heads:
2140+
raise ValueError(
2141+
f"{architecture} GGUF has invalid encoder geometry: "
2142+
f"embedding_length={hidden}, feed_forward_length={intermediate}, "
2143+
f"block_count={layers}, attention.head_count={num_heads}, "
2144+
f"context_length={context}; all values must be positive and "
2145+
"embedding_length must be divisible by attention.head_count"
2146+
)
21192147
num_kv_heads = int(metadata.get(f"{architecture}.attention.head_count_kv", num_heads))
21202148
if num_kv_heads != num_heads:
21212149
raise ValueError(
@@ -2125,13 +2153,16 @@ def _raise_for_invalid_encoder_tensor_contract(gguf_model) -> None:
21252153
vocab = int(metadata.get(f"{architecture}.vocab_size", 0))
21262154
if not vocab:
21272155
vocab = len(metadata.get("tokenizer.ggml.tokens", ()))
2128-
context = int(metadata[f"{architecture}.context_length"])
2156+
if vocab <= 0:
2157+
raise ValueError(f"{architecture} GGUF has no positive vocabulary size")
21292158

21302159
required: dict[str, tuple[int, ...]] = {
21312160
"token_embd.weight": (vocab, hidden),
21322161
}
21332162
if architecture == "bert":
21342163
token_types = int(metadata.get("tokenizer.ggml.token_type_count", 0))
2164+
if token_types <= 0:
2165+
raise ValueError("bert GGUF tokenizer.ggml.token_type_count must be positive")
21352166
required.update(
21362167
{
21372168
"token_types.weight": (token_types, hidden),

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

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4642,6 +4642,43 @@ def test_encoder_gqa_rejected_before_graph_build(
46424642
with pytest.raises(ValueError, match="grouped-query attention is not supported"):
46434643
build_from_gguf(path)
46444644

4645+
@pytest.mark.parametrize("architecture", ["bert", "modern-bert"])
4646+
def test_encoder_missing_geometry_is_actionable(self, architecture: str) -> None:
4647+
from mobius.integrations.gguf._builder import (
4648+
_raise_for_invalid_encoder_tensor_contract,
4649+
)
4650+
4651+
model = SimpleNamespace(
4652+
architecture=architecture,
4653+
metadata={
4654+
f"{architecture}.context_length": 32,
4655+
f"{architecture}.feed_forward_length": 64,
4656+
f"{architecture}.block_count": 1,
4657+
f"{architecture}.attention.head_count": 4,
4658+
},
4659+
)
4660+
with pytest.raises(ValueError, match=r"missing required encoder metadata.*embedding"):
4661+
_raise_for_invalid_encoder_tensor_contract(model)
4662+
4663+
@pytest.mark.parametrize("architecture", ["bert", "modern-bert"])
4664+
def test_encoder_hidden_size_must_divide_attention_heads(self, architecture: str) -> None:
4665+
from mobius.integrations.gguf._builder import (
4666+
_raise_for_invalid_encoder_tensor_contract,
4667+
)
4668+
4669+
model = SimpleNamespace(
4670+
architecture=architecture,
4671+
metadata={
4672+
f"{architecture}.context_length": 32,
4673+
f"{architecture}.embedding_length": 65,
4674+
f"{architecture}.feed_forward_length": 64,
4675+
f"{architecture}.block_count": 1,
4676+
f"{architecture}.attention.head_count": 4,
4677+
},
4678+
)
4679+
with pytest.raises(ValueError, match=r"embedding_length must be divisible"):
4680+
_raise_for_invalid_encoder_tensor_contract(model)
4681+
46454682
@pytest.mark.parametrize("architecture", ["bert", "modern-bert"])
46464683
def test_pooling_classifier_and_task_overrides_are_rejected(
46474684
self, tmp_path: Path, architecture: str

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,24 @@ def test_dense_cohort_missing_geometry_is_actionable_before_graph() -> None:
421421
_raise_for_invalid_dense_c01_tensor_contract(_FakeGGUF("phi2", metadata, {}))
422422

423423

424+
def test_dense_cohort_known_skip_tensors_do_not_break_exact_closure() -> None:
425+
metadata = _metadata("phi2", intermediate=32, layers=1)
426+
metadata["phi2.attention.layer_norm_epsilon"] = 1e-5
427+
tensors = _phi2_tensors(metadata)
428+
tensors["blk.0.rope_freqs.weight"] = (4,)
429+
tensors["tokenizer.ggml.extra"] = (1,)
430+
_raise_for_invalid_dense_c01_tensor_contract(_FakeGGUF("phi2", metadata, tensors))
431+
432+
433+
def test_dense_cohort_still_rejects_unknown_extra_tensors() -> None:
434+
metadata = _metadata("phi2", intermediate=32, layers=1)
435+
metadata["phi2.attention.layer_norm_epsilon"] = 1e-5
436+
tensors = _phi2_tensors(metadata)
437+
tensors["blk.0.unowned.weight"] = (8,)
438+
with pytest.raises(ValueError, match=r"unexpected=.*unowned"):
439+
_raise_for_invalid_dense_c01_tensor_contract(_FakeGGUF("phi2", metadata, tensors))
440+
441+
424442
@pytest.mark.parametrize("context", [0, -1])
425443
def test_dense_cohort_rejects_nonpositive_context_before_graph(context) -> None:
426444
metadata = _metadata("chatglm", layers=1)

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -953,10 +953,10 @@ def supported_projector_types() -> tuple[str, ...]:
953953

954954

955955
def projector_type_for_modality(metadata: Mapping[str, Any], modality: MMProjModality) -> str:
956-
"""Resolve the pinned global-key then modality-key projector fallback."""
957-
projector_type = metadata.get("clip.projector_type")
956+
"""Resolve a modality override before the global projector fallback."""
957+
projector_type = metadata.get(f"clip.{modality.value}.projector_type")
958958
if not projector_type:
959-
projector_type = metadata.get(f"clip.{modality.value}.projector_type")
959+
projector_type = metadata.get("clip.projector_type")
960960
if not isinstance(projector_type, str) or not projector_type:
961961
raise ValueError(
962962
f"clip mmproj has an active {modality.value} encoder but neither "

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,10 @@
1414
CLIP_METADATA_SCHEMA,
1515
LLAMA_CPP_MMPROJ_SHA,
1616
MMPROJ_ARTIFACT_PINS,
17+
MMProjModality,
1718
get_projector_spec,
1819
iter_projector_specs,
20+
projector_type_for_modality,
1921
supported_projector_types,
2022
)
2123
from mobius.integrations.gguf._spec import Support
@@ -157,6 +159,20 @@ def test_metadata_schema_captures_the_pinned_absence_of_a_text_encoder() -> None
157159
assert "Absent from the pinned ABI" in fields["clip.has_text_encoder"].note
158160

159161

162+
def test_modality_projector_overrides_global_fallback() -> None:
163+
metadata = {
164+
"clip.projector_type": "gemma4v",
165+
"clip.audio.projector_type": "gemma4a",
166+
}
167+
assert projector_type_for_modality(metadata, MMProjModality.AUDIO) == "gemma4a"
168+
assert projector_type_for_modality(metadata, MMProjModality.VISION) == "gemma4v"
169+
170+
171+
def test_missing_modality_and_global_projector_fails_closed() -> None:
172+
with pytest.raises(ValueError, match=r"neither 'clip\.projector_type' nor"):
173+
projector_type_for_modality({}, MMProjModality.GENERATED_AUDIO)
174+
175+
160176
@pytest.mark.parametrize("projector_type", ["mlp", "gemma4a", "qwen2.5o"])
161177
def test_deferred_projector_has_no_dispatch_or_loader_closure(projector_type: str) -> None:
162178
spec = get_projector_spec(projector_type)

‎src/mobius/models/cohere.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,11 @@ def forward(
144144
layer_type = (
145145
self.layer_types[layer_index] if self.layer_types else "full_attention"
146146
)
147-
use_rope = self.no_rope_layers is None or self.no_rope_layers[layer_index] == 1
147+
use_rope = (
148+
self.no_rope_layers is None
149+
or layer_index >= len(self.no_rope_layers)
150+
or self.no_rope_layers[layer_index] == 1
151+
)
148152
hidden_states, present_kv = layer(
149153
op,
150154
hidden_states=hidden_states,

‎src/mobius/models/cohere_test.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
from __future__ import annotations
5+
6+
import pytest
7+
8+
from mobius._configs import ArchitectureConfig
9+
from mobius.models.cohere import CohereCausalLMModel
10+
from mobius.tasks import CausalLMTask
11+
12+
13+
@pytest.mark.parametrize("no_rope_layers", [[0], [0, 1]])
14+
def test_cohere_short_or_complete_rope_schedule_builds(no_rope_layers: list[int]) -> None:
15+
config = ArchitectureConfig(
16+
vocab_size=32,
17+
hidden_size=16,
18+
intermediate_size=32,
19+
num_hidden_layers=2,
20+
num_attention_heads=2,
21+
num_key_value_heads=2,
22+
head_dim=8,
23+
hidden_act="silu",
24+
max_position_embeddings=32,
25+
rope_type="default",
26+
layer_types=["full_attention", "full_attention"],
27+
no_rope_layers=no_rope_layers,
28+
tie_word_embeddings=True,
29+
logit_scale=0.0625,
30+
)
31+
package = CausalLMTask().build(CohereCausalLMModel(config), config)
32+
assert "model" in package

‎src/mobius/tasks/_seq2seq.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,10 +110,15 @@ def _build_decoder_graph(
110110
)
111111
encoder_attention_mask = None
112112
if self.use_attention_masks:
113+
encoder_mask_sequence = (
114+
"cross_past_sequence_len + encoder_sequence_len"
115+
if self.use_cross_attention_cache
116+
else enc_seq_len
117+
)
113118
encoder_attention_mask = builder.input(
114119
"encoder_attention_mask",
115120
dtype=ir.DataType.INT64,
116-
shape=[batch, "cross_past_sequence_len + encoder_sequence_len"],
121+
shape=[batch, encoder_mask_sequence],
117122
)
118123

119124
num_heads = config.num_attention_heads

‎src/mobius/tasks/_task_test.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,28 @@ def test_decoder_inputs(self):
334334
assert "past_key_values.0.cross.key" in input_names
335335
assert "past_key_values.0.cross.value" in input_names
336336

337+
@pytest.mark.parametrize(
338+
("use_cross_attention_cache", "expected_shape"),
339+
[
340+
(False, "[batch,encoder_sequence_len]"),
341+
(True, "[batch,cross_past_sequence_len + encoder_sequence_len]"),
342+
],
343+
)
344+
def test_encoder_attention_mask_matches_cross_cache_contract(
345+
self, use_cross_attention_cache, expected_shape
346+
):
347+
from mobius.models.t5 import T5ForConditionalGeneration
348+
349+
config, _ = self._make_seq2seq()
350+
module = T5ForConditionalGeneration(config)
351+
task = Seq2SeqTask(
352+
use_attention_masks=True,
353+
use_cross_attention_cache=use_cross_attention_cache,
354+
)
355+
decoder = task.build(module, config)["decoder"]
356+
inputs = {value.name: value for value in decoder.graph.inputs}
357+
assert str(inputs["encoder_attention_mask"].shape) == expected_shape
358+
337359
def test_decoder_outputs(self):
338360
config, module = self._make_seq2seq()
339361
task = Seq2SeqTask()

0 commit comments

Comments
 (0)