1818from 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+
21105def _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 )
0 commit comments