Skip to content

Add ComponentSpec for multi-model task validation - #73

Closed
justinchuby wants to merge 5 commits into
mainfrom
justinchu/component-spec
Closed

justinchuby wants to merge 5 commits into
mainfrom
justinchu/component-spec

Conversation

@justinchuby

@justinchuby justinchuby commented Apr 1, 2026 •

Copy link
Copy Markdown
Member

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 clear TypeError with a helpful message instead of a cryptic AttributeError deep inside build().

API

# ComponentSpec maps output model name → module attribute name
spec = ComponentSpec(decoder="decoder", vision="vision_encoder", embedding="embedding")

# Validate: raises TypeError if any attribute is missing
spec.validate(module, "VisionLanguageTask")

Changes

Core (_base.py)

  • ComponentSpec class — declarative attribute spec (**components: str kwargs, output name → attr name)
  • ModelTask.components — optional class-level spec (default None)
  • ModelTask._validate_components() — no-op when components is None; calls spec.validate() otherwise

Tasks wired up (all 6 multi-model tasks)

Task Required attributes
VisionLanguageTask decoder, vision_encoder, embedding
SpeechLanguageTask audio_tower, embedding, decoder
Phi4MMMultiModalTask vision_encoder, speech_encoder, embedding, decoder
Seq2SeqTask encoder, decoder
VAETask encoder, decoder
SpeechToTextTask model (then accesses .model.encoder / .model.decoder)

Export

ComponentSpec exported from mobius.tasks public surface.

Tests (13 new in TestComponentSpec + 4 integration tests)

  • ComponentSpec repr, iteration, passes when all present, raises on single/multiple missing
  • Error message includes task name and module class name
  • VisionLanguageTask integration test
  • No-op when components is None
  • Seq2SeqTask: missing encoder, missing decoder
  • VAETask: missing encoder
  • SpeechToTextTask: missing model

@justinchuby justinchuby added the ai Created by an AI agent label Apr 1, 2026
@justinchuby justinchuby self-assigned this Apr 1, 2026
@justinchuby
justinchuby requested review from a team and Copilot April 1, 2026 17:39
@justinchuby justinchuby added the ai Created by an AI agent label Apr 1, 2026
@github-actions

github-actions Bot commented Apr 1, 2026 •

Copy link
Copy Markdown

Performance Comparison

Comparing d66a566 → bfaf15e

Model Metric Baseline Current Delta
bert (feature-extraction) model_size_bytes 359 KB 359 KB +0.0% ⚪
bert (feature-extraction) num_nodes 49 49 +0.0% ⚪
falcon model_size_bytes 364 KB 364 KB +0.0% ⚪
falcon num_nodes 53 53 +0.0% ⚪
gemma2 model_size_bytes 428 KB 428 KB +0.0% ⚪
gemma2 num_nodes 92 92 +0.0% ⚪
gpt2 model_size_bytes 388 KB 388 KB +0.0% ⚪
gpt2 num_nodes 40 40 +0.0% ⚪
llama model_size_bytes 425 KB 425 KB +0.0% ⚪
llama num_nodes 46 46 +0.0% ⚪
llama (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
llama (static-cache) num_nodes 43 43 +0.0% ⚪
mamba (ssm-text-generation) model_size_bytes 360 KB 360 KB +0.0% ⚪
mamba (ssm-text-generation) num_nodes 94 94 +0.0% ⚪
phi3 model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 num_nodes 46 46 +0.0% ⚪
phi3 (static-cache) model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 (static-cache) num_nodes 43 43 +0.0% ⚪
qwen2 model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 num_nodes 46 46 +0.0% ⚪
qwen2 (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 (static-cache) num_nodes 43 43 +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) model_size_bytes 506 KB 506 KB +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) num_nodes 233 233 +0.0% ⚪
qwen3_5_text (hybrid-text-generation) model_size_bytes 458 KB 458 KB +0.0% ⚪
qwen3_5_text (hybrid-text-generation) num_nodes 113 113 +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) model_size_bytes 977 KB 977 KB +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) num_nodes 381 381 +0.0% ⚪
t5 (seq2seq) model_size_bytes 836 KB 836 KB +0.0% ⚪
t5 (seq2seq) num_nodes 141 141 +0.0% ⚪
whisper (speech-to-text) model_size_bytes 1008 KB 1008 KB +0.0% ⚪
whisper (speech-to-text) num_nodes 95 95 +0.0% ⚪

No performance regressions.

@github-actions

github-actions Bot commented Apr 1, 2026 •

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing d66a566 → bfaf15e

Model Sub-model Changes Status
bert (feature-extraction) model 0 ⚪
falcon model 0 ⚪
gemma2 model 0 ⚪
gpt2 model 0 ⚪
llama model 0 ⚪
llama (static-cache) model 0 ⚪
mamba (ssm-text-generation) model 0 ⚪
phi3 model 0 ⚪
phi3 (static-cache) model 0 ⚪
qwen model 0 ⚪
qwen (static-cache) model 0 ⚪
qwen2 model 0 ⚪
qwen2 (static-cache) model 0 ⚪
qwen2_moe model 0 ⚪
qwen2_moe (static-cache) model 0 ⚪
qwen3 model 0 ⚪
qwen3 (static-cache) model 0 ⚪
qwen3_5_moe (hybrid-text-generation) model 0 ⚪
qwen3_5_text (hybrid-text-generation) model 0 ⚪
qwen3_5_vl (hybrid-qwen-vl) decoder 0 ⚪
qwen3_5_vl (hybrid-qwen-vl) embedding 0 ⚪
qwen3_5_vl (hybrid-qwen-vl) vision 0 ⚪
qwen3_moe model 0 ⚪
qwen3_moe (static-cache) model 0 ⚪
qwen3_next (hybrid-text-generation) model 0 ⚪
t5 (seq2seq) decoder 0 ⚪
t5 (seq2seq) encoder 0 ⚪
whisper (speech-to-text) decoder 0 ⚪
whisper (speech-to-text) encoder 0 ⚪

No architecture changes detected. ✅


Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed)

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ComponentSpec plus ModelTask.components and _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 of build().
  • Added/updated task tests to cover ComponentSpec behavior and error messaging; exported ComponentSpec from mobius.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.

Comment thread src/mobius/tasks/_base.py
Comment on lines +71 to +86
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__()."
)

Copilot AI Apr 1, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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)

Copilot uses AI. Check for mistakes.
task = NoSpecTask()
task._validate_components(EmptyModule()) # must not raise

"""Test the user story: custom module + standard task."""

Copilot AI Apr 1, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
"""Test the user story: custom module + standard task."""
# Test the user story: custom module + standard task.

Copilot uses AI. Check for mistakes.
Comment on lines +50 to +55
components = ComponentSpec(
vision="vision_encoder",
speech="speech_encoder",
embedding="embedding",
model="decoder",
)

Copilot AI Apr 1, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"].

Copilot uses AI. Check for mistakes.
@justinchuby
justinchuby marked this pull request as draft April 1, 2026 18:45
justinchuby and others added 3 commits April 7, 2026 21:31
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]>
@justinchuby
justinchuby force-pushed the justinchu/component-spec branch from d58fa58 to f2f56f7 Compare April 8, 2026 04:35
justinchuby and others added 2 commits April 7, 2026 21:44
- 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]>
justinchuby added a commit that referenced this pull request Apr 10, 2026
## 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]>
@justinchuby
justinchuby deleted the justinchu/component-spec branch May 7, 2026 01:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ai Created by an AI agent

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants