Skip to content

Commit 3ca0d86

Browse files
justinchubyCopilot
andcommitted
Fix workflow batching declarations
Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot <[email protected]> Copilot-Session: d60eb808-7cc6-4abc-b48d-2a6dd3841624
1 parent c49d422 commit 3ca0d86

14 files changed

Lines changed: 640 additions & 32 deletions

File tree

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

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1395,16 +1395,19 @@ def validate_executable_closure(pkg: Any, metadata: dict[str, Any]) -> None:
13951395
)
13961396

13971397

1398-
#: Symbolic leading dimension Mobius emits for every batched ONNX port. A port
1399-
#: that opens with it holds exactly one entry per in-flight request, which is
1400-
#: the structural fact a runtime needs to permute or drop rows.
1398+
#: Symbolic dimension Mobius emits for every request-aligned ONNX port.
14011399
REQUEST_AXIS_SYMBOL = "batch"
14021400

14031401

14041402
def request_batch_layout(shape: list[Any] | None) -> dict[str, Any] | None:
14051403
"""Return the request-aligned batch layout implied by a port's shape."""
1406-
if shape and shape[0] == REQUEST_AXIS_SYMBOL:
1407-
return {"kind": "request_aligned", "axis": 0}
1404+
axes = [
1405+
axis
1406+
for axis, dimension in enumerate(shape or [])
1407+
if str(dimension) in _BATCH_DIMENSION_NAMES
1408+
]
1409+
if len(axes) == 1:
1410+
return {"kind": "request_aligned", "axis": axes[0]}
14081411
return None
14091412

14101413

@@ -1519,11 +1522,11 @@ def tensor_contract(value: Any) -> dict[str, Any]:
15191522

15201523

15211524
def declare_request_alignment(workflow: dict[str, Any]) -> None:
1522-
"""Stamp the request-aligned row axis onto every batch-leading contract.
1525+
"""Stamp the request axis named by exactly one batch symbol.
15231526
15241527
The runtime compacts finished rows out of a batch by applying one row
1525-
permutation to every request-aligned tensor. A contract whose leading axis
1526-
is the batch symbol but that does not say so is unpermutable, so state,
1528+
permutation to every request-aligned tensor. A contract whose batch axis
1529+
does not say so is unpermutable, so state,
15271530
component ports, and outputs would silently drift apart after the first
15281531
eviction. Deriving the declaration from the admitted graph's own batch
15291532
symbol keeps alignment a property of the model interface rather than an
@@ -1534,8 +1537,8 @@ def stamp(contract: Any) -> None:
15341537
if not isinstance(contract, dict) or "batch_layout" in contract:
15351538
return
15361539
shape = contract.get("shape") or []
1537-
if shape and str(shape[0]) in _BATCH_DIMENSION_NAMES:
1538-
contract["batch_layout"] = {"kind": "request_aligned", "axis": 0}
1540+
if layout := request_batch_layout(shape):
1541+
contract["batch_layout"] = layout
15391542

15401543
for section in ("inputs", "outputs", "state"):
15411544
for declaration in (workflow.get(section) or {}).values():

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
load_diffusers_scheduler_config,
4040
load_diffusers_vae_scaling_factor,
4141
published_value_references,
42+
request_batch_layout,
4243
validate_executable_closure,
4344
write_diffusion_pipeline_metadata,
4445
write_mtp_speculator_metadata,
@@ -49,6 +50,19 @@
4950
)
5051

5152

53+
def test_request_batch_layout_follows_the_unique_batch_symbol():
54+
assert request_batch_layout(["batch", "sequence"]) == {
55+
"kind": "request_aligned",
56+
"axis": 0,
57+
}
58+
assert request_batch_layout([3, "batch", "sequence"]) == {
59+
"kind": "request_aligned",
60+
"axis": 1,
61+
}
62+
assert request_batch_layout(["batch", "batch"]) is None
63+
assert request_batch_layout([3, "sequence"]) is None
64+
65+
5266
def test_ort_extensions_processor_config_supplies_structural_values(tmp_path):
5367
(tmp_path / "processor_config.json").write_text(
5468
json.dumps(

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

Lines changed: 172 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,157 @@ def _component(
239239
return declaration
240240

241241

242+
def _declare_batch_capacities(
243+
metadata: dict[str, Any],
244+
component_names: Sequence[str],
245+
) -> None:
246+
"""Assert independent-row execution for explicitly audited components.
247+
248+
Presence is the semantic permission; it is never inferred from a dynamic
249+
leading axis. For synthesized policy graphs, whose port contracts are part
250+
of the workflow dataflow, every non-request symbolic input extent is also
251+
declared uniform. Exported model graphs remain authoritative for their own
252+
port geometry and therefore contribute an empty capacity declaration.
253+
"""
254+
workflow = metadata["pipeline"]["workflow"]
255+
components = workflow["components"]
256+
declared = False
257+
for name in component_names:
258+
component = components.get(name)
259+
if component is None:
260+
continue
261+
uniform_dimensions: list[str] = []
262+
for contract in component.get("ports", {}).get("inputs", {}).values():
263+
layout = contract.get("batch_layout", {})
264+
request_axis = (
265+
layout.get("axis")
266+
if layout.get("kind") in {"request_aligned", "request_expanded"}
267+
else None
268+
)
269+
for axis, dimension in enumerate(contract.get("shape") or []):
270+
if (
271+
axis != request_axis
272+
and isinstance(dimension, str)
273+
and dimension not in uniform_dimensions
274+
):
275+
uniform_dimensions.append(dimension)
276+
capacity: dict[str, Any] = {}
277+
if uniform_dimensions:
278+
capacity["uniform_dimensions"] = uniform_dimensions
279+
component["batch_capacity"] = capacity
280+
declared = True
281+
if declared:
282+
metadata["schema_version"] = "v1.1"
283+
284+
285+
def _preserve_request_expansion(
286+
metadata: dict[str, Any],
287+
component_names: Sequence[str],
288+
*,
289+
factor: int,
290+
) -> None:
291+
"""Keep a fixed internal row expansion distinct from request batching."""
292+
workflow = metadata["pipeline"]["workflow"]
293+
for name in component_names:
294+
component = workflow["components"][name]
295+
for side in ("inputs", "outputs"):
296+
for contract in component.get("ports", {}).get(side, {}).values():
297+
shape = contract.get("shape") or []
298+
if shape and shape[0] == "batch":
299+
contract["batch_layout"] = {
300+
"kind": "request_expanded",
301+
"axis": 0,
302+
"factor": factor,
303+
}
304+
305+
306+
_DECODER_BATCH_COMPONENTS = (
307+
"model",
308+
"token_sampler",
309+
"termination",
310+
"token_state_update",
311+
"last_token_logits",
312+
"decoder_state_initializer",
313+
"decoder_step_update",
314+
"cache_length_update",
315+
"termination_batch_initializer",
316+
"token_to_slot",
317+
"generated_length_update",
318+
"state_init",
319+
"step_update",
320+
"next_token",
321+
"loop_continue",
322+
)
323+
324+
_DIFFUSION_BATCH_COMPONENTS = (
325+
"text_encoder",
326+
"denoiser",
327+
"vae_decoder",
328+
"image_output_clamp",
329+
"solver_step",
330+
"continue_predicate",
331+
"model_input_scale",
332+
"diffusion_schedule",
333+
"diffusion_timesteps",
334+
"schedule_lookup",
335+
"tensor_scale",
336+
"initial_state_scale",
337+
"decoder_input_scale",
338+
"history_initializer",
339+
"guidance_combine",
340+
"latent_row_shape",
341+
"latent_noise",
342+
)
343+
344+
_TTS_BATCH_COMPONENTS = (
345+
"talker",
346+
"code_predictor",
347+
"embedding",
348+
"talker_step_embedder",
349+
"talker_prefill_embedder",
350+
"code_predictor_prefill",
351+
"code_predictor_step_embedder",
352+
"code_predictor_indices",
353+
"talker_text_step",
354+
"codec",
355+
"last_token_logits",
356+
"setup_talker_sampler",
357+
"setup_predictor_sampler",
358+
"talker_sampler",
359+
"predictor_prefill_sampler",
360+
"predictor_body_sampler",
361+
"continue_predicate",
362+
"tts_state_initializer",
363+
"token_to_slot",
364+
"code_frame_update",
365+
"code_history_append",
366+
"cache_length_update",
367+
"talker_state_initializer",
368+
"predictor_state_initializer",
369+
"talker_step_update",
370+
"predictor_step_update",
371+
"codec_layout",
372+
)
373+
374+
_VIDEO_BATCH_COMPONENTS = (
375+
"transformer",
376+
"vae_decoder",
377+
"model_input",
378+
"solver_step",
379+
"continue_predicate",
380+
"video_latent_init",
381+
"schedule_history_append",
382+
"video_latent_permute",
383+
"video_latent_unscale",
384+
"video_decode_chunks",
385+
"video_decode_chunk",
386+
"video_conv_cache_init",
387+
"diffusion_schedule",
388+
"diffusion_timesteps",
389+
"schedule_lookup",
390+
)
391+
392+
242393
def _grammar_adapter_component(action: str) -> dict[str, Any]:
243394
"""Declare one action of the versioned grammar-guidance adapter ABI."""
244395

@@ -2013,6 +2164,14 @@ def invoke_model(
20132164
"pipeline": {"workflow": _publish_workflow_v1(workflow)},
20142165
}
20152166
add_policy_components_to_workflow(metadata, pkg)
2167+
expansion = metadata["pipeline"]["workflow"]["inputs"]["request.prompt_tokens"][
2168+
"contract"
2169+
]["batch_layout"]["factor"]
2170+
_preserve_request_expansion(
2171+
metadata,
2172+
("global_initializer", "global_step_update"),
2173+
factor=expansion,
2174+
)
20162175
return metadata
20172176

20182177

@@ -3794,7 +3953,9 @@ def build_tts_workflow_metadata(pkg: Any, config: Any) -> dict[str, Any]:
37943953
"talker_text_step",
37953954
}
37963955
if real_transition_components <= set(pkg.keys()):
3797-
return _build_real_tts_workflow_metadata(pkg, config)
3956+
metadata = _build_real_tts_workflow_metadata(pkg, config)
3957+
_declare_batch_capacities(metadata, _TTS_BATCH_COMPONENTS)
3958+
return metadata
37983959
required = {
37993960
"talker",
38003961
"code_predictor",
@@ -4243,6 +4404,7 @@ def bind_outputs(values: Any, bound: dict[str, str], prefix: str) -> dict[str, s
42434404
"pipeline": {"workflow": _publish_workflow_v1(workflow)},
42444405
}
42454406
add_policy_components_to_workflow(metadata, pkg)
4407+
_declare_batch_capacities(metadata, _TTS_BATCH_COMPONENTS)
42464408
return metadata
42474409

42484410

@@ -4838,6 +5000,7 @@ def denoiser_call(conditioning: str | None, estimate: str) -> dict[str, Any]:
48385000
"value": "denoiser.estimate",
48395001
"output": "noise_estimate",
48405002
"mode": "append",
5003+
"axis": 3,
48415004
"effect_name": "emit",
48425005
"effect": _effect("emit.0", "emit.1"),
48435006
},
@@ -4846,6 +5009,7 @@ def denoiser_call(conditioning: str | None, estimate: str) -> dict[str, Any]:
48465009
"value": "latent.body",
48475010
"output": "latent_trajectory",
48485011
"mode": "append",
5012+
"axis": 3,
48495013
"effect_name": "emit",
48505014
"effect": _effect("emit.1", "emit.2"),
48515015
},
@@ -4951,6 +5115,7 @@ def denoiser_call(conditioning: str | None, estimate: str) -> dict[str, Any]:
49515115
"pipeline": {"workflow": _publish_workflow_v1(workflow)},
49525116
}
49535117
add_policy_components_to_workflow(metadata, pkg)
5118+
_declare_batch_capacities(metadata, _DIFFUSION_BATCH_COMPONENTS)
49545119
return metadata
49555120

49565121

@@ -6063,6 +6228,7 @@ def build_video_diffusion_workflow_metadata(
60636228
"pipeline": {"workflow": _publish_workflow_v1(workflow)},
60646229
}
60656230
add_policy_components_to_workflow(metadata, pkg)
6231+
_declare_batch_capacities(metadata, _VIDEO_BATCH_COMPONENTS)
60666232
return metadata
60676233

60686234

@@ -8071,7 +8237,11 @@ def build_decoder_workflow_metadata(
80718237
"""Build the exact workflow-policy contract for an autoregressive decoder."""
80728238
if len(pkg) != 1:
80738239
raise ValueError("decoder workflow requires exactly one neural component")
8074-
return _build_autoregressive_workflow_metadata(pkg, config, sampler=sampler, source=source)
8240+
metadata = _build_autoregressive_workflow_metadata(
8241+
pkg, config, sampler=sampler, source=source
8242+
)
8243+
_declare_batch_capacities(metadata, _DECODER_BATCH_COMPONENTS)
8244+
return metadata
80758245

80768246

80778247
def _build_autoregressive_workflow_metadata(

0 commit comments

Comments
 (0)