Skip to content

Commit c20e9c9

Browse files
justinchubyCopilot
andcommitted
Validate explicit MTP prediction counts
Prefer authoritative GGUF NextN metadata over default-zero architecture fields, reject absent or invalid prediction counts, and never infer proposal width from hidden-layer depth. Keep tokenizer copying best-effort only for missing optional Hub files while propagating online cache, permission, disk, network, and destination-write failures across supported Hub versions. Co-authored-by: Copilot App <[email protected]> Signed-off-by: Justin Chu <[email protected]>
1 parent 5210c1b commit c20e9c9

2 files changed

Lines changed: 247 additions & 15 deletions

File tree

‎src/mobius/integrations/ort_genai/auto_export.py‎

Lines changed: 58 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -675,9 +675,16 @@ def _copy_tokenizer_files(
675675
676676
Returns list of copied filenames.
677677
"""
678+
from huggingface_hub import errors as hub_errors
678679
from huggingface_hub import hf_hub_download
679680
from huggingface_hub.utils import EntryNotFoundError, LocalEntryNotFoundError
680681

682+
remote_entry_not_found = getattr(
683+
hub_errors,
684+
"RemoteEntryNotFoundError",
685+
EntryNotFoundError,
686+
)
687+
681688
copied: list[str] = []
682689
for filename in _TOKENIZER_FILES:
683690
try:
@@ -692,7 +699,13 @@ def _copy_tokenizer_files(
692699
dst = os.path.join(output_dir, filename)
693700
shutil.copy2(src, dst)
694701
copied.append(filename)
695-
except (EntryNotFoundError, LocalEntryNotFoundError, OSError):
702+
except LocalEntryNotFoundError:
703+
if local_files_only:
704+
continue
705+
raise
706+
except remote_entry_not_found:
707+
# Tokenizer formats are alternatives; a repository is not expected
708+
# to contain every filename in _TOKENIZER_FILES.
696709
continue
697710
return copied
698711

@@ -1991,6 +2004,49 @@ def _mtp_sidecar_model(pkg: ModelPackage) -> tuple[Any, str, Any] | None:
19912004
return None
19922005

19932006

2007+
def _mtp_prediction_count(pkg: ModelPackage, proposer_config: Any) -> int:
2008+
"""Resolve an explicit MTP prediction count without inferring model depth."""
2009+
missing = object()
2010+
target_config = getattr(pkg, "config", None)
2011+
authoritative = getattr(target_config, "_gguf_nextn_predict_layers", missing)
2012+
if authoritative is missing:
2013+
authoritative = getattr(
2014+
proposer_config,
2015+
"_gguf_nextn_predict_layers",
2016+
missing,
2017+
)
2018+
if authoritative is not missing:
2019+
if isinstance(authoritative, bool) or not isinstance(authoritative, int):
2020+
raise TypeError(
2021+
f"_gguf_nextn_predict_layers must be an integer, got {authoritative!r}"
2022+
)
2023+
if authoritative <= 0:
2024+
raise ValueError(
2025+
"An attached MTP sidecar requires positive _gguf_nextn_predict_layers metadata"
2026+
)
2027+
return authoritative
2028+
2029+
for config, field in (
2030+
(target_config, "target num_nextn_predict_layers"),
2031+
(proposer_config, "proposer num_nextn_predict_layers"),
2032+
):
2033+
if config is None or not hasattr(config, "num_nextn_predict_layers"):
2034+
continue
2035+
value = config.num_nextn_predict_layers
2036+
if isinstance(value, bool) or not isinstance(value, int):
2037+
raise TypeError(f"{field} must be an integer, got {value!r}")
2038+
# Zero is the dataclass default and therefore does not prove explicit
2039+
# MTP width. Keep looking for a positive declaration on the proposer.
2040+
if value > 0:
2041+
return value
2042+
if value < 0:
2043+
raise ValueError(f"{field} must be positive, got {value}")
2044+
raise ValueError(
2045+
"An attached MTP sidecar requires an explicit positive "
2046+
"num_nextn_predict_layers declaration"
2047+
)
2048+
2049+
19942050
def _write_mtp_config(pkg: ModelPackage, directory: str) -> str | None:
19952051
"""Write the external target/MTP coordination contract without claiming OGA support."""
19962052
resolved = _mtp_sidecar_model(pkg)
@@ -2024,17 +2080,7 @@ def _write_mtp_config(pkg: ModelPackage, directory: str) -> str | None:
20242080
"ports": _mtp_state_ports(mtp_model),
20252081
},
20262082
},
2027-
"num_nextn_predict_layers": int(
2028-
getattr(
2029-
getattr(pkg, "config", None),
2030-
"num_nextn_predict_layers",
2031-
getattr(
2032-
proposer_config,
2033-
"num_nextn_predict_layers",
2034-
getattr(proposer_config, "num_hidden_layers", 1),
2035-
),
2036-
)
2037-
),
2083+
"num_nextn_predict_layers": _mtp_prediction_count(pkg, proposer_config),
20382084
"shared_embedding": None if dedicated_embeddings else "model.embed_tokens",
20392085
"shared_lm_head": None if dedicated_lm_head else "lm_head",
20402086
"runtime_orchestration": "external",

‎src/mobius/integrations/ort_genai/auto_export_test.py‎

Lines changed: 189 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1064,15 +1064,21 @@ def test_copies_available_files(self, tmp_path):
10641064
(fake_src / "chat_template.jinja").write_text("{{ messages }}")
10651065

10661066
with mock.patch("huggingface_hub.hf_hub_download") as mock_dl:
1067-
mock_dl.side_effect = lambda model_id, filename: (
1067+
from huggingface_hub.utils import LocalEntryNotFoundError
1068+
1069+
mock_dl.side_effect = lambda model_id, filename, **_kwargs: (
10681070
str(fake_src / filename)
10691071
if (fake_src / filename).exists()
1070-
else (_ for _ in ()).throw(OSError("not found"))
1072+
else (_ for _ in ()).throw(LocalEntryNotFoundError("not cached"))
10711073
)
10721074

10731075
dst = tmp_path / "output"
10741076
dst.mkdir()
1075-
copied = _copy_tokenizer_files("fake/model", str(dst))
1077+
copied = _copy_tokenizer_files(
1078+
"fake/model",
1079+
str(dst),
1080+
local_files_only=True,
1081+
)
10761082

10771083
assert "tokenizer.json" in copied
10781084
assert (dst / "tokenizer.json").exists()
@@ -1095,6 +1101,97 @@ def test_local_cache_miss_is_best_effort(self, tmp_path):
10951101
assert copied == []
10961102
assert not list(tmp_path.iterdir())
10971103

1104+
def test_online_cache_miss_propagates(self, tmp_path):
1105+
from huggingface_hub.utils import LocalEntryNotFoundError
1106+
1107+
with (
1108+
mock.patch(
1109+
"huggingface_hub.hf_hub_download",
1110+
side_effect=LocalEntryNotFoundError("unexpected online miss"),
1111+
),
1112+
pytest.raises(LocalEntryNotFoundError, match="unexpected online miss"),
1113+
):
1114+
_copy_tokenizer_files("fake/model", str(tmp_path))
1115+
1116+
def test_online_missing_optional_file_is_skipped(self, tmp_path):
1117+
from huggingface_hub import errors as hub_errors
1118+
1119+
remote_entry_not_found = getattr(
1120+
hub_errors,
1121+
"RemoteEntryNotFoundError",
1122+
None,
1123+
)
1124+
if remote_entry_not_found is None:
1125+
pytest.skip("RemoteEntryNotFoundError is available in huggingface_hub >= 1.0")
1126+
1127+
response = mock.Mock()
1128+
response.status_code = 404
1129+
response.headers = {}
1130+
with mock.patch(
1131+
"huggingface_hub.hf_hub_download",
1132+
side_effect=remote_entry_not_found(
1133+
"optional file absent",
1134+
response=response,
1135+
),
1136+
):
1137+
copied = _copy_tokenizer_files("fake/model", str(tmp_path))
1138+
1139+
assert copied == []
1140+
1141+
def test_hub_zero_x_remote_missing_falls_back_to_entry_not_found(
1142+
self, tmp_path, monkeypatch
1143+
):
1144+
from huggingface_hub import errors as hub_errors
1145+
from huggingface_hub.utils import EntryNotFoundError
1146+
1147+
monkeypatch.delattr(hub_errors, "RemoteEntryNotFoundError")
1148+
with mock.patch(
1149+
"huggingface_hub.hf_hub_download",
1150+
side_effect=EntryNotFoundError("optional file absent"),
1151+
):
1152+
copied = _copy_tokenizer_files("fake/model", str(tmp_path))
1153+
1154+
assert copied == []
1155+
1156+
@pytest.mark.parametrize(
1157+
"error",
1158+
[
1159+
PermissionError("denied"),
1160+
OSError("disk full"),
1161+
RuntimeError("network failure"),
1162+
],
1163+
)
1164+
def test_operational_failures_propagate(self, tmp_path, error):
1165+
with (
1166+
mock.patch("huggingface_hub.hf_hub_download", side_effect=error),
1167+
pytest.raises(type(error), match=str(error)),
1168+
):
1169+
_copy_tokenizer_files(
1170+
"fake/model",
1171+
str(tmp_path),
1172+
local_files_only=True,
1173+
)
1174+
1175+
def test_destination_write_failure_propagates(self, tmp_path):
1176+
source = tmp_path / "tokenizer.json"
1177+
source.write_text("{}")
1178+
with (
1179+
mock.patch(
1180+
"huggingface_hub.hf_hub_download",
1181+
return_value=str(source),
1182+
),
1183+
mock.patch(
1184+
"mobius.integrations.ort_genai.auto_export.shutil.copy2",
1185+
side_effect=PermissionError("destination denied"),
1186+
),
1187+
pytest.raises(PermissionError, match="destination denied"),
1188+
):
1189+
_copy_tokenizer_files(
1190+
"fake/model",
1191+
str(tmp_path),
1192+
local_files_only=True,
1193+
)
1194+
10981195

10991196
class TestCopyTokenizerFilesFromLocal:
11001197
"""Tests for _copy_tokenizer_files_from_local."""
@@ -3730,6 +3827,7 @@ def test_lfm2_runtime_compatibility_is_pinned_to_released_probe(tmp_path):
37303827

37313828
def test_decoder_sidecar_preserves_type_and_matching_compatibility_metadata(tmp_path):
37323829
pkg = _make_fake_llm_pkg("qwen2")
3830+
pkg.config.num_nextn_predict_layers = 1
37333831
pkg["mtp"] = _mock_model(inputs=["hidden_states"], outputs=["draft_logits"])
37343832

37353833
result = write_ort_genai_config(pkg, str(tmp_path))
@@ -3763,6 +3861,7 @@ def test_attached_mtp_sidecar_emits_component_qualified_cache_contract(tmp_path)
37633861
},
37643862
config=types.SimpleNamespace(
37653863
num_hidden_layers=1,
3864+
num_nextn_predict_layers=1,
37663865
use_dedicated_embeddings=False,
37673866
use_dedicated_lm_head=False,
37683867
),
@@ -3819,6 +3918,93 @@ def test_attached_mtp_sidecar_emits_component_qualified_cache_contract(tmp_path)
38193918
assert compatibility["graph_contract"] is not None
38203919

38213920

3921+
def test_gguf_mtp_count_overrides_architecture_config_default_zero(tmp_path):
3922+
from mobius._model_package import ModelPackage
3923+
from mobius._testing import make_config
3924+
3925+
config = make_config(num_nextn_predict_layers=0)
3926+
config._gguf_nextn_predict_layers = 1
3927+
pkg = ModelPackage(
3928+
{"model": _mock_decoder_model(layer_indices=(0,))},
3929+
config=config,
3930+
)
3931+
pkg.mtp_head = ModelPackage(
3932+
{"model": _mock_model(inputs=["hidden_states"], outputs=["mtp_hidden"])},
3933+
config=make_config(num_nextn_predict_layers=0),
3934+
)
3935+
3936+
result = write_ort_genai_config(pkg, str(tmp_path))
3937+
with open(result["mtp_config"], encoding="utf-8") as handle:
3938+
mtp = json.load(handle)
3939+
3940+
assert mtp["num_nextn_predict_layers"] == 1
3941+
3942+
3943+
@pytest.mark.parametrize(
3944+
("authoritative", "error"),
3945+
[
3946+
(0, "requires positive"),
3947+
(-1, "requires positive"),
3948+
(None, "must be an integer"),
3949+
("one", "must be an integer"),
3950+
],
3951+
)
3952+
def test_attached_mtp_rejects_invalid_authoritative_gguf_count(tmp_path, authoritative, error):
3953+
from mobius._model_package import ModelPackage
3954+
3955+
pkg = _make_fake_llm_pkg("qwen2")
3956+
pkg.config._gguf_nextn_predict_layers = authoritative
3957+
pkg.config.num_nextn_predict_layers = 1
3958+
pkg.mtp_head = ModelPackage(
3959+
{"model": _mock_model(inputs=["hidden_states"], outputs=["mtp_hidden"])},
3960+
config=types.SimpleNamespace(num_nextn_predict_layers=1),
3961+
)
3962+
3963+
with pytest.raises((TypeError, ValueError), match=error):
3964+
write_ort_genai_config(pkg, str(tmp_path))
3965+
3966+
3967+
def test_explicit_target_mtp_count_precedes_proposer_declaration(tmp_path):
3968+
from mobius._model_package import ModelPackage
3969+
3970+
pkg = _make_fake_llm_pkg("qwen2")
3971+
pkg.config.num_nextn_predict_layers = 2
3972+
pkg.mtp_head = ModelPackage(
3973+
{"model": _mock_model(inputs=["hidden_states"], outputs=["mtp_hidden"])},
3974+
config=types.SimpleNamespace(num_nextn_predict_layers=1),
3975+
)
3976+
3977+
result = write_ort_genai_config(pkg, str(tmp_path))
3978+
with open(result["mtp_config"], encoding="utf-8") as handle:
3979+
mtp = json.load(handle)
3980+
3981+
assert mtp["num_nextn_predict_layers"] == 2
3982+
3983+
3984+
@pytest.mark.parametrize(
3985+
("target_count", "proposer_count", "error"),
3986+
[
3987+
(0, 0, "explicit positive"),
3988+
(-1, 1, "must be positive"),
3989+
(0, "one", "must be an integer"),
3990+
],
3991+
)
3992+
def test_attached_mtp_requires_valid_positive_prediction_count(
3993+
tmp_path, target_count, proposer_count, error
3994+
):
3995+
from mobius._model_package import ModelPackage
3996+
3997+
pkg = _make_fake_llm_pkg("qwen2")
3998+
pkg.config.num_nextn_predict_layers = target_count
3999+
pkg.mtp_head = ModelPackage(
4000+
{"model": _mock_model(inputs=["hidden_states"], outputs=["mtp_hidden"])},
4001+
config=types.SimpleNamespace(num_nextn_predict_layers=proposer_count),
4002+
)
4003+
4004+
with pytest.raises((TypeError, ValueError), match=error):
4005+
write_ort_genai_config(pkg, str(tmp_path))
4006+
4007+
38224008
@pytest.mark.parametrize("order", ["config-before-save", "save-before-config"])
38234009
@pytest.mark.parametrize("stale_layout", ["same", "different", "extra"])
38244010
def test_attached_mtp_uses_current_package_sidecar_despite_stale_manifest(

0 commit comments

Comments
 (0)