Skip to content

Commit 9e7d1ad

Browse files
justinchubyCopilot
andauthored
configs refactor 2/3: registry-based audio extractor hooks (#310)
## Part 2 of 3 — stacked on #309 Replaces the 135-line `model_type` switch in `_extract_audio_config` with a tiny plugin registry. Each model now contributes a hook in its own file under `src/mobius/_configs/per_model/`, mutating an `audio_fields` dict or short-circuiting with a fully-formed sub-config. **Adding a new audio-capable architecture no longer requires editing `_base.py`.** ## Layout ``` src/mobius/_configs/ ├── _extractors.py # @register_audio_hook + dispatch └── per_model/ ├── _audio_default.py # audio_processor / embd_layer / speech_lora ├── _phi4mm_audio.py # phi4mm audio_token_id ├── _qwen3_asr_audio.py # thinker_config.audio_config + token ids ├── _gemma4_audio.py # short-circuit to Gemma4AudioConfig └── _sensevoice_audio.py # encoder_conf + frontend_conf mapping ``` `_extract_audio_config` in `_base.py` shrinks to a 5-line shim that triggers the `per_model` side-effect import and calls the dispatcher. **No behavior change**: every existing audio-capable model still produces the same `AudioConfig` from the same HF config. ## Hook protocol ```python @register_audio_hook def _my_model(config, parent_config, model_type: str, fields: dict) -> dict | None: if model_type != "my_model": return None fields.update(attention_dim=..., ...) return None # contribute fields, defer to default AudioConfig(**fields) # OR return {"audio": MySubclassAudioConfig(...)} # short-circuit ``` ## Deferred Vision-side conversion (also a mega-switch) is intentionally deferred to a follow-up so reviewers can verify the registry pattern on the smaller surface first. ## Tests | Suite | Result | |---|---| | `pytest src/ tests/build_graph_test.py tests/cli_test.py -n auto` | 2769 passed, 41 skipped | | `pytest tests/arch_validation_test.py -k 'sensevoice_small or phi4mm or qwen3_asr or gemma4'` | 15 passed | | Ruff | clean | --------- Signed-off-by: Justin Chu <[email protected]> Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot <[email protected]>
1 parent 5d592c6 commit 9e7d1ad

9 files changed

Lines changed: 568 additions & 131 deletions

File tree

‎src/mobius/_configs/_base.py‎

Lines changed: 6 additions & 131 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
CodecDecoderConfig,
1717
CodecEncoderConfig,
1818
CodePredictorConfig,
19-
Gemma4AudioConfig,
2019
RoPEConfig,
2120
SpeakerEncoderConfig,
2221
TTSConfig,
@@ -453,138 +452,14 @@ def _extract_vision_config(config, parent_config, model_type: str) -> dict:
453452
def _extract_audio_config(config, parent_config, model_type: str) -> dict:
454453
"""Extract audio sub-config from a HuggingFace config.
455454
456-
Builds an :class:`AudioConfig` (if audio fields are found) and
457-
returns a dict of options to merge into :class:`ArchitectureConfig`
458-
kwargs.
455+
Thin shim that delegates to the per-model registry. The actual
456+
hooks live under :mod:`mobius._configs.per_model` and are
457+
registered with :mod:`mobius._configs._extractors` at import time.
459458
"""
460-
audio_fields: dict = {}
461-
audio_processor = getattr(config, "audio_processor", None)
462-
if isinstance(audio_processor, dict) and "config" in audio_processor:
463-
ac = audio_processor["config"]
464-
nemo = ac.get("nemo_conv_settings", {})
465-
rel_bias = ac.get("relative_attention_bias_args", {})
466-
audio_fields.update(
467-
attention_dim=ac.get("attention_dim"),
468-
attention_heads=ac.get("attention_heads"),
469-
num_blocks=ac.get("num_blocks"),
470-
linear_units=ac.get("linear_units"),
471-
kernel_size=ac.get("kernel_size"),
472-
input_size=ac.get("input_size"),
473-
conv_channels=nemo.get("conv_channels", ac.get("attention_dim")),
474-
t5_bias_max_distance=rel_bias.get("t5_bias_max_distance"),
475-
)
459+
from mobius._configs import per_model # noqa: F401 - side-effect import
460+
from mobius._configs._extractors import extract_audio_config as _dispatch
476461

477-
embd_layer = getattr(config, "embd_layer", None)
478-
if isinstance(embd_layer, dict):
479-
audio_fields["projection_hidden_size"] = config.hidden_size
480-
481-
# Phi4MM audio token ID
482-
if model_type == "phi4mm":
483-
audio_config_dict = getattr(config, "audio_config", None)
484-
if audio_config_dict is not None:
485-
ac_dict = (
486-
audio_config_dict
487-
if isinstance(audio_config_dict, dict)
488-
else vars(audio_config_dict)
489-
)
490-
audio_fields["token_id"] = ac_dict.get("audio_token_id")
491-
492-
speech_lora = getattr(config, "speech_lora", None)
493-
if speech_lora is not None:
494-
audio_fields["lora"] = (
495-
speech_lora if isinstance(speech_lora, dict) else vars(speech_lora)
496-
)
497-
498-
# Qwen3-ASR audio config (from thinker_config)
499-
thinker_config_source = parent_config or config
500-
hf_thinker_config = getattr(thinker_config_source, "thinker_config", None)
501-
if hf_thinker_config is not None:
502-
tc = (
503-
hf_thinker_config
504-
if not isinstance(hf_thinker_config, dict)
505-
else type("TC", (), hf_thinker_config)()
506-
)
507-
hf_audio_config = getattr(tc, "audio_config", None)
508-
if hf_audio_config is not None:
509-
ac = (
510-
hf_audio_config
511-
if not isinstance(hf_audio_config, dict)
512-
else type("AC", (), hf_audio_config)()
513-
)
514-
audio_fields.update(
515-
d_model=getattr(ac, "d_model", None),
516-
encoder_layers=getattr(ac, "encoder_layers", None),
517-
encoder_attention_heads=getattr(ac, "encoder_attention_heads", None),
518-
encoder_ffn_dim=getattr(ac, "encoder_ffn_dim", None),
519-
num_mel_bins=getattr(ac, "num_mel_bins", None),
520-
max_source_positions=getattr(ac, "max_source_positions", None),
521-
downsample_hidden_size=getattr(ac, "downsample_hidden_size", None),
522-
output_dim=getattr(ac, "output_dim", None),
523-
activation_function=getattr(ac, "activation_function", "gelu"),
524-
n_window=getattr(ac, "n_window", None),
525-
n_window_infer=getattr(ac, "n_window_infer", None),
526-
)
527-
# Special tokens from thinker config
528-
audio_fields["audio_token_id"] = getattr(tc, "audio_token_id", None)
529-
audio_fields["audio_start_token_id"] = getattr(tc, "audio_start_token_id", None)
530-
audio_fields["audio_end_token_id"] = getattr(tc, "audio_end_token_id", None)
531-
audio_fields["classify_num"] = getattr(tc, "classify_num", None)
532-
533-
# Gemma4 audio config (from composite audio_config sub-config).
534-
# model_type may be "gemma4_text" when build() resolves to the text sub-config;
535-
# check parent_config to catch that case.
536-
parent_model_type = getattr(parent_config, "model_type", "") if parent_config else ""
537-
if model_type in ("gemma4", "gemma4_text") or parent_model_type == "gemma4":
538-
composite = parent_config or config
539-
hf_audio_config = getattr(composite, "audio_config", None)
540-
if hf_audio_config is not None:
541-
ac = (
542-
hf_audio_config
543-
if not isinstance(hf_audio_config, dict)
544-
else type("AC", (), hf_audio_config)()
545-
)
546-
subsampling = getattr(ac, "subsampling_conv_channels", None)
547-
return {
548-
"audio": Gemma4AudioConfig(
549-
num_layers=getattr(ac, "num_hidden_layers", 12),
550-
hidden_size=getattr(ac, "hidden_size", 1024),
551-
subsampling_conv_channels=(
552-
list(subsampling) if subsampling is not None else None
553-
),
554-
use_causal_chunked_attn=getattr(ac, "use_causal_chunked_attn", False),
555-
output_dim=getattr(ac, "output_dim", None),
556-
output_proj_dims=getattr(ac, "output_proj_dims", None),
557-
audio_token_id=getattr(composite, "audio_token_id", None),
558-
)
559-
}
560-
561-
# SenseVoice / FunASR-style: encoder config lives under "encoder_conf"
562-
# and the mel-spec frontend under "frontend_conf". Top-level holds
563-
# input_size + vocab_size. model_type is "sensevoice".
564-
if model_type == "sensevoice":
565-
encoder_conf = getattr(config, "encoder_conf", None) or {}
566-
frontend_conf = getattr(config, "frontend_conf", None) or {}
567-
if isinstance(encoder_conf, dict) and encoder_conf:
568-
audio_fields.update(
569-
attention_dim=encoder_conf.get("output_size"),
570-
attention_heads=encoder_conf.get("attention_heads"),
571-
num_blocks=encoder_conf.get("num_blocks"),
572-
tp_num_blocks=encoder_conf.get("tp_blocks"),
573-
linear_units=encoder_conf.get("linear_units"),
574-
kernel_size=encoder_conf.get("kernel_size"),
575-
input_size=getattr(config, "input_size", None),
576-
)
577-
if isinstance(frontend_conf, dict):
578-
audio_fields["num_mel_bins"] = frontend_conf.get("n_mels")
579-
580-
# Build AudioConfig sub-config if any audio fields are set
581-
has_audio = any(v is not None for v in audio_fields.values())
582-
583-
result: dict = {}
584-
if has_audio:
585-
result["audio"] = AudioConfig(**audio_fields)
586-
587-
return result
462+
return _dispatch(config, parent_config, model_type)
588463

589464

590465
@dataclasses.dataclass

‎src/mobius/_configs/_extractors.py‎

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
"""Plugin-style registry for sub-config extractors.
5+
6+
Each ``extract_*`` function used to be a single mega-switch inside
7+
:mod:`mobius._configs._base` with a chain of ``if model_type == "..."``
8+
branches. That meant every new architecture had to edit a shared file
9+
and risk merge conflicts with unrelated work.
10+
11+
This module replaces those switches with a tiny registry. Hooks are
12+
plain functions registered via the :func:`register_audio_hook` /
13+
:func:`register_vision_hook` decorators. Each hook is invoked on every
14+
extraction and is responsible for guarding its own applicability
15+
(typically by checking ``model_type`` or for the presence of a specific
16+
HuggingFace field). A hook may:
17+
18+
* mutate ``fields`` to contribute key/value pairs into the default
19+
sub-config that the dispatcher will instantiate at the end, or
20+
* return a fully-formed ``dict`` (e.g. ``{"audio": Gemma4AudioConfig(...)}``)
21+
to short-circuit — skipping all subsequent hooks and the default
22+
instantiation. Use this when a model needs a non-default sub-config
23+
subclass.
24+
25+
New models live in :mod:`mobius._configs.per_model`. Importing that
26+
package is what populates the registries (each module registers its
27+
own hooks at import time).
28+
"""
29+
30+
from __future__ import annotations
31+
32+
from collections.abc import Callable
33+
from typing import Any
34+
35+
Hook = Callable[[Any, Any, str, dict], dict | None]
36+
37+
# Each registry entry is ``(model_type_filter, hook)`` where the filter is
38+
# either ``None`` (always run) or a frozenset of model_type strings.
39+
_AUDIO_HOOKS: list[tuple[frozenset[str] | None, Hook]] = []
40+
_VISION_HOOKS: list[tuple[frozenset[str] | None, Hook]] = []
41+
42+
43+
def _make_register(registry: list) -> Callable:
44+
"""Build a decorator that supports both bare and parameterised usage."""
45+
46+
def register(*model_types):
47+
"""Register a hook in *registry*.
48+
49+
Two usages are supported:
50+
51+
* Bare decorator — runs for every model_type. Use this for default
52+
hooks that pull a generic HuggingFace field common to many models.
53+
54+
.. code-block:: python
55+
56+
@register_audio_hook
57+
def _default(config, parent, mt, fields): ...
58+
59+
* Parameterised decorator — runs only when ``model_type`` matches one
60+
of the supplied strings. The dispatcher filters before invocation
61+
so hook bodies don't need to repeat the ``if model_type != ...``
62+
guard. Hooks that *also* need to inspect ``parent_config`` (e.g.
63+
Gemma4's text-config short-circuit) can still do that check inside.
64+
65+
.. code-block:: python
66+
67+
@register_audio_hook("phi4mm")
68+
def _phi4mm(config, parent, mt, fields): ...
69+
70+
@register_audio_hook("gemma4", "gemma4_text")
71+
def _gemma4(config, parent, mt, fields): ...
72+
"""
73+
# Bare decorator: ``@register`` with a single callable arg
74+
if (
75+
len(model_types) == 1
76+
and callable(model_types[0])
77+
and not isinstance(model_types[0], str)
78+
):
79+
fn = model_types[0]
80+
registry.append((None, fn))
81+
return fn
82+
83+
types_set = frozenset(model_types) if model_types else None
84+
85+
def deco(fn: Hook) -> Hook:
86+
registry.append((types_set, fn))
87+
return fn
88+
89+
return deco
90+
91+
return register
92+
93+
94+
register_audio_hook = _make_register(_AUDIO_HOOKS)
95+
register_vision_hook = _make_register(_VISION_HOOKS)
96+
97+
98+
def _run(hooks: list, config, parent_config, model_type: str, fields: dict):
99+
"""Apply each hook whose filter matches ``model_type``.
100+
101+
Short-circuits on the first hook that returns a non-None dict.
102+
"""
103+
for filter_set, hook in hooks:
104+
if filter_set is not None and model_type not in filter_set:
105+
continue
106+
result = hook(config, parent_config, model_type, fields)
107+
if result is not None:
108+
return result
109+
return None
110+
111+
112+
def extract_audio_config(config, parent_config, model_type: str) -> dict:
113+
"""Run every applicable audio hook and assemble the result.
114+
115+
Each hook either contributes to ``fields`` (which become kwargs for
116+
:class:`AudioConfig` at the end) or returns a dict that short-circuits
117+
the dispatcher.
118+
"""
119+
from mobius._configs._sub_configs import AudioConfig
120+
121+
fields: dict = {}
122+
short_circuit = _run(_AUDIO_HOOKS, config, parent_config, model_type, fields)
123+
if short_circuit is not None:
124+
return short_circuit
125+
if any(v is not None for v in fields.values()):
126+
return {"audio": AudioConfig(**fields)}
127+
return {}
128+
129+
130+
def extract_vision_config(config, parent_config, model_type: str) -> dict:
131+
"""Run every registered vision hook and assemble the result.
132+
133+
Vision hooks differ from audio hooks: there is no default
134+
:class:`VisionConfig` autoinstantiation — vision sub-configs are
135+
constructed by an always-applied "default" hook so that other hooks
136+
can override its output.
137+
"""
138+
fields: dict = {}
139+
short_circuit = _run(_VISION_HOOKS, config, parent_config, model_type, fields)
140+
if short_circuit is not None:
141+
return short_circuit
142+
return fields

0 commit comments

Comments
 (0)