Skip to content

Commit 54be48a

Browse files
justinchubyCopilot
andauthored
Emit Gemma4 optional audio modality contract (#419)
## Summary - declare Gemma4 audio optionality on exported ONNX graph structure and emit io.optional_inputs.audio_features with the frozen audio presence key and zero fallback - emit phases.audio_encoder.when_present: audio while keeping the strategy stage run_on: prompt_only - adapt E2B audio features inside the exported audio encoder graph by flattening batch/time and applying the downsampled validity mask with ONNX Compress - route the resulting rank-2 audio output directly to the rank-2 embedding input; keep gemma4_unified declarations consistent ## Contract optional_inputs: audio_features: presence: audio absent: kind: zeros shape: [0, 1536] phases: audio_encoder: run_on: prompt_only when_present: audio ## Validation - ruff check on changed files - ruff format --check on changed files - python3 -m pytest src/mobius/integrations/onnx_genai/inference_metadata_test.py -q (40 passed) - targeted Gemma4 graph/adapter tests (4 passed) - verified an E2B-width export emits a rank-2, dtype-compatible audio_encoder.audio_features to embedding.audio_features edge WP-B4 optional-modality exporter contract. --------- Co-authored-by: Copilot <[email protected]>
1 parent 640c1cb commit 54be48a

5 files changed

Lines changed: 225 additions & 16 deletions

File tree

‎src/mobius/_pipeline_contract.py‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
"""Declarations carried by exported ONNX graphs for pipeline metadata emission."""
5+
6+
from __future__ import annotations
7+
8+
import json
9+
from collections.abc import Sequence
10+
from typing import Any
11+
12+
import onnx_ir as ir
13+
14+
_COMPONENT_PRESENCE = "mobius.pipeline.when_present"
15+
_OPTIONAL_INPUT_PRESENCE = "mobius.pipeline.optional_input.presence"
16+
_OPTIONAL_INPUT_ABSENT_SHAPE = "mobius.pipeline.optional_input.absent_shape"
17+
18+
19+
def declare_component_presence(graph: ir.Graph, presence: str) -> None:
20+
"""Declare the opaque presence key required to execute a component graph."""
21+
if not presence:
22+
raise ValueError("Component presence key must be non-empty")
23+
graph.metadata_props[_COMPONENT_PRESENCE] = presence
24+
25+
26+
def component_presence(graph: Any) -> str | None:
27+
"""Return a component graph's declared presence key, if any."""
28+
presence = getattr(graph, "metadata_props", {}).get(_COMPONENT_PRESENCE)
29+
return presence or None
30+
31+
32+
def declare_optional_input(
33+
value: ir.Value,
34+
*,
35+
presence: str,
36+
absent_shape: Sequence[int | str],
37+
) -> None:
38+
"""Declare a zero fallback for an optional ONNX graph input."""
39+
if not presence:
40+
raise ValueError("Optional-input presence key must be non-empty")
41+
shape = list(absent_shape)
42+
if not shape or any(isinstance(dim, int) and dim < 0 for dim in shape):
43+
raise ValueError("Optional-input absent shape must contain non-negative dimensions")
44+
value.metadata_props[_OPTIONAL_INPUT_PRESENCE] = presence
45+
value.metadata_props[_OPTIONAL_INPUT_ABSENT_SHAPE] = json.dumps(shape)
46+
47+
48+
def optional_input_contract(value: Any) -> dict[str, Any] | None:
49+
"""Return the executable optional-input contract declared on a graph input."""
50+
metadata = getattr(value, "metadata_props", {})
51+
presence = metadata.get(_OPTIONAL_INPUT_PRESENCE)
52+
absent_shape = metadata.get(_OPTIONAL_INPUT_ABSENT_SHAPE)
53+
if presence is None and absent_shape is None:
54+
return None
55+
if not presence or absent_shape is None:
56+
raise ValueError(
57+
f"ONNX input {value.name!r} has an incomplete optional-input declaration"
58+
)
59+
try:
60+
shape = json.loads(absent_shape)
61+
except (TypeError, json.JSONDecodeError) as error:
62+
raise ValueError(
63+
f"ONNX input {value.name!r} has an invalid optional-input absent shape"
64+
) from error
65+
if not isinstance(shape, list) or not shape:
66+
raise ValueError(
67+
f"ONNX input {value.name!r} optional-input absent shape must be a non-empty list"
68+
)
69+
return {
70+
"presence": presence,
71+
"absent": {
72+
"kind": "zeros",
73+
"shape": shape,
74+
},
75+
}

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@
4242

4343
import yaml
4444

45+
from mobius._pipeline_contract import component_presence, optional_input_contract
46+
4547
_LOGGER = logging.getLogger(__name__)
4648

4749
_RUNTIME_ASSET_NAMES = (
@@ -1257,9 +1259,18 @@ def build_native_vlm_package_metadata(
12571259
"type": role,
12581260
"io": io,
12591261
}
1262+
optional_inputs = {
1263+
value.name: contract
1264+
for value in pkg[name].graph.inputs
1265+
if (contract := optional_input_contract(value)) is not None
1266+
}
1267+
if optional_inputs:
1268+
io["optional_inputs"] = optional_inputs
12601269
if name == decoder_name:
12611270
models[name]["tokenizer"] = "tokenizer.json"
12621271
phases[name] = {"run_on": run_on}
1272+
if presence := component_presence(pkg[name].graph):
1273+
phases[name]["when_present"] = presence
12631274

12641275
image_endpoints = {
12651276
output["name"] for output in preprocessing_outputs if not output.get("optional", False)

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

Lines changed: 44 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@
1818
import yaml
1919

2020
from mobius._model_package import ModelPackage
21+
from mobius._pipeline_contract import (
22+
declare_component_presence,
23+
declare_optional_input,
24+
)
2125
from mobius.integrations.onnx_genai.inference_metadata import (
2226
SchedulerConfig,
2327
build_diffusion_pipeline_metadata,
@@ -118,13 +122,21 @@ def _embedding_model(
118122
outputs: list[tuple[str, ir.DataType, list[int | str]]],
119123
*,
120124
include_audio: bool = False,
125+
optional_audio: bool = False,
121126
) -> ir.Model:
122127
inputs = [
123128
_value("input_ids", ir.DataType.INT64, ["batch", "sequence"]),
124129
_value("image_features", ir.DataType.FLOAT, ["image_tokens", 64]),
125130
]
126131
if include_audio:
127-
inputs.append(_value("audio_features", ir.DataType.FLOAT, ["audio_tokens", 64]))
132+
audio_features = _value("audio_features", ir.DataType.FLOAT, ["audio_tokens", 64])
133+
if optional_audio:
134+
declare_optional_input(
135+
audio_features,
136+
presence="audio",
137+
absent_shape=[0, 64],
138+
)
139+
inputs.append(audio_features)
128140
return _model("embedding", inputs, outputs)
129141

130142

@@ -348,6 +360,7 @@ def test_gemma4_routes_all_embedding_outputs(self, tmp_path):
348360
),
349361
],
350362
include_audio=True,
363+
optional_audio=True,
351364
),
352365
"audio_encoder": _model(
353366
"audio_encoder",
@@ -367,7 +380,7 @@ def test_gemma4_routes_all_embedding_outputs(self, tmp_path):
367380
(
368381
"audio_features",
369382
ir.DataType.FLOAT,
370-
["batch", "audio_sequence", 64],
383+
["audio_tokens", 64],
371384
),
372385
(
373386
"audio_features_mask",
@@ -379,6 +392,7 @@ def test_gemma4_routes_all_embedding_outputs(self, tmp_path):
379392
},
380393
config=config,
381394
)
395+
declare_component_presence(package["audio_encoder"].graph, "audio")
382396

383397
source = tmp_path / "gemma"
384398
source.mkdir()
@@ -402,6 +416,7 @@ def test_gemma4_routes_all_embedding_outputs(self, tmp_path):
402416
metadata = build_native_vlm_package_metadata(
403417
package, config=config, source=str(source)
404418
)
419+
emitted_yaml = yaml.safe_load(yaml.safe_dump(metadata, sort_keys=False))
405420
validate_executable_closure(package, metadata)
406421
self._validate(metadata)
407422
_assert_all_graph_ports_declared(package, metadata)
@@ -420,13 +435,38 @@ def test_gemma4_routes_all_embedding_outputs(self, tmp_path):
420435
"rank": 3,
421436
"device_transfer": False,
422437
} in flow
423-
assert not any(edge["from"] == "audio_encoder.audio_features" for edge in flow)
438+
assert {
439+
"from": "audio_encoder.audio_features",
440+
"to": "embedding.audio_features",
441+
"dtype": "fp32",
442+
"rank": 2,
443+
"device_transfer": False,
444+
} in flow
424445
embedding_audio = next(
425446
port
426447
for port in metadata["pipeline"]["models"]["embedding"]["io"]["inputs"]
427448
if port["name"] == "audio_features"
428449
)
429-
assert embedding_audio["source"] == {"kind": "external", "input": "request"}
450+
assert embedding_audio["source"] == {
451+
"kind": "dataflow",
452+
"from": "audio_encoder.audio_features",
453+
}
454+
assert emitted_yaml["pipeline"]["models"]["embedding"]["io"]["optional_inputs"] == {
455+
"audio_features": {
456+
"presence": "audio",
457+
"absent": {"kind": "zeros", "shape": [0, 64]},
458+
}
459+
}
460+
assert emitted_yaml["pipeline"]["phases"]["audio_encoder"] == {
461+
"run_on": "prompt_only",
462+
"when_present": "audio",
463+
}
464+
audio_stage = next(
465+
stage
466+
for stage in metadata["pipeline"]["strategy"]["stages"]
467+
if stage["strategy"].get("model") == "audio_encoder"
468+
)
469+
assert audio_stage["run_on"] == "prompt_only"
430470
assert metadata["pipeline"]["phases"]["embedding"] == {"run_on": "every_step"}
431471
embedding_stage = next(
432472
stage

‎src/mobius/tasks/_gemma4.py‎

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,10 @@
2727
from mobius._build_context import ep_capabilities
2828
from mobius._configs import Gemma4Config
2929
from mobius._model_package import ModelPackage
30+
from mobius._pipeline_contract import (
31+
declare_component_presence,
32+
declare_optional_input,
33+
)
3034
from mobius.tasks._base import (
3135
ModelTask,
3236
_make_graph,
@@ -192,9 +196,8 @@ class Gemma4Task(ModelTask):
192196
(``True``) vs padding (``False``), always contiguous
193197
(right-padded). The mask is downsampled through two conv layers
194198
(stride 2 each → ``T//4``) and used to zero out padding in
195-
Conformer attention. The downsampled mask is returned as
196-
``audio_features_mask [B, T//4]`` so callers can strip padding
197-
rows before scattering into text embeddings.
199+
Conformer attention. The export strips padding inside the ONNX
200+
graph and returns ``audio_features [num_valid, hidden_size]``.
198201
199202
**Decoder** — standard ``attention_mask`` for KV cache padding.
200203
``attention_mask [B, past+current]`` is a 1/0 int mask indicating
@@ -380,10 +383,10 @@ def _build_audio(
380383
positions in Conformer attention.
381384
382385
Outputs:
383-
- ``audio_features [batch, time//4, text_hidden_size]``: encoded tokens
386+
- ``audio_features [num_valid, text_hidden_size]``: encoded tokens with
387+
padded rows removed in batch-major order
384388
- ``audio_features_mask [batch, time//4]``: BOOL downsampled mask
385-
indicating which output positions are valid (for stripping
386-
padding rows before scattering into text embeddings)
389+
retained for diagnostics and backwards compatibility
387390
"""
388391
batch = ir.SymbolicDim("batch")
389392
time = ir.SymbolicDim("time")
@@ -408,11 +411,25 @@ def _build_audio(
408411
input_features,
409412
input_features_mask=input_features_mask,
410413
)
414+
if downsampled_mask is None:
415+
raise ValueError("Gemma4 audio encoder must return a downsampled validity mask")
416+
flattened_features = op.Reshape(
417+
audio_features,
418+
op.Constant(value_ints=[-1, config.hidden_size]),
419+
)
420+
flattened_mask = op.Reshape(
421+
downsampled_mask,
422+
op.Constant(value_ints=[-1]),
423+
)
424+
flattened_features_f32 = op.Cast(flattened_features, to=ir.DataType.FLOAT)
425+
audio_features = op.CastLike(
426+
op.Compress(flattened_features_f32, flattened_mask, axis=0),
427+
flattened_features,
428+
)
411429
builder.add_output(audio_features, "audio_features")
430+
builder.add_output(downsampled_mask, "audio_features_mask")
412431

413-
if downsampled_mask is not None:
414-
builder.add_output(downsampled_mask, "audio_features_mask")
415-
432+
declare_component_presence(graph, "audio")
416433
return _make_model(graph)
417434

418435
def _build_embedding(
@@ -448,6 +465,11 @@ def _build_embedding(
448465
dtype=config.dtype,
449466
shape=[num_audio_tokens, config.hidden_size],
450467
)
468+
declare_optional_input(
469+
audio_features_val,
470+
presence="audio",
471+
absent_shape=[0, config.hidden_size],
472+
)
451473

452474
result = embedding(
453475
op,
@@ -568,4 +590,5 @@ def _build_audio(
568590
input_features_mask=input_features_mask,
569591
)
570592
builder.add_output(audio_features, "audio_features")
593+
declare_component_presence(graph, "audio")
571594
return _make_model(graph)

0 commit comments

Comments
 (0)