|
| 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