Repository navigation
Add ComponentSpec for multi-model task validation - #73
justinchuby wants to merge 5 commits into
Conversation
Performance Comparison
|
🏗️ Architecture Diff
No architecture changes detected. ✅ Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed) |
There was a problem hiding this comment.
Pull request overview
Introduces a declarative ComponentSpec to let multi-model tasks validate required sub-module attributes up front, improving failure modes during task build() for composite modules (vision-language, speech-language, Phi4MM multimodal).
Changes:
- Added
ComponentSpecplusModelTask.componentsand_validate_components()to centralize multi-component module validation. - Updated multi-model tasks to declare required sub-modules via
components = ComponentSpec(...)and call_validate_components()at the start ofbuild(). - Added/updated task tests to cover
ComponentSpecbehavior and error messaging; exportedComponentSpecfrommobius.tasks.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
src/mobius/tasks/_base.py |
Adds ComponentSpec and a ModelTask helper to validate required module attributes early. |
src/mobius/tasks/_vision_language_3model.py |
Declares required components for VisionLanguageTask and validates before building sub-model graphs. |
src/mobius/tasks/_speech_language.py |
Declares required components for SpeechLanguageTask and validates before building sub-model graphs. |
src/mobius/tasks/_phi4mm_multimodal.py |
Declares required components for Phi4MMMultiModalTask and validates before building sub-model graphs. |
src/mobius/tasks/__init__.py |
Exports ComponentSpec as part of the public tasks API. |
src/mobius/tasks/_task_test.py |
Adds ComponentSpec tests and integrates validation behavior checks into task tests. |
| missing = [ | ||
| (output_name, attr_name) | ||
| for output_name, attr_name in self._components.items() | ||
| if not hasattr(module, attr_name) | ||
| ] | ||
| if not missing: | ||
| return | ||
| lines = "\n".join( | ||
| f" '{output_name}' component expects module.{attr_name}" | ||
| for output_name, attr_name in missing | ||
| ) | ||
| raise TypeError( | ||
| f"{task_name} requires sub-module attribute(s) that are missing " | ||
| f"from {type(module).__name__}:\n{lines}\n" | ||
| f"Ensure each attribute is assigned in the module's __init__()." | ||
| ) |
There was a problem hiding this comment.
ComponentSpec.validate() currently only checks hasattr(module, attr_name). If the attribute exists but is None or not an onnxscript.nn.Module, validation will pass and the task will still fail later with a less-helpful error (e.g., 'NoneType' object is not callable). Consider validating the attribute value as well (e.g., non-None and isinstance(value, nn.Module)) and include that in the error message so the early failure is consistently actionable.
| missing = [ | |
| (output_name, attr_name) | |
| for output_name, attr_name in self._components.items() | |
| if not hasattr(module, attr_name) | |
| ] | |
| if not missing: | |
| return | |
| lines = "\n".join( | |
| f" '{output_name}' component expects module.{attr_name}" | |
| for output_name, attr_name in missing | |
| ) | |
| raise TypeError( | |
| f"{task_name} requires sub-module attribute(s) that are missing " | |
| f"from {type(module).__name__}:\n{lines}\n" | |
| f"Ensure each attribute is assigned in the module's __init__()." | |
| ) | |
| problems: list[tuple[str, str, str]] = [] | |
| for output_name, attr_name in self._components.items(): | |
| if not hasattr(module, attr_name): | |
| # Attribute is completely missing from the module. | |
| problems.append( | |
| (output_name, attr_name, "missing"), | |
| ) | |
| continue | |
| value = getattr(module, attr_name) | |
| if value is None: | |
| # Attribute is present but not initialized to a module. | |
| problems.append( | |
| (output_name, attr_name, "none"), | |
| ) | |
| elif not isinstance(value, nn.Module): | |
| # Attribute is present but is not an onnxscript.nn.Module instance. | |
| problems.append( | |
| (output_name, attr_name, f"type:{type(value).__name__}"), | |
| ) | |
| if not problems: | |
| return | |
| lines: list[str] = [] | |
| for output_name, attr_name, kind in problems: | |
| if kind == "missing": | |
| lines.append( | |
| f" '{output_name}' component expects module.{attr_name} " | |
| f"but the attribute is missing." | |
| ) | |
| elif kind == "none": | |
| lines.append( | |
| f" '{output_name}' component expects module.{attr_name} " | |
| f"to be an onnxscript.nn.Module, but it is set to None." | |
| ) | |
| elif kind.startswith("type:"): | |
| type_name = kind.split(":", 1)[1] | |
| lines.append( | |
| f" '{output_name}' component expects module.{attr_name} " | |
| f"to be an onnxscript.nn.Module, but found object of type " | |
| f"{type_name}." | |
| ) | |
| message = ( | |
| f"{task_name} requires sub-module attribute(s) that are missing or invalid " | |
| f"on {type(module).__name__}:\n" | |
| + "\n".join(lines) | |
| + "\nEnsure each attribute is assigned to an onnxscript.nn.Module " | |
| "instance in the module's __init__()." | |
| ) | |
| raise TypeError(message) |
| task = NoSpecTask() | ||
| task._validate_components(EmptyModule()) # must not raise | ||
|
|
||
| """Test the user story: custom module + standard task.""" |
There was a problem hiding this comment.
There is a standalone triple-quoted string inside TestComponentSpec (not at the start of the class). Ruff/flake8-bugbear flags this as a useless expression (B018), and it also makes the following test_custom_module_with_causal_lm_task look like it belongs to a different section. Convert this to a # comment or move the custom-module tests into a separate test class so the file remains lint-clean and well-structured.
| """Test the user story: custom module + standard task.""" | |
| # Test the user story: custom module + standard task. |
| components = ComponentSpec( | ||
| vision="vision_encoder", | ||
| speech="speech_encoder", | ||
| embedding="embedding", | ||
| model="decoder", | ||
| ) |
There was a problem hiding this comment.
In this task, the component/output key is named model (mapping to module.decoder), but the module docstring and method names refer to the fourth component as decoder. With ComponentSpec, any validation error will now mention a missing 'model' component expecting module.decoder, which is potentially confusing. Consider aligning the output/component name with the terminology used elsewhere (e.g., use decoder as the ModelPackage key), or update the docstring to explicitly document that the decoder is stored under package["model"].
Introduce ComponentSpec, a declarative mechanism for multi-component tasks to declare which sub-module attributes they require. When a module is missing a required attribute, VisionLanguageTask (and similar) now raises a clear TypeError instead of a cryptic AttributeError deep inside build(). Changes: - tasks/_base.py: Add ComponentSpec class and ModelTask.components / _validate_components() API - tasks/_vision_language_3model.py: Add ComponentSpec to VisionLanguageTask (decoder/vision_encoder/embedding) and call _validate_components() - tasks/_speech_language.py: Add ComponentSpec to SpeechLanguageTask (audio_tower/embedding/decoder) and call _validate_components() - tasks/_phi4mm_multimodal.py: Add ComponentSpec to Phi4MMMultiModalTask (vision_encoder/speech_encoder/embedding/decoder) and call _validate_components() - tasks/__init__.py: Export ComponentSpec in __all__ and imports - tasks/_task_test.py: Add 9 TestComponentSpec tests covering validation, error messages (task name, module name, all missing attrs), VisionLanguageTask integration, and no-op behavior when no spec is declared Co-authored-by: Copilot <[email protected]> Signed-off-by: Justin Chu <[email protected]>
The class declaration was accidentally omitted when TestComponentSpec was inserted, leaving its docstring and test method orphaned inside the previous class. Co-authored-by: Copilot <[email protected]> Signed-off-by: Justin Chu <[email protected]>
…ToTextTask Add `components = ComponentSpec(...)` declarations and `_validate_components(module)` calls to the three remaining multi-model tasks that access sub-module attributes directly in `build()`. - tasks/_seq2seq.py: ComponentSpec(encoder='encoder', decoder='decoder') Seq2SeqTask accesses module.encoder / module.decoder directly. - tasks/_vae.py: ComponentSpec(encoder='encoder', decoder='decoder') VAETask accesses module.encoder / module.decoder directly; quant_conv and post_quant_conv are already guarded with 'is not None' checks so they are intentionally omitted from the spec. - tasks/_speech_to_text.py: ComponentSpec(model='model') SpeechToTextTask accesses module.model.encoder and module.model.decoder, so the top-level required attribute is 'model'. - tasks/_task_test.py: 4 new validation tests covering each task (TestSeq2SeqTask: missing encoder/decoder, TestVAETask: missing encoder, TestSpeechToTextTask: missing model). Co-authored-by: Copilot <[email protected]> Signed-off-by: Justin Chu <[email protected]>
d58fa58 to
f2f56f7
Compare
- Add ClassVar annotation to components field on ModelTask - Use dotted-path validation for SpeechToTextTask (model.encoder/model.decoder) - Fix Phi4MMMultiModalTask naming: use 'decoder' key instead of 'model' - Update build_graph_test.py to use pkg['decoder'] for Phi4MM - Add per-task validation tests for SpeechLanguageTask and Phi4MMMultiModalTask - Escape regex metacharacters in pytest.raises match pattern Co-authored-by: Copilot <[email protected]> Signed-off-by: Justin Chu <[email protected]>
- tests/build_graph_test.py: fix remaining pkg['model'] ref to pkg['decoder'] - auto_export_test.py: update pkg['model'] assertion to pkg['decoder'] - genai_config.py: use 'decoder/model.onnx' filename for multimodal decoder (consistent with vision/speech/embedding subfolder convention) - genai_config_test.py: add tests for multimodal and single-model decoder filenames Co-authored-by: Copilot <[email protected]> Signed-off-by: Justin Chu <[email protected]>
## 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]>
Summary
Introduces
ComponentSpec, a declarative mechanism for multi-component tasks to validate required sub-module attributes before building. When a module is missing a required attribute, the task now raises a clearTypeErrorwith a helpful message instead of a crypticAttributeErrordeep insidebuild().API
Changes
Core (
_base.py)ComponentSpecclass — declarative attribute spec (**components: strkwargs, output name → attr name)ModelTask.components— optional class-level spec (defaultNone)ModelTask._validate_components()— no-op whencomponents is None; callsspec.validate()otherwiseTasks wired up (all 6 multi-model tasks)
VisionLanguageTaskdecoder,vision_encoder,embeddingSpeechLanguageTaskaudio_tower,embedding,decoderPhi4MMMultiModalTaskvision_encoder,speech_encoder,embedding,decoderSeq2SeqTaskencoder,decoderVAETaskencoder,decoderSpeechToTextTaskmodel(then accesses.model.encoder/.model.decoder)Export
ComponentSpecexported frommobius.taskspublic surface.Tests (13 new in
TestComponentSpec+ 4 integration tests)components is None