Skip to content

Commit 23f3da7

Browse files
NishantN2005claude
andauthored
Add vision and audio support for Gemma 3n (#474)
## What this does Makes `google/gemma-3n-E4B-it` export as a real 4-model multimodal package (`decoder` + `vision_encoder` + `audio_encoder` + `embedding`) instead of a text-only decoder. Before this, both `gemma3n` and `gemma3n_text` mapped to `Gemma3nCausalLMModel`, so `Gemma3nCausalLMModel.preprocess_weights` deleted every `vision_tower.`, `audio_tower.`, and `multi_modal_projector.` key. The export succeeded and produced a package that could not accept images or audio at all. `gemma3n` now maps to a new `Gemma3nMultiModalModel` with `task="gemma3n"`, matching how `gemma3` / `gemma3_text` are already split. ## Two pre-existing text-path bugs fixed first These affect the already-shipping text export and are independent of the modality work, so they land as their own commits at the base of the branch. Both silently produced wrong numbers rather than crashing. - **KV layer sharing was not implemented** (2f01334). E4B sets `num_kv_shared_layers=15`, so layers >= 20 reuse the KV of the last non-shared layer of the same type (sliding -> layer 18, full -> layer 19). Attention always recomputed `k_proj`/`v_proj`. The checkpoint does ship `k_proj` for all 35 layers, so nothing failed to load -- the graph just computed KV that HF never uses, and the exported cache had 35 entries where HF effectively has 20. - **Activation sparsity (`_gaussian_topk`) was missing** (08a14a0). For E4B layers 0-9 `activation_sparsity_pattern` is 0.95. HF computes `cutoff = mean + std * icdf(0.95)` over the last dim and applies `relu(gate_proj - cutoff)` before the activation. `icdf(0.95)` is a compile-time constant, so no ONNX erf/ppf is needed. Both were previously invisible because `tests/synthetic_parity_test.py` pinned `num_kv_shared_layers: 0` for `gemma3n` and never set a sparsity pattern. Those escape hatches are removed here, so the existing HF-vs-mobius parity harness now covers both. ## Architecture notes Three places where gemma3n does not match the obvious existing component, and reusing it would have been wrong: - **The vision tower is MobileNet-V5-300m, not SigLIP.** HF routes `gemma3n_vision` to `TimmWrapperModel`, and timm is not a dependency. New `components/_mobilenetv5.py` implements the stem, EdgeResidual / UIB / UIB+MQA blocks, and the Multi-Scale Fusion Adapter, driven by a hard-coded per-stage spec table -- there is no config source for the block layout. - **The 116 `bn.weight` tensors are timm `RmsNorm2d`, not BatchNorm.** The checkpoint ships zero `bn.bias` / `running_mean` / `running_var` / `num_batches_tracked`. Using the existing `components.BatchNorm2d` would have demanded four initializers that do not exist. - **The audio tower reuses `_gemma4_audio.py` except for the norm.** gemma3n's SSCP conv blocks use `Gemma3nAudioCumulativeGroupNorm` -- group norm computed cumulatively over the time axis -- where gemma4 uses plain `LayerNormNoBias`. That needs `CumSum` over T. gemma3n also adds an explicit `relative_position_embedding.pos_proj` that gemma4 lacks. `components/_rms_norm.py` gains a shared scale-free RMSNorm, promoted out of `models/gemma4.py` rather than duplicated. --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
1 parent 1944a40 commit 23f3da7

42 files changed

Lines changed: 7615 additions & 265 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/mobius/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
"EpCapabilities",
1515
"Gemma2Config",
1616
"Gemma3nConfig",
17+
"Gemma3nMultiModalConfig",
1718
"Gemma4AudioConfig",
1819
"Gemma4Config",
1920
"MambaConfig",
@@ -69,6 +70,7 @@
6970
EncoderConfig,
7071
Gemma2Config,
7172
Gemma3nConfig,
73+
Gemma3nMultiModalConfig,
7274
Gemma4AudioConfig,
7375
Gemma4Config,
7476
MambaConfig,

‎src/mobius/_configs/__init__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
EncoderConfig,
3434
Gemma2Config,
3535
Gemma3nConfig,
36+
Gemma3nMultiModalConfig,
3637
Gemma4AssistantConfig,
3738
Gemma4Config,
3839
GraniteMoeHybridConfig,
@@ -74,6 +75,7 @@
7475
CodecDecoderConfig,
7576
CodecEncoderConfig,
7677
CodePredictorConfig,
78+
Gemma3nAudioConfig,
7779
Gemma4AudioConfig,
7880
RoPEConfig,
7981
SpeakerEncoderConfig,
@@ -96,7 +98,9 @@
9698
"Eagle3Config",
9799
"EncoderConfig",
98100
"Gemma2Config",
101+
"Gemma3nAudioConfig",
99102
"Gemma3nConfig",
103+
"Gemma3nMultiModalConfig",
100104
"Gemma4AudioConfig",
101105
"Gemma4Config",
102106
"GraniteMoeHybridConfig",

‎src/mobius/_configs/_base.py‎

Lines changed: 82 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -682,7 +682,7 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
682682
or 0
683683
),
684684
hidden_size=_as_int(hidden_size),
685-
intermediate_size=(
685+
intermediate_size=_as_int(
686686
getattr(config, "intermediate_size", None)
687687
or getattr(config, "mlp_hidden_size", None)
688688
or getattr(config, "n_inner", None)
@@ -792,6 +792,8 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
792792
model_type
793793
in (
794794
"gemma3_text",
795+
"gemma3n",
796+
"gemma3n_text",
795797
"flex_olmo",
796798
"olmoe",
797799
"olmo2",
@@ -1542,6 +1544,21 @@ class Gemma3nConfig(CausalLMConfig):
15421544
15431545
Adds AltUp prediction/correction parameters and per-layer input
15441546
dimension fields used exclusively by :mod:`models.gemma3n`.
1547+
1548+
``num_kv_shared_layers`` mirrors the Gemma4 field of the same name: the
1549+
last N decoder layers borrow K,V from the last non-shared layer of the
1550+
same attention type instead of projecting their own, so they own no KV
1551+
cache entry. E4B ships 15 (of 35 layers), i.e. layers 20..34 are shared.
1552+
1553+
``activation_sparsity_pattern`` holds a per-layer target sparsity for the
1554+
MLP gate branch. Where it is non-zero the gate activations below a
1555+
Gaussian quantile cutoff are zeroed (see
1556+
:class:`~mobius.models.gemma3n.Gemma3nMLP`). E4B ships 0.95 for layers
1557+
0..9 and 0.0 for the rest; ``None`` disables sparsity everywhere.
1558+
1559+
``final_logit_softcapping`` tanh-caps the LM head output as in Gemma2
1560+
(``cap * tanh(logits / cap)``). Every published Gemma 3n config ships
1561+
30.0; ``0.0`` disables it.
15451562
"""
15461563

15471564
altup_num_inputs: int = 4
@@ -1550,10 +1567,14 @@ class Gemma3nConfig(CausalLMConfig):
15501567
laurel_rank: int = 64
15511568
hidden_size_per_layer_input: int = 256
15521569
vocab_size_per_layer_input: int = 262_144
1570+
num_kv_shared_layers: int = 0
1571+
activation_sparsity_pattern: list[float] | None = None
1572+
final_logit_softcapping: float = 0.0
15531573

15541574
@classmethod
15551575
def from_transformers(cls, config, parent_config=None) -> Gemma3nConfig:
15561576
base = ArchitectureConfig.from_transformers(config, parent_config)
1577+
sparsity = getattr(config, "activation_sparsity_pattern", None)
15571578
return cls(
15581579
**_shallow_fields(base),
15591580
altup_num_inputs=getattr(config, "altup_num_inputs", 4),
@@ -1562,6 +1583,66 @@ def from_transformers(cls, config, parent_config=None) -> Gemma3nConfig:
15621583
laurel_rank=getattr(config, "laurel_rank", 64),
15631584
hidden_size_per_layer_input=getattr(config, "hidden_size_per_layer_input", 256),
15641585
vocab_size_per_layer_input=getattr(config, "vocab_size_per_layer_input", 262_144),
1586+
num_kv_shared_layers=getattr(config, "num_kv_shared_layers", 0) or 0,
1587+
activation_sparsity_pattern=(
1588+
[float(s) for s in sparsity] if sparsity is not None else None
1589+
),
1590+
final_logit_softcapping=(getattr(config, "final_logit_softcapping", 0.0) or 0.0),
1591+
)
1592+
1593+
1594+
@dataclasses.dataclass
1595+
class Gemma3nMultiModalConfig(Gemma3nConfig):
1596+
"""Configuration for the full Gemma 3n image + audio + text model.
1597+
1598+
Carries the same text-decoder fields as :class:`Gemma3nConfig` (from which
1599+
it inherits, since the decoder is unchanged) plus the multimodal wiring.
1600+
The towers live in the inherited ``vision`` (:class:`VisionConfig`, a
1601+
MobileNet-V5 encoder rather than SigLIP) and ``audio``
1602+
(:class:`Gemma3nAudioConfig`, a USM Conformer) sub-configs, populated by
1603+
the ``gemma3n`` extractor hooks.
1604+
1605+
Both modalities are projected into the decoder's embedding space and
1606+
spliced in at their placeholder token positions, so each needs its token
1607+
id and its fixed soft-token count. The token ids come from the inherited
1608+
``image_token_id`` / ``audio_token_id`` (262145 and 262273 for E4B, also
1609+
mirrored on the sub-configs per the Gemma4 convention); the per-image
1610+
counts are fixed because both towers emit a fixed-size feature map:
1611+
1612+
- ``vision_soft_tokens_per_image``: 256 — a 768x768 image becomes a 16x16
1613+
grid.
1614+
- ``audio_soft_tokens_per_image``: 188.
1615+
1616+
Audio is optional: checkpoints without an ``audio_config`` leave ``audio``
1617+
as ``None`` and the exported package omits the audio encoder.
1618+
"""
1619+
1620+
vision_soft_tokens_per_image: int = 256
1621+
audio_soft_tokens_per_image: int = 188
1622+
1623+
@classmethod
1624+
def from_transformers(cls, config, parent_config=None) -> Gemma3nMultiModalConfig:
1625+
# The HF Gemma3nConfig wraps a text_config while the multimodal token
1626+
# ids and soft-token counts live on the outer config. build() may hand
1627+
# us either one, so resolve in both directions.
1628+
text_config = getattr(config, "text_config", None) or config
1629+
composite = parent_config if parent_config is not None else config
1630+
base = Gemma3nConfig.from_transformers(text_config, composite)
1631+
# audio_token_id is an ArchitectureConfig field that no generic
1632+
# extractor populates for gemma3n (the audio hook puts it on the
1633+
# sub-config); lift it so tasks can read it at the top level.
1634+
if base.audio_token_id is None:
1635+
base = dataclasses.replace(
1636+
base, audio_token_id=getattr(composite, "audio_token_id", None)
1637+
)
1638+
return cls(
1639+
**_shallow_fields(base),
1640+
vision_soft_tokens_per_image=int(
1641+
getattr(composite, "vision_soft_tokens_per_image", 256) or 256
1642+
),
1643+
audio_soft_tokens_per_image=int(
1644+
getattr(composite, "audio_soft_tokens_per_image", 188) or 188
1645+
),
15651646
)
15661647

15671648

‎src/mobius/_configs/_base_test.py‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
"""Unit tests for :class:`ArchitectureConfig.from_transformers`."""
5+
6+
from __future__ import annotations
7+
8+
from mobius._configs._base import ArchitectureConfig
9+
10+
11+
class _FakeHFConfig:
12+
"""Minimal HuggingFace-config stand-in with attribute access."""
13+
14+
def __init__(self, model_type: str = "_unrelated_", **kwargs):
15+
self.model_type = model_type
16+
self.__dict__.update(kwargs)
17+
18+
19+
def test_scalar_intermediate_size_passes_through():
20+
cfg = _FakeHFConfig(
21+
hidden_size=2048,
22+
intermediate_size=8192,
23+
num_attention_heads=8,
24+
num_hidden_layers=4,
25+
vocab_size=256,
26+
)
27+
out = ArchitectureConfig.from_transformers(cfg)
28+
assert out.intermediate_size == 8192
29+
30+
31+
def test_list_intermediate_size_collapses_to_first_element():
32+
"""Gemma 3n expresses intermediate_size as a per-layer list.
33+
34+
The list is uniform in every shipped checkpoint, so collapsing to the
35+
first element yields the correct scalar MLP width. Without the coercion
36+
the list reached ``nn.Parameter``/``ir.Shape`` as a dim and raised.
37+
"""
38+
cfg = _FakeHFConfig(
39+
hidden_size=2048,
40+
intermediate_size=[8192] * 4,
41+
num_attention_heads=8,
42+
num_hidden_layers=4,
43+
vocab_size=256,
44+
)
45+
out = ArchitectureConfig.from_transformers(cfg)
46+
assert out.intermediate_size == 8192
47+
assert isinstance(out.intermediate_size, int)

‎src/mobius/_configs/_extractors_test.py‎

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,3 +343,154 @@ def test_hunyuan_vl_mot_image_token_id_survives_default_hook(loaded_vision_hooks
343343
out = _extractors.extract_vision_config(cfg, None, "hunyuan_vl_mot")
344344
assert out["vision"].image_token_id == 12
345345
assert out.get("image_token_id") == 12
346+
347+
348+
# ---------------------------------------------------------------------------
349+
# Gemma 3n hooks (MobileNet-V5 vision tower + USM Conformer audio tower)
350+
# ---------------------------------------------------------------------------
351+
352+
353+
def _gemma3n_hf_config(**overrides):
354+
"""Stand-in for the outer HF ``Gemma3nConfig``, with E4B's real values."""
355+
vision = _FakeHFConfig(
356+
model_type="gemma3n_vision",
357+
architecture="mobilenetv5_300m_enc",
358+
hidden_size=2048,
359+
do_pooling=False,
360+
rms_norm_eps=1e-6,
361+
vocab_offset=262144,
362+
vocab_size=128,
363+
)
364+
audio = _FakeHFConfig(
365+
model_type="gemma3n_audio",
366+
hidden_size=1536,
367+
conf_num_hidden_layers=12,
368+
conf_num_attention_heads=8,
369+
conf_attention_chunk_size=12,
370+
conf_attention_context_left=13,
371+
conf_attention_context_right=0,
372+
conf_attention_logit_cap=50.0,
373+
conf_conv_kernel_size=5,
374+
conf_reduction_factor=4,
375+
conf_residual_weight=0.5,
376+
input_feat_size=128,
377+
sscp_conv_channel_size=[128, 32],
378+
sscp_conv_kernel_size=[[3, 3], [3, 3]],
379+
sscp_conv_stride_size=[[2, 2], [2, 2]],
380+
sscp_conv_group_norm_eps=1e-3,
381+
gradient_clipping=1e10,
382+
rms_norm_eps=1e-6,
383+
vocab_offset=262272,
384+
vocab_size=128,
385+
)
386+
fields = dict(
387+
vision_config=vision,
388+
audio_config=audio,
389+
image_token_id=262145,
390+
audio_token_id=262273,
391+
vision_soft_tokens_per_image=256,
392+
audio_soft_tokens_per_image=188,
393+
)
394+
fields.update(overrides)
395+
return _FakeHFConfig(model_type="gemma3n", **fields)
396+
397+
398+
def test_gemma3n_vision_maps_mobilenet_fields(loaded_vision_hooks):
399+
"""The tower is MobileNet-V5, so the timm spec name and 768x768 are pinned."""
400+
out = _extractors.extract_vision_config(_gemma3n_hf_config(), None, "gemma3n")
401+
vision = out["vision"]
402+
403+
assert vision.model_type == "gemma3n_vision"
404+
assert vision.architecture == "mobilenetv5_300m_enc"
405+
assert vision.hidden_size == 2048
406+
# HF ships no image_size; MobileNet-V5 has no dynamic-resolution path and
407+
# the processor resizes to a fixed 768x768 (16x16 grid = 256 soft tokens).
408+
assert vision.image_size == 768
409+
# Gemma3n needs the spatial feature map, not a pooled vector.
410+
assert vision.do_pooling is False
411+
assert (vision.vocab_offset, vision.vocab_size) == (262144, 128)
412+
assert vision.image_token_id == 262145
413+
assert vision.mm_tokens_per_image == 256
414+
415+
416+
def test_gemma3n_vision_fires_from_text_sub_config(loaded_vision_hooks):
417+
"""build() may resolve to the text sub-config; the parent still drives the hook."""
418+
parent = _gemma3n_hf_config()
419+
text = _FakeHFConfig(model_type="gemma3n_text")
420+
421+
out = _extractors.extract_vision_config(text, parent, "gemma3n_text")
422+
423+
assert out["vision"].architecture == "mobilenetv5_300m_enc"
424+
425+
426+
def test_gemma3n_vision_does_not_fire_for_unrelated_model(loaded_vision_hooks):
427+
"""A gemma3n-shaped vision_config must not leak into another model type.
428+
429+
Regression guard: reading the parent model_type off the
430+
``parent_config or config`` composite (rather than ``parent_config``)
431+
made the hook fire for *any* dispatched model_type as long as the config
432+
itself was a gemma3n one.
433+
"""
434+
out = _extractors.extract_vision_config(_gemma3n_hf_config(), None, "llama")
435+
436+
assert out.get("vision") is None or out["vision"].architecture is None, (
437+
f"gemma3n vision hook fired for model_type='llama': {out}"
438+
)
439+
440+
441+
def test_gemma3n_audio_maps_usm_conformer_fields(loaded_hooks):
442+
"""The USM field names pass through verbatim onto Gemma3nAudioConfig."""
443+
from mobius._configs._sub_configs import Gemma3nAudioConfig
444+
445+
out = _extractors.extract_audio_config(_gemma3n_hf_config(), None, "gemma3n")
446+
audio = out["audio"]
447+
448+
assert isinstance(audio, Gemma3nAudioConfig)
449+
assert audio.hidden_size == 1536
450+
assert audio.conf_num_hidden_layers == 12
451+
assert audio.conf_num_attention_heads == 8
452+
assert audio.conf_attention_chunk_size == 12
453+
assert audio.conf_attention_context_left == 13
454+
assert audio.conf_attention_context_right == 0
455+
assert audio.conf_attention_logit_cap == pytest.approx(50.0)
456+
assert audio.conf_conv_kernel_size == 5
457+
assert audio.conf_reduction_factor == 4
458+
assert audio.conf_residual_weight == pytest.approx(0.5)
459+
assert audio.input_feat_size == 128
460+
assert audio.sscp_conv_channel_size == [128, 32]
461+
assert audio.sscp_conv_kernel_size == [[3, 3], [3, 3]]
462+
assert audio.sscp_conv_stride_size == [[2, 2], [2, 2]]
463+
assert audio.sscp_conv_group_norm_eps == pytest.approx(1e-3)
464+
assert (audio.vocab_offset, audio.vocab_size) == (262272, 128)
465+
assert audio.audio_token_id == 262273
466+
467+
468+
def test_gemma3n_audio_fires_from_text_sub_config(loaded_hooks):
469+
"""Same parent-resolution path as the vision hook."""
470+
parent = _gemma3n_hf_config()
471+
text = _FakeHFConfig(model_type="gemma3n_text")
472+
473+
out = _extractors.extract_audio_config(text, parent, "gemma3n_text")
474+
475+
assert out["audio"].conf_num_hidden_layers == 12
476+
477+
478+
def test_gemma3n_audio_absent_without_audio_config(loaded_hooks):
479+
"""Audio is optional: no audio_config means no audio sub-config."""
480+
cfg = _gemma3n_hf_config(audio_config=None)
481+
482+
assert _extractors.extract_audio_config(cfg, None, "gemma3n") == {}
483+
484+
485+
def test_gemma3n_audio_does_not_fire_for_unrelated_model(loaded_hooks):
486+
"""A gemma3n-shaped audio_config must not leak into another model type.
487+
488+
Same parent-resolution regression guard as the vision hook above.
489+
"""
490+
from mobius._configs._sub_configs import Gemma3nAudioConfig
491+
492+
out = _extractors.extract_audio_config(_gemma3n_hf_config(), None, "llama")
493+
494+
assert not isinstance(out.get("audio"), Gemma3nAudioConfig), (
495+
f"gemma3n audio hook fired for model_type='llama': {out}"
496+
)

0 commit comments

Comments
 (0)