Skip to content

Commit 1a6e048

Browse files
justinchubyCopilotJustin Chu
authored
refactor: simplify and deduplicate task classes (#133)
## Summary Addresses all 10 simplification opportunities identified in the task audit. ### Changes **P1 — Shared `_build_decoder`**: Added `build_decoder_from_embeds()` helper to `_cache_utils.py`. Eliminated 5 near-duplicate `_build_decoder` methods from VisionLanguageTask, QwenVLTask, HybridQwenVLTask, SpeechLanguageTask, and Phi4MMMultiModalTask. **P2 — Add `model_roles`**: Added `model_roles` to 10 tasks that were missing it: TTSTask, AdapterTask, VideoDenoisingTask, CodecTask, Seq2SeqTask, SpeechToTextTask, VAETask, QwenImageVAETask, SSMCausalLMTask, SSM2CausalLMTask. Fixes role-detection bugs for AdapterTask (encoder, not decoder) and VideoDenoisingTask. **P3 — `ComponentSpec` (from PR #73)**: Added `ComponentSpec` class to `_base.py` and wired into 12 multi-model tasks. Provides structured validation that required sub-modules exist before graph construction begins. **P4 — SSM deduplication**: Extracted shared `_build_ssm_task()` helper, eliminating ~65 lines of copy-pasted graph wiring between SSMCausalLMTask and SSM2CausalLMTask. **P5 — Remove orphaned `name=`**: Removed dead `name =` class attributes from 7 tasks (DenoisingTask, ControlNetTask, AudioFeatureExtractionTask, AdapterTask, VideoDenoisingTask, VAETask, QwenImageVAETask). **P6 — Fix `ModelPackage(config=)`**: Fixed inconsistent construction in 5 tasks to pass `config=` consistently. **P7/P8 — Shared `_build_embedding`**: Added `build_embedding_from_features()` helper shared by VisionLanguageTask and SpeechLanguageTask. Added `name=` to all `_make_graph()` calls missing it. **P9 — Export `ComponentSpec`**: Added to `__init__.py` `__all__` and import. **P10 — `__pycache__` in `.gitignore`**: Already present, no change needed. ### Test results ``` 2322 passed, 29 skipped in 17.37s ``` Lint: clean (lintrunner) --------- Signed-off-by: Justin Chu <[email protected]> Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot <[email protected]> Co-authored-by: Justin Chu <[email protected]>
1 parent 679251f commit 1a6e048

19 files changed

Lines changed: 1022 additions & 540 deletions

‎src/mobius/tasks/__init__.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
"AudioFeatureExtractionTask",
2424
"CausalLMTask",
2525
"CodecTask",
26+
"ComponentSpec",
2627
"ControlNetTask",
2728
"DenoisingTask",
2829
"FeatureExtractionTask",
@@ -48,13 +49,20 @@
4849
"VAETask",
4950
"VideoDenoisingTask",
5051
"VisionLanguageTask",
52+
"build_decoder_from_embeds",
53+
"build_embedding_from_features",
5154
"get_task",
5255
]
5356

5457
from mobius._constants import OPSET_VERSION
5558
from mobius.tasks._adapter import AdapterTask
5659
from mobius.tasks._audio_feature_extraction import AudioFeatureExtractionTask
57-
from mobius.tasks._base import ModelTask
60+
from mobius.tasks._base import (
61+
ComponentSpec,
62+
ModelTask,
63+
build_decoder_from_embeds,
64+
build_embedding_from_features,
65+
)
5866
from mobius.tasks._causal_lm import (
5967
CausalLMTask,
6068
HybridCausalLMTask,

‎src/mobius/tasks/_adapter.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55

66
from __future__ import annotations
77

8+
from typing import ClassVar
9+
810
import onnx_ir as ir
911

1012
from mobius._model_package import ModelPackage
@@ -14,7 +16,7 @@
1416
class AdapterTask(ModelTask):
1517
"""Build ONNX graph for conditioning adapters (T2I, IP-Adapter)."""
1618

17-
name = "adapter"
19+
model_roles: ClassVar[dict[str, str]] = {"model": "encoder"}
1820

1921
def build(
2022
self,
@@ -50,4 +52,4 @@ def build(
5052
outputs.name = "adapter_output"
5153
graph.outputs.append(outputs)
5254

53-
return ModelPackage({"model": _make_model(graph)})
55+
return ModelPackage({"model": _make_model(graph)}, config=config)

‎src/mobius/tasks/_audio_feature_extraction.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
class AudioFeatureExtractionTask(ModelTask):
2222
"""Build ONNX graph for audio feature extraction (encoder-only)."""
2323

24-
name = "audio-feature-extraction"
2524
model_roles: ClassVar[dict[str, str]] = {"model": "encoder"}
2625

2726
def build(
@@ -43,4 +42,4 @@ def build(
4342
last_hidden_state.name = "last_hidden_state"
4443
graph.outputs.append(last_hidden_state)
4544

46-
return ModelPackage({"model": _make_model(graph)})
45+
return ModelPackage({"model": _make_model(graph)}, config=config)

‎src/mobius/tasks/_base.py‎

Lines changed: 272 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,90 @@
1818
from mobius._model_package import ModelPackage
1919

2020

21+
class ComponentSpec:
22+
"""Declares which sub-module attributes a multi-component task requires.
23+
24+
Used by multi-component tasks (e.g. :class:`VisionLanguageTask`) to
25+
validate that a module exposes the expected sub-module attributes before
26+
building begins. This produces a clear :exc:`TypeError` instead of the
27+
cryptic ``AttributeError`` that would otherwise surface deep inside
28+
``build()``.
29+
30+
Map output model names to the module attribute that builds each component::
31+
32+
ComponentSpec(
33+
decoder="decoder",
34+
vision="vision_encoder",
35+
embedding="embedding",
36+
)
37+
38+
The keys are the names used in the output :class:`ModelPackage`; the
39+
values are the attribute names on the ``nn.Module`` passed to
40+
``task.build()``. Dot notation is supported for nested attributes
41+
(e.g. ``"model.encoder"``).
42+
43+
Args:
44+
**components: Keyword arguments mapping output name → module attribute
45+
name. For example, ``vision="vision_encoder"`` means the task
46+
expects ``module.vision_encoder`` and will store the result as
47+
``package["vision"]``.
48+
"""
49+
50+
def __init__(self, **components: str) -> None:
51+
self._components: dict[str, str] = dict(components)
52+
53+
def validate(self, module: nn.Module, task_name: str) -> None:
54+
"""Check that all required sub-module attributes exist on *module*.
55+
56+
Args:
57+
module: The module passed to ``task.build()``.
58+
task_name: Name of the task class (for the error message).
59+
60+
Raises:
61+
TypeError: If any required attribute is absent from *module*.
62+
"""
63+
64+
def _has_nested(obj: object, dotted: str) -> bool:
65+
for part in dotted.split("."):
66+
if not hasattr(obj, part):
67+
return False
68+
obj = getattr(obj, part)
69+
return True
70+
71+
missing = [
72+
(output_name, attr_name)
73+
for output_name, attr_name in self._components.items()
74+
if not _has_nested(module, attr_name)
75+
]
76+
if not missing:
77+
return
78+
lines = "\n".join(
79+
f" '{output_name}' component expects module.{attr_name}"
80+
for output_name, attr_name in missing
81+
)
82+
raise TypeError(
83+
f"{task_name} requires sub-module attribute(s) that are missing "
84+
f"from {type(module).__name__}:\n{lines}\n"
85+
f"Ensure each attribute is assigned in the module's __init__()."
86+
)
87+
88+
def items(self):
89+
"""Iterate over ``(output_name, attribute_name)`` pairs."""
90+
return self._components.items()
91+
92+
def keys(self):
93+
"""Return the output model names declared by this spec."""
94+
return self._components.keys()
95+
96+
def __contains__(self, item: str) -> bool:
97+
"""Return ``True`` if *item* is a declared output model name."""
98+
return item in self._components
99+
100+
def __repr__(self) -> str:
101+
parts = ", ".join(f"{k}={v!r}" for k, v in self._components.items())
102+
return f"ComponentSpec({parts})"
103+
104+
21105
def _make_graph(
22106
inputs: list[ir.Value],
23107
name: str = "main_graph",
@@ -50,14 +134,41 @@ class ModelTask(ABC):
50134
51135
Subclass this to support new model tasks (e.g. feature extraction,
52136
sequence classification). Each task defines its own graph I/O contract.
137+
138+
Multi-component tasks should declare a class-level :class:`ComponentSpec`
139+
and call :meth:`_validate_components` at the start of ``build()``::
140+
141+
class MyMultiModelTask(ModelTask):
142+
components = ComponentSpec(decoder="decoder", vision="vision_encoder")
143+
144+
def build(self, module, config):
145+
self._validate_components(module)
146+
...
53147
"""
54148

55149
#: Maps package key → optimization role for each model produced by this task.
56150
#: The role controls which fusion passes run (e.g. only ``"decoder"`` gets
57151
#: GQA fusion). Override in subclasses that produce non-decoder outputs.
58-
#: Unrecognised keys default to ``"decoder"``.
152+
#: Unrecognised keys fall back to ``_MODEL_ROLE_MAP`` in ``_builder.py``,
153+
#: then default to ``"decoder"``.
59154
model_roles: ClassVar[dict[str, str]] = {"model": "decoder"}
60155

156+
#: Optional component spec for multi-component tasks. When set,
157+
#: :meth:`_validate_components` checks that all declared attributes
158+
#: exist on the module before building begins.
159+
components: ClassVar[ComponentSpec | None] = None
160+
161+
def _validate_components(self, module: nn.Module) -> None:
162+
"""Validate that *module* exposes all attributes declared in :attr:`components`.
163+
164+
Call at the start of :meth:`build` in multi-component tasks.
165+
166+
Raises:
167+
TypeError: If any required sub-module attribute is missing.
168+
"""
169+
if self.components is not None:
170+
self.components.validate(module, type(self).__name__)
171+
61172
@abstractmethod
62173
def build(
63174
self,
@@ -78,3 +189,163 @@ def build(
78189
A :class:`ModelPackage` containing the built model(s).
79190
"""
80191
...
192+
193+
194+
# ---------------------------------------------------------------------------
195+
# Shared graph-builder helpers for multi-component tasks
196+
# ---------------------------------------------------------------------------
197+
198+
199+
def build_decoder_from_embeds(
200+
decoder,
201+
config: BaseModelConfig,
202+
*,
203+
mrope: bool = False,
204+
hybrid: bool = False,
205+
) -> ir.Model:
206+
"""Build an ``inputs_embeds → logits + KV cache`` decoder ONNX graph.
207+
208+
This is the shared implementation for the ``_build_decoder`` method that
209+
is common to :class:`VisionLanguageTask`, :class:`QwenVLTask`,
210+
:class:`HybridQwenVLTask`, :class:`SpeechLanguageTask`, and
211+
:class:`Phi4MMMultiModalTask`.
212+
213+
Args:
214+
decoder: The decoder sub-module to invoke.
215+
config: Architecture configuration.
216+
mrope: If ``True``, uses 3D MRoPE position_ids
217+
``[3, batch, seq_len]`` instead of the standard
218+
``[batch, seq_len]``.
219+
hybrid: If ``True``, uses hybrid KV + DeltaNet cache inputs/outputs
220+
(for Qwen3.5-VL and similar). Requires ``config.layer_types``.
221+
222+
Returns:
223+
A built :class:`ir.Model` for the decoder.
224+
"""
225+
# Import here rather than at module top to keep _base.py focused on base
226+
# class definitions. _cache_utils does NOT import from _base.py, so there
227+
# is no circular dependency — this is purely a namespace-clarity choice.
228+
from mobius.tasks._cache_utils import (
229+
_make_hybrid_cache_inputs,
230+
_make_kv_cache_inputs,
231+
_register_hybrid_cache_outputs,
232+
_register_kv_cache_outputs,
233+
_register_linear_attention_functions,
234+
)
235+
236+
batch = ir.SymbolicDim("batch")
237+
seq_len = ir.SymbolicDim("sequence_len")
238+
past_seq_len = ir.SymbolicDim("past_sequence_len")
239+
240+
inputs_embeds = ir.Value(
241+
name="inputs_embeds",
242+
shape=ir.Shape([batch, seq_len, config.hidden_size]),
243+
type=ir.TensorType(config.dtype),
244+
)
245+
attention_mask = ir.Value(
246+
name="attention_mask",
247+
shape=ir.Shape([batch, "past_seq_len + seq_len"]),
248+
type=ir.TensorType(ir.DataType.INT64),
249+
)
250+
# MRoPE: 3D position IDs (temporal, height, width) — shape [3, batch, seq_len]
251+
# Standard: shape [batch, seq_len]
252+
position_ids = ir.Value(
253+
name="position_ids",
254+
shape=ir.Shape([3, batch, seq_len] if mrope else [batch, seq_len]),
255+
type=ir.TensorType(ir.DataType.INT64),
256+
)
257+
258+
graph_inputs = [inputs_embeds, attention_mask, position_ids]
259+
260+
if hybrid:
261+
cache_inputs, past_key_values = _make_hybrid_cache_inputs(
262+
config,
263+
config.dtype,
264+
batch,
265+
past_seq_len,
266+
)
267+
else:
268+
cache_inputs, past_key_values = _make_kv_cache_inputs(
269+
config.num_hidden_layers,
270+
config.num_key_value_heads,
271+
config.head_dim,
272+
config.dtype,
273+
batch,
274+
past_seq_len,
275+
)
276+
graph_inputs.extend(cache_inputs)
277+
278+
graph, builder = _make_graph(graph_inputs)
279+
logits, present_key_values = decoder(
280+
builder.op,
281+
inputs_embeds=inputs_embeds,
282+
attention_mask=attention_mask,
283+
position_ids=position_ids,
284+
past_key_values=past_key_values,
285+
)
286+
287+
logits.name = "logits"
288+
graph.outputs.append(logits)
289+
290+
if hybrid:
291+
_register_hybrid_cache_outputs(
292+
graph,
293+
present_key_values,
294+
config.layer_types or [],
295+
)
296+
model = _make_model(graph)
297+
_register_linear_attention_functions(model, config)
298+
return model
299+
else:
300+
_register_kv_cache_outputs(graph, present_key_values)
301+
return _make_model(graph)
302+
303+
304+
def build_embedding_from_features(
305+
embedding,
306+
config: BaseModelConfig,
307+
*,
308+
feature_name: str,
309+
feature_dim: int,
310+
) -> ir.Model:
311+
"""Build an ``input_ids + features → inputs_embeds`` embedding ONNX graph.
312+
313+
This is the shared implementation for ``_build_embedding`` in
314+
:class:`VisionLanguageTask` (image features) and
315+
:class:`SpeechLanguageTask` (audio features).
316+
317+
Args:
318+
embedding: The embedding sub-module to invoke.
319+
config: Architecture configuration.
320+
feature_name: Name of the second input (e.g. ``"image_features"`` or
321+
``"audio_features"``).
322+
feature_dim: Feature dimension for the second input's last axis.
323+
324+
Returns:
325+
A built :class:`ir.Model` for the embedding model.
326+
"""
327+
batch = ir.SymbolicDim("batch")
328+
seq_len = ir.SymbolicDim("sequence_len")
329+
num_feature_tokens = ir.SymbolicDim("num_feature_tokens")
330+
331+
input_ids = ir.Value(
332+
name="input_ids",
333+
shape=ir.Shape([batch, seq_len]),
334+
type=ir.TensorType(ir.DataType.INT64),
335+
)
336+
features = ir.Value(
337+
name=feature_name,
338+
shape=ir.Shape([num_feature_tokens, feature_dim]),
339+
type=ir.TensorType(config.dtype),
340+
)
341+
342+
graph, builder = _make_graph([input_ids, features], name="embedding")
343+
inputs_embeds = embedding(
344+
builder.op,
345+
input_ids=input_ids,
346+
**{feature_name: features},
347+
)
348+
349+
inputs_embeds.name = "inputs_embeds"
350+
graph.outputs.append(inputs_embeds)
351+
return _make_model(graph)

‎src/mobius/tasks/_cache_utils.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
# Copyright (c) Microsoft Corporation.
22
# Licensed under the MIT License.
33

4-
"""KV cache and linear attention utility functions for task graph construction."""
4+
"""KV cache and linear attention utility functions for task graph construction.
5+
6+
Provides helpers for wiring KV cache state tensors (inputs/outputs) into
7+
ONNX task graphs, and for registering hybrid (DeltaNet) linear-attention
8+
function bodies. Only cache-related utilities live here; higher-level
9+
multi-component graph builders live in :mod:`mobius.tasks._base`.
10+
"""
511

612
from __future__ import annotations
713

0 commit comments

Comments
 (0)