Skip to content

Commit 66e9c5e

Browse files
xiaoyu-workCopilotCopilotjustinchubygithub-code-quality[bot]
authored
Add component inspection API (#378)
## Summary - add mobius.inspect_components and ComponentInfo - report ModelPackage component names/kinds without building graphs or loading weights - include source_path hints for Qwen VL components ## Validation - PYTHONPATH=$PWD/src conda run -n olive python -m pytest src/mobius/_inspect_test.py -q --------- Signed-off-by: Xiaoyu <[email protected]> Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot <[email protected]> Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: Justin Chu <[email protected]> Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> Copilot-Session: 8f087f94-098a-4cca-8653-436c45150324 Copilot-Session: ad41ef64-d67a-49f7-b340-200b666497f2 Copilot-Session: 88ec109e-af0c-46c3-9806-731bc2b7342f
1 parent cf77d0f commit 66e9c5e

33 files changed

Lines changed: 1235 additions & 80 deletions

‎.github/workflows/golden_regen.yml‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -77,15 +77,17 @@ jobs:
7777
if: inputs.device != 'cuda'
7878
run: pip install onnxruntime
7979

80-
- name: Install onnxruntime (GPU)
81-
if: inputs.device == 'cuda'
82-
run: pip install onnxruntime-gpu
83-
8480
- name: Install dependencies
8581
run: |
8682
pip install -r requirements/ci/requirements.txt
8783
pip install -e '.[testing,transformers]'
8884
85+
- name: Install onnxruntime (GPU)
86+
if: inputs.device == 'cuda'
87+
run: |
88+
# Install after project dependencies so the CPU ORT package cannot overwrite it.
89+
pip install --pre --no-deps --index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/ onnxruntime-gpu
90+
8991
- name: Reject trust_remote_code cases
9092
run: |
9193
# Safety: never auto-run models that require trust_remote_code

‎.github/workflows/gpu_l4_golden_parity.yml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,9 @@ jobs:
6464
pip install -r requirements/ci/requirements.txt
6565
pip install soundfile librosa ml_dtypes flatbuffers numpy packaging protobuf sympy coloredlogs
6666
pip install -e '.[testing,transformers]'
67-
pip install --pre --extra-index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/ort-cuda-12-nightly/pypi/simple/ onnxruntime-gpu onnxruntime-genai-cuda
67+
# PyPI's ORT 1.27+ wheel requires CUDA 13, while these runners use CUDA 12.
68+
pip install --pre --no-deps --index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/ onnxruntime-gpu
69+
pip install --no-deps onnxruntime-genai-cuda
6870
6971
- name: Check for golden test data
7072
id: check_golden

‎.github/workflows/gpu_l5_generation_e2e.yml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,9 @@ jobs:
6464
pip install -r requirements/ci/requirements.txt
6565
pip install soundfile librosa ml_dtypes flatbuffers numpy packaging protobuf sympy coloredlogs
6666
pip install -e '.[testing,transformers]'
67-
pip install --pre --extra-index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/ort-cuda-12-nightly/pypi/simple/ onnxruntime-gpu onnxruntime-genai-cuda
67+
# PyPI's ORT 1.27+ wheel requires CUDA 13, while these runners use CUDA 12.
68+
pip install --pre --no-deps --index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/ onnxruntime-gpu
69+
pip install --no-deps onnxruntime-genai-cuda
6870
6971
- name: Run L5 generation E2E tests
7072
env:

‎.github/workflows/main.yml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,9 @@ jobs:
283283
pip install -r requirements/ci/requirements.txt
284284
pip install soundfile librosa ml_dtypes flatbuffers numpy packaging protobuf sympy coloredlogs
285285
pip install -e '.[testing]'
286-
pip install --pre --extra-index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/ort-cuda-12-nightly/pypi/simple/ "onnxruntime-gpu<1.27" onnxruntime-genai-cuda
286+
# PyPI's ORT 1.27+ wheel requires CUDA 13, while these runners use CUDA 12.
287+
pip install --pre --no-deps --index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/ onnxruntime-gpu
288+
pip install --no-deps onnxruntime-genai-cuda
287289
- name: Run fast integration tests
288290
env:
289291
HF_TOKEN: ${{ secrets.HF_TOKEN }}

‎.github/workflows/validation_examples_gpu.yml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,9 @@ jobs:
8383
pip install -r requirements/ci/requirements.txt
8484
pip install -e '.[testing,transformers]'
8585
pip install soundfile librosa ml_dtypes flatbuffers numpy packaging protobuf sympy coloredlogs
86-
pip install --pre --extra-index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/ort-cuda-12-nightly/pypi/simple/ onnxruntime-gpu onnxruntime-genai-cuda
86+
# PyPI's ORT 1.27+ wheel requires CUDA 13, while these runners use CUDA 12.
87+
pip install --pre --no-deps --index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/ onnxruntime-gpu
88+
pip install --no-deps onnxruntime-genai-cuda
8789
8890
- name: Run ${{ matrix.name }}
8991
env:

‎src/mobius/__init__.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
"BaseModelConfig",
1010
"CausalLMConfig",
1111
"CausalLMTask",
12+
"ComponentInfo",
1213
"DepthAnythingConfig",
1314
"EncoderConfig",
1415
"EpCapabilities",
@@ -48,6 +49,7 @@
4849
"ep_registry",
4950
"get_build_dtype",
5051
"get_ep",
52+
"inspect_components",
5153
"models",
5254
"optimize_model",
5355
"register_ep",
@@ -87,6 +89,7 @@
8789
)
8890
from mobius._constants import OPSET_VERSION
8991
from mobius._execution_providers import EpCapabilities, ep_registry, get_ep, register_ep
92+
from mobius._inspect import ComponentInfo, inspect_components
9093
from mobius._model_package import ModelPackage
9194
from mobius._optimizations import optimize_model
9295
from mobius._registry import (

‎src/mobius/_inspect.py‎

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
"""Inspect a model's component layout without building it.
5+
6+
``inspect_components`` reports the components mobius would produce for a model
7+
(their package keys and optimization roles) **without** constructing graphs or
8+
loading weights. External tools such as Olive use this to plan per-component
9+
work — e.g. optimizing a VLM's ``decoder`` differently from its
10+
``vision_encoder`` — before calling :func:`mobius.build`.
11+
12+
The component names returned here are the same keys :func:`mobius.build`
13+
produces in its :class:`~mobius._model_package.ModelPackage` (and therefore the
14+
subfolder names ``ModelPackage.save`` writes for multi-component models).
15+
"""
16+
17+
from __future__ import annotations
18+
19+
__all__ = ["ComponentInfo", "inspect_components"]
20+
21+
import dataclasses
22+
import logging
23+
24+
logger = logging.getLogger(__name__)
25+
26+
27+
@dataclasses.dataclass(frozen=True)
28+
class ComponentInfo:
29+
"""A single component of a model.
30+
31+
Attributes:
32+
name: Component name. This is the ``ModelPackage`` key mobius produces
33+
(and the subfolder name a multi-component export is saved under).
34+
role: Optimization role of the component, e.g. ``"decoder"``,
35+
``"encoder"``, or ``"embedding"``. Mobius uses this to gate fusion
36+
passes (only ``"decoder"`` receives GQA / QKV-packing). It is the
37+
value declared in the task's ``model_roles``.
38+
source_paths: Runtime ``named_modules()`` paths that make up this
39+
component inside the full HuggingFace model. These are not
40+
checkpoint/state-dict key prefixes. A single component may map to
41+
multiple disjoint sub-modules (e.g. a decoder assembled from
42+
``model.layers``, ``model.norm`` and ``lm_head``), so this is a
43+
tuple. Empty when the component is the whole model or the layout is
44+
unknown. Tools such as Olive use these to optimize a submodule in
45+
place before exporting the full model.
46+
"""
47+
48+
name: str
49+
role: str
50+
source_paths: tuple[str, ...] = ()
51+
52+
53+
def _resolve_task_model_type_and_config(
54+
model_id: str, task, trust_remote_code: bool
55+
) -> tuple[str, str | None, object | None]:
56+
"""Resolve the mobius task name for a model id without building it.
57+
58+
Mirrors the model_type/task resolution in :func:`mobius.build`, limited to
59+
what is needed to pick a task and inspect class-level component metadata
60+
(no module construction, no weight loading).
61+
"""
62+
import transformers
63+
64+
from mobius._registry import _detect_fallback_registration, registry
65+
from mobius.integrations.transformers._config_resolver import (
66+
_default_task_for_model,
67+
_try_load_config_json,
68+
)
69+
70+
try:
71+
hf_config = transformers.AutoConfig.from_pretrained(
72+
model_id, trust_remote_code=trust_remote_code
73+
)
74+
except (ValueError, KeyError, OSError):
75+
hf_config = _try_load_config_json(model_id)
76+
if hf_config is None:
77+
# An explicit task is enough to report component names and roles,
78+
# but source paths require a model type and therefore stay empty.
79+
if task is not None:
80+
return task, None, None
81+
raise ValueError(
82+
f"Could not load a HuggingFace config for {model_id!r}. inspect_components supports "
83+
"transformers/registry models; diffusers pipelines are not supported."
84+
) from None
85+
86+
model_type = hf_config.model_type
87+
88+
# model_type adjustments that affect task selection (subset of build()):
89+
# Qwen3.5-MoE ships the same model_type for text-only and VL checkpoints.
90+
if model_type == "qwen3_5_moe" and getattr(hf_config, "vision_config", None) is not None:
91+
model_type = "qwen3_5_moe_vl"
92+
# wav2vec2/hubert/wavlm with a CTC head map to the mms (CTC) registration.
93+
if model_type in ("wav2vec2", "hubert", "wavlm"):
94+
architectures = getattr(hf_config, "architectures", None) or []
95+
if any("ForCTC" in arch for arch in architectures):
96+
model_type = "mms"
97+
98+
if task is not None:
99+
return task, model_type, hf_config
100+
if model_type in registry:
101+
return _default_task_for_model(model_type), model_type, hf_config
102+
103+
fallback = _detect_fallback_registration(hf_config)
104+
if fallback is not None and fallback.task is not None:
105+
return fallback.task, model_type, hf_config
106+
return _default_task_for_model(model_type), model_type, hf_config
107+
108+
109+
def _get_hf_component_sources(
110+
module_class: type,
111+
model_type: str,
112+
hf_config: object,
113+
) -> dict[str, tuple[str, ...]]:
114+
"""Read runtime HuggingFace component paths from a registered model class."""
115+
resolver = getattr(module_class, "get_hf_component_sources", None)
116+
if resolver is not None:
117+
return resolver(model_type=model_type, hf_config=hf_config)
118+
return getattr(module_class, "HF_COMPONENT_SOURCES", {})
119+
120+
121+
def inspect_components(
122+
model_id: str,
123+
task=None,
124+
trust_remote_code: bool = False,
125+
) -> list[ComponentInfo]:
126+
"""Return the components mobius would produce for a model.
127+
128+
Args:
129+
model_id: HuggingFace model id or local path.
130+
task: Optional task name (e.g. ``"vision-language"``) or
131+
:class:`~mobius.tasks.ModelTask` instance. When ``None``, the task
132+
is auto-detected from the model type.
133+
trust_remote_code: Whether to trust remote code when loading the
134+
HuggingFace config.
135+
136+
Returns:
137+
A list of :class:`ComponentInfo`. Single-component models (most LLMs)
138+
return a single entry named ``"model"``; multi-component models (VLMs,
139+
encoder-decoders, speech models) return one entry per component.
140+
141+
Raises:
142+
ValueError: If a config cannot be resolved for ``model_id`` (e.g. a
143+
diffusers pipeline, which is not supported).
144+
"""
145+
from mobius._registry import registry
146+
from mobius.tasks import get_task
147+
148+
resolved_task, model_type, hf_config = _resolve_task_model_type_and_config(
149+
model_id, task, trust_remote_code
150+
)
151+
task_obj = get_task(resolved_task)
152+
roles = task_obj.model_roles or {}
153+
154+
# Runtime HF paths are owned by the registered model class. Most classes
155+
# declare a fixed ``HF_COMPONENT_SOURCES`` mapping; classes shared by
156+
# several HF layouts can resolve paths from the already-loaded config.
157+
component_sources: dict[str, tuple[str, ...]] = {}
158+
if model_type is not None and hf_config is not None and model_type in registry:
159+
module_class = registry.get(model_type)
160+
component_sources = _get_hf_component_sources(module_class, model_type, hf_config)
161+
162+
components = [
163+
ComponentInfo(
164+
name=name,
165+
role=role,
166+
source_paths=tuple(component_sources.get(name, ())),
167+
)
168+
for name, role in roles.items()
169+
]
170+
logger.debug(
171+
"inspect_components(%s): task=%s components=%s",
172+
model_id,
173+
resolved_task,
174+
[c.name for c in components],
175+
)
176+
return components

0 commit comments

Comments
 (0)