Skip to content

Commit 30ff64a

Browse files
Copilotjustinchuby
andauthored
Enforce package graph availability
Require every ModelPackage component to retain an in-memory ONNX graph, so runtime metadata generation does not rely on reloading exported models. Signed-off-by: GitHub <[email protected]> Co-authored-by: justinchuby <[email protected]>
1 parent e930574 commit 30ff64a

4 files changed

Lines changed: 20 additions & 254 deletions

File tree

‎src/mobius/_model_package.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,12 @@ def __repr__(self) -> str:
5555
names = ", ".join(repr(k) for k in self.data)
5656
return f"ModelPackage({{{names}}})"
5757

58+
def __setitem__(self, name: str, model: ir.Model) -> None:
59+
"""Store a component whose ONNX graph is available for downstream tooling."""
60+
if not isinstance(model, ir.Model) or model.graph is None:
61+
raise TypeError(f"ModelPackage component {name!r} must be an ir.Model with a graph")
62+
super().__setitem__(name, model)
63+
5864
# -- Persistence -------------------------------------------------------
5965

6066
def save(

‎src/mobius/_model_package_test.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import logging
99

1010
import onnx_ir as ir
11+
import pytest
1112
import torch
1213

1314
from mobius._builder import build_from_module
@@ -37,6 +38,14 @@ def test_setitem(self):
3738
pkg["new"] = m
3839
assert pkg["new"] is m
3940

41+
def test_rejects_component_without_graph(self):
42+
with pytest.raises(TypeError, match="must be an ir.Model with a graph"):
43+
ModelPackage({"invalid": object()}) # type: ignore[arg-type]
44+
45+
pkg = ModelPackage()
46+
with pytest.raises(TypeError, match="must be an ir.Model with a graph"):
47+
pkg["invalid"] = object() # type: ignore[assignment]
48+
4049
def test_delitem(self):
4150
pkg = ModelPackage({"a": _make_simple_model()})
4251
del pkg["a"]
@@ -99,6 +108,7 @@ def test_roundtrip(self, tmp_path):
99108

100109
assert len(loaded) == 1
101110
assert "model" in loaded
111+
assert pkg["model"].graph is not None
102112
assert loaded["model"].graph.num_nodes() == pkg["model"].graph.num_nodes()
103113

104114
def test_load_multiple(self, tmp_path):

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

Lines changed: 4 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
import os
1717
from typing import Any
1818

19-
import onnx_ir as ir
2019
import yaml
2120

2221
from mobius.integrations.onnx_genai.decoder_metadata import (
@@ -25,7 +24,6 @@
2524
)
2625
from mobius.integrations.onnx_genai.inference_metadata import (
2726
SchedulerConfig,
28-
_component_filenames,
2927
add_explicit_package_io,
3028
load_diffusers_scheduler_config,
3129
write_audio_codec_pipeline_metadata,
@@ -41,78 +39,20 @@
4139

4240

4341
def _add_explicit_io_to_file(path: str, pkg: Any, config: Any) -> None:
44-
"""Augment an emitted sidecar with roles derived from the actual ONNX ports.
45-
46-
Port roles (``kv_inputs``/``kv_outputs``/``state_pairs`` etc.) are derived
47-
from each component's ONNX graph ports. Normally the built in-memory package
48-
still holds the ``ir.Model`` objects, so ``model.graph`` is available. But a
49-
large decoder built with external-data / streamed weights may not retain its
50-
graph in memory, in which case we reload the graph from the ``model.onnx``
51-
file already written next to the sidecar. Only when a component's graph is
52-
truly unavailable (missing in memory *and* on disk) do we skip it — and then
53-
loudly, never silently shipping thin metadata.
54-
"""
42+
"""Augment an emitted sidecar with roles derived from the actual ONNX ports."""
5543
try:
56-
component_names = list(pkg.keys())
44+
models = list(pkg.values())
5745
except AttributeError:
5846
return
59-
if not component_names:
47+
if not models or any(not hasattr(model, "graph") for model in models):
6048
return
61-
62-
output_dir = os.path.dirname(path)
63-
filenames = _component_filenames(pkg)
64-
resolved: dict[str, Any] = {}
65-
for name in component_names:
66-
model = pkg[name]
67-
if hasattr(model, "graph") and model.graph is not None:
68-
resolved[name] = model
69-
continue
70-
model_path = os.path.join(output_dir, filenames[name])
71-
graph_model = _load_graph_from_disk(model_path)
72-
if graph_model is None:
73-
_LOGGER.warning(
74-
"onnx-genai: skipping explicit 'model.io' port contract for "
75-
"component %r in %s — its ONNX graph is not available in memory "
76-
"and could not be reloaded from %s. The sidecar will ship without "
77-
"the derived 'io' block (kv_inputs/kv_outputs/state_pairs); "
78-
"downstream runtimes must derive ports from the graph at load.",
79-
name,
80-
path,
81-
model_path,
82-
)
83-
return
84-
resolved[name] = graph_model
85-
8649
with open(path, encoding="utf-8") as handle:
8750
metadata = yaml.safe_load(handle)
88-
add_explicit_package_io(metadata, resolved, config)
51+
add_explicit_package_io(metadata, pkg, config)
8952
with open(path, "w", encoding="utf-8") as handle:
9053
yaml.safe_dump(metadata, handle, sort_keys=False)
9154

9255

93-
def _load_graph_from_disk(model_path: str) -> Any | None:
94-
"""Reload an ONNX model (with external data) for graph-port derivation.
95-
96-
Returns the loaded ``ir.Model`` (a drop-in for the in-memory model's
97-
``.graph`` access), or ``None`` if the file is absent or cannot be parsed.
98-
External data resolves relative to *model_path*, so the sidecar-adjacent
99-
``model.onnx`` + ``model.onnx.data`` load without materializing weights we
100-
do not need for port inspection.
101-
"""
102-
if not os.path.isfile(model_path):
103-
return None
104-
try:
105-
return ir.load(model_path)
106-
except Exception:
107-
_LOGGER.warning(
108-
"onnx-genai: failed to reload ONNX graph from %s for explicit "
109-
"model.io derivation.",
110-
model_path,
111-
exc_info=True,
112-
)
113-
return None
114-
115-
11656
def _write_clip_tokenizer(output_dir: str, source: str | None) -> str | None:
11757
"""Emit ``tokenizer.json`` for a text-conditioned diffusion package.
11858

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

Lines changed: 0 additions & 190 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
from __future__ import annotations
77

88
import dataclasses
9-
import os
109

1110
import onnx_ir as ir
1211
import pytest
@@ -484,192 +483,3 @@ def test_decoder_without_source_skips_tokenizer(tmp_path):
484483
artifacts = write_onnx_genai_config(object(), str(tmp_path), config=_Cfg())
485484
assert "tokenizer" not in artifacts
486485
assert not (tmp_path / "tokenizer.json").exists()
487-
488-
489-
class _GraphlessModel:
490-
"""Stand-in for a built component whose ONNX graph was streamed to disk.
491-
492-
Large decoders built with external-data / streamed weights do not retain
493-
the ``ir.Graph`` in memory, so the in-memory package value exposes no
494-
``.graph`` attribute. The port contract must instead be derived from the
495-
``model.onnx`` written next to the sidecar.
496-
"""
497-
498-
499-
class _GraphlessPkg(dict):
500-
pass
501-
502-
503-
def _ir_value(name: str, dtype: ir.DataType, shape: list[int | str]) -> ir.Value:
504-
return ir.Value(name=name, type=ir.TensorType(dtype), shape=ir.Shape(shape))
505-
506-
507-
def _ir_decoder_model(
508-
inputs: list[ir.Value],
509-
output_specs: list[tuple[str, ir.DataType, list[int | str]]],
510-
) -> ir.Model:
511-
outputs = [_ir_value(*spec) for spec in output_specs]
512-
nodes = [
513-
ir.Node("", "Identity", [inputs[0]], outputs=[out], name=f"emit_{out.name}")
514-
for out in outputs
515-
]
516-
graph = ir.Graph(
517-
inputs=inputs,
518-
outputs=outputs,
519-
nodes=nodes,
520-
name="decoder",
521-
opset_imports={"": 21},
522-
)
523-
return ir.Model(graph, ir_version=10)
524-
525-
526-
@dataclasses.dataclass
527-
class _HybridCfg(_Cfg):
528-
# A hybrid decoder mirroring Qwen3.6-27B: linear-attention layers carrying
529-
# conv_state + recurrent_state interleaved with grouped-query-attention KV
530-
# layers. This is the shape that shipped thin metadata (io block dropped).
531-
layer_types: list[str] | None = dataclasses.field(
532-
default_factory=lambda: [
533-
"linear_attention",
534-
"linear_attention",
535-
"full_attention",
536-
]
537-
)
538-
539-
540-
def _write_hybrid_decoder_onnx(directory: str) -> None:
541-
inputs = [
542-
_ir_value("input_ids", ir.DataType.INT64, ["batch", "sequence"]),
543-
_ir_value("attention_mask", ir.DataType.INT64, ["batch", "past_sequence + sequence"]),
544-
_ir_value("position_ids", ir.DataType.INT64, ["batch", "sequence"]),
545-
]
546-
output_specs = [("logits", ir.DataType.FLOAT, ["batch", "sequence", 128])]
547-
# Layers 0-1: linear attention (conv_state + recurrent_state replace-state).
548-
for layer in (0, 1):
549-
inputs.extend(
550-
[
551-
_ir_value(
552-
f"past_key_values.{layer}.conv_state",
553-
ir.DataType.FLOAT,
554-
["batch", 10240, 3],
555-
),
556-
_ir_value(
557-
f"past_key_values.{layer}.recurrent_state",
558-
ir.DataType.FLOAT,
559-
["batch", 48, 128, 128],
560-
),
561-
]
562-
)
563-
output_specs.extend(
564-
[
565-
(f"present.{layer}.conv_state", ir.DataType.FLOAT, ["batch", 10240, 3]),
566-
(
567-
f"present.{layer}.recurrent_state",
568-
ir.DataType.FLOAT,
569-
["batch", 48, 128, 128],
570-
),
571-
]
572-
)
573-
# Layer 2: grouped-query attention (KV append cache).
574-
inputs.extend(
575-
[
576-
_ir_value(
577-
"past_key_values.2.key", ir.DataType.FLOAT, ["batch", 4, "past_sequence", 256]
578-
),
579-
_ir_value(
580-
"past_key_values.2.value",
581-
ir.DataType.FLOAT,
582-
["batch", 4, "past_sequence", 256],
583-
),
584-
]
585-
)
586-
output_specs.extend(
587-
[
588-
("present.2.key", ir.DataType.FLOAT, ["batch", 4, "total_sequence", 256]),
589-
("present.2.value", ir.DataType.FLOAT, ["batch", 4, "total_sequence", 256]),
590-
]
591-
)
592-
model = _ir_decoder_model(inputs, output_specs)
593-
ir.save(model, os.path.join(directory, "model.onnx"))
594-
595-
596-
def test_graphless_decoder_reloads_io_from_disk(tmp_path):
597-
# Regression: when the in-memory package value lacks `.graph` (external-data /
598-
# streamed build), the sidecar MUST still gain its explicit `model.io` port
599-
# contract by reloading `model.onnx` from disk — never ship thin metadata.
600-
_write_hybrid_decoder_onnx(str(tmp_path))
601-
pkg = _GraphlessPkg({"model": _GraphlessModel()})
602-
assert not hasattr(pkg["model"], "graph")
603-
604-
arts = write_onnx_genai_config(pkg, str(tmp_path), config=_HybridCfg())
605-
with open(arts["inference_metadata"]) as handle:
606-
meta = yaml.safe_load(handle)
607-
608-
io = meta["model"]["io"]
609-
assert io["kv_inputs"] == ["past_key_values.2.key", "past_key_values.2.value"]
610-
assert io["kv_outputs"] == ["present.2.key", "present.2.value"]
611-
# The linear-attention layers' conv/recurrent state are replace-state pairs,
612-
# locking the 27B hybrid scenario.
613-
state_inputs = {pair["input"] for pair in io["state_pairs"]}
614-
assert state_inputs == {
615-
"past_key_values.0.conv_state",
616-
"past_key_values.0.recurrent_state",
617-
"past_key_values.1.conv_state",
618-
"past_key_values.1.recurrent_state",
619-
}
620-
assert all(pair["update"] == "replace" for pair in io["state_pairs"])
621-
assert io["token_input"] == "input_ids"
622-
assert io["logits_output"] == "logits"
623-
624-
625-
def test_graphless_decoder_without_disk_model_warns_and_skips(tmp_path, caplog):
626-
# If the graph is unavailable in memory AND absent on disk, we must not ship
627-
# thin metadata silently — emit a loud warning and leave the sidecar without
628-
# the `io` block (downstream runtimes derive it from the graph at load).
629-
import logging
630-
631-
pkg = _GraphlessPkg({"model": _GraphlessModel()})
632-
with caplog.at_level(logging.WARNING):
633-
arts = write_onnx_genai_config(pkg, str(tmp_path), config=_Cfg())
634-
635-
with open(arts["inference_metadata"]) as handle:
636-
meta = yaml.safe_load(handle)
637-
assert "io" not in meta.get("model", {})
638-
assert any("model.io" in rec.message for rec in caplog.records)
639-
640-
641-
def test_in_memory_graph_is_not_reloaded_from_disk(tmp_path, monkeypatch):
642-
# When `.graph` is present in memory, we must derive io directly and never
643-
# touch the disk reload path (preserving existing fast-path behavior).
644-
from mobius.integrations.onnx_genai import auto_export
645-
646-
def _boom(_model_path):
647-
raise AssertionError("disk reload must not run when .graph is present")
648-
649-
monkeypatch.setattr(auto_export, "_load_graph_from_disk", _boom)
650-
651-
inputs = [
652-
_ir_value("input_ids", ir.DataType.INT64, ["batch", "sequence"]),
653-
_ir_value("attention_mask", ir.DataType.INT64, ["batch", "past_sequence + sequence"]),
654-
_ir_value("position_ids", ir.DataType.INT64, ["batch", "sequence"]),
655-
_ir_value(
656-
"past_key_values.0.key", ir.DataType.FLOAT, ["batch", 4, "past_sequence", 256]
657-
),
658-
_ir_value(
659-
"past_key_values.0.value", ir.DataType.FLOAT, ["batch", 4, "past_sequence", 256]
660-
),
661-
]
662-
output_specs = [
663-
("logits", ir.DataType.FLOAT, ["batch", "sequence", 128]),
664-
("present.0.key", ir.DataType.FLOAT, ["batch", 4, "total_sequence", 256]),
665-
("present.0.value", ir.DataType.FLOAT, ["batch", 4, "total_sequence", 256]),
666-
]
667-
pkg = _GraphlessPkg({"model": _ir_decoder_model(inputs, output_specs)})
668-
669-
arts = write_onnx_genai_config(pkg, str(tmp_path), config=_Cfg())
670-
with open(arts["inference_metadata"]) as handle:
671-
meta = yaml.safe_load(handle)
672-
assert meta["model"]["io"]["kv_inputs"] == [
673-
"past_key_values.0.key",
674-
"past_key_values.0.value",
675-
]

0 commit comments

Comments
 (0)