Skip to content

Commit e1781d5

Browse files
justinchubyCopilot
andcommitted
Add vlm_vision_weights helper and adopt it in VLM vision sub-models
The vision sub-models of LLaVA, Gemma3 and Mllama hand-wrote the same preprocess_weights body: filter to the vision-tower prefixes and rename the HF vision MLP projections (mlp.fc1 → mlp.up_proj, mlp.fc2 → mlp.down_proj) to match our FCMLP component naming. Add `vlm_vision_weights(state_dict, prefixes)` to `_weight_utils.py` next to the existing `vlm_decoder_weights` / `vlm_embedding_weights` helpers, and adopt it in those three models. The only per-model difference is the prefix tuple (gemma3/llava use ("vision_tower.", "multi_modal_projector."); mllama uses ("vision_model.",)). Behaviour-preserving. Co-authored-by: Copilot <[email protected]> Signed-off-by: Justin Chu <[email protected]>
1 parent 329d15e commit e1781d5

5 files changed

Lines changed: 90 additions & 30 deletions

File tree

‎src/mobius/_weight_utils.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,39 @@ def vlm_embedding_weights(
474474
return renamed
475475

476476

477+
def vlm_vision_weights(
478+
state_dict: dict[str, torch.Tensor],
479+
prefixes: tuple[str, ...],
480+
) -> dict[str, torch.Tensor]:
481+
"""Extract vision-tower weights for a VLM vision sub-model.
482+
483+
Keeps only keys starting with one of *prefixes* and renames the vision
484+
MLP projections ``mlp.fc1`` → ``mlp.up_proj`` and ``mlp.fc2`` →
485+
``mlp.down_proj`` to match our ``FCMLP`` component naming.
486+
487+
This is the standard pattern for VLM vision sub-models (LLaVA, Gemma3,
488+
Mllama) whose HuggingFace vision encoders use ``fc1``/``fc2`` MLP names.
489+
490+
Args:
491+
state_dict: Full model state dict.
492+
prefixes: Prefixes identifying vision-tower weights to keep, e.g.
493+
``("vision_tower.", "multi_modal_projector.")`` or
494+
``("vision_model.",)``.
495+
496+
Returns:
497+
New dictionary with the kept vision weights and renamed MLP keys.
498+
"""
499+
renamed: dict[str, torch.Tensor] = {}
500+
for key, value in state_dict.items():
501+
if not key.startswith(prefixes):
502+
continue
503+
new_key = key.replace(".mlp.fc1.", ".mlp.up_proj.").replace(
504+
".mlp.fc2.", ".mlp.down_proj."
505+
)
506+
renamed[new_key] = value
507+
return renamed
508+
509+
477510
def _reshape_packed_qweight(value: torch.Tensor, blob_size: int) -> torch.Tensor:
478511
"""Transpose and reshape a packed qweight tensor for MatMulNBits.
479512

‎src/mobius/_weight_utils_test.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
tie_word_embeddings,
2121
vlm_decoder_weights,
2222
vlm_embedding_weights,
23+
vlm_vision_weights,
2324
)
2425

2526

@@ -330,6 +331,44 @@ def test_custom_keyword(self):
330331
assert list(result.keys()) == ["word_embedding.weight"]
331332

332333

334+
class TestVlmVisionWeights:
335+
"""Tests for vlm_vision_weights."""
336+
337+
def test_filters_and_renames(self):
338+
"""Keeps prefixed keys and renames fc1/fc2."""
339+
fc1 = torch.randn(4, 8)
340+
fc2 = torch.randn(8, 4)
341+
sd = {
342+
"vision_tower.encoder.layers.0.mlp.fc1.weight": fc1,
343+
"vision_tower.encoder.layers.0.mlp.fc2.weight": fc2,
344+
"multi_modal_projector.linear.weight": torch.randn(4),
345+
"language_model.model.layers.0.weight": torch.randn(4),
346+
}
347+
result = vlm_vision_weights(sd, ("vision_tower.", "multi_modal_projector."))
348+
assert set(result.keys()) == {
349+
"vision_tower.encoder.layers.0.mlp.up_proj.weight",
350+
"vision_tower.encoder.layers.0.mlp.down_proj.weight",
351+
"multi_modal_projector.linear.weight",
352+
}
353+
assert result["vision_tower.encoder.layers.0.mlp.up_proj.weight"].data_ptr() == (
354+
fc1.data_ptr()
355+
)
356+
357+
def test_single_prefix(self):
358+
"""Works with a single-element prefix tuple."""
359+
sd = {
360+
"vision_model.layers.0.mlp.fc1.weight": torch.randn(2),
361+
"other.weight": torch.randn(2),
362+
}
363+
result = vlm_vision_weights(sd, ("vision_model.",))
364+
assert list(result.keys()) == ["vision_model.layers.0.mlp.up_proj.weight"]
365+
366+
def test_empty_when_no_match(self):
367+
"""Returns empty dict when no key matches the prefixes."""
368+
sd = {"language_model.layers.0.weight": torch.randn(2)}
369+
assert vlm_vision_weights(sd, ("vision_tower.",)) == {}
370+
371+
333372
class TestPreprocessGptqWeights:
334373
"""Tests for GPTQ weight preprocessing.
335374

‎src/mobius/models/gemma3.py‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,11 @@
1818
from onnxscript import OpBuilder, nn
1919

2020
from mobius._configs import ArchitectureConfig
21-
from mobius._weight_utils import vlm_decoder_weights, vlm_embedding_weights
21+
from mobius._weight_utils import (
22+
vlm_decoder_weights,
23+
vlm_embedding_weights,
24+
vlm_vision_weights,
25+
)
2226
from mobius.components import (
2327
Gemma3MultiModalProjector,
2428
Linear,
@@ -93,15 +97,7 @@ def forward(self, op: OpBuilder, pixel_values: ir.Value):
9397
def preprocess_weights(
9498
self, state_dict: dict[str, torch.Tensor]
9599
) -> dict[str, torch.Tensor]:
96-
renamed: dict[str, torch.Tensor] = {}
97-
for key, value in state_dict.items():
98-
if not key.startswith(("vision_tower.", "multi_modal_projector.")):
99-
continue
100-
# VisionModel MLP uses up_proj/down_proj; HF uses fc1/fc2
101-
key = key.replace(".mlp.fc1.", ".mlp.up_proj.")
102-
key = key.replace(".mlp.fc2.", ".mlp.down_proj.")
103-
renamed[key] = value
104-
return renamed
100+
return vlm_vision_weights(state_dict, ("vision_tower.", "multi_modal_projector."))
105101

106102

107103
class _Gemma3EmbeddingModel(nn.Module):

‎src/mobius/models/llava.py‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,11 @@
2727
from onnxscript import OpBuilder, nn
2828

2929
from mobius._configs import ArchitectureConfig
30-
from mobius._weight_utils import vlm_decoder_weights, vlm_embedding_weights
30+
from mobius._weight_utils import (
31+
vlm_decoder_weights,
32+
vlm_embedding_weights,
33+
vlm_vision_weights,
34+
)
3135
from mobius.components import (
3236
Embedding,
3337
Linear,
@@ -92,15 +96,7 @@ def forward(self, op: OpBuilder, pixel_values: ir.Value):
9296
def preprocess_weights(
9397
self, state_dict: dict[str, torch.Tensor]
9498
) -> dict[str, torch.Tensor]:
95-
renamed: dict[str, torch.Tensor] = {}
96-
for key, value in state_dict.items():
97-
if not key.startswith(("vision_tower.", "multi_modal_projector.")):
98-
continue
99-
# VisionModel MLP uses up_proj/down_proj; HF uses fc1/fc2
100-
key = key.replace(".mlp.fc1.", ".mlp.up_proj.")
101-
key = key.replace(".mlp.fc2.", ".mlp.down_proj.")
102-
renamed[key] = value
103-
return renamed
99+
return vlm_vision_weights(state_dict, ("vision_tower.", "multi_modal_projector."))
104100

105101

106102
class _LLaVAEmbeddingModel(nn.Module):

‎src/mobius/models/mllama.py‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,11 @@
2323
from onnxscript import OpBuilder, nn
2424

2525
from mobius._configs import ArchitectureConfig, MllamaConfig
26-
from mobius._weight_utils import vlm_decoder_weights, vlm_embedding_weights
26+
from mobius._weight_utils import (
27+
vlm_decoder_weights,
28+
vlm_embedding_weights,
29+
vlm_vision_weights,
30+
)
2731
from mobius.components import (
2832
MLP,
2933
DecoderLayer,
@@ -317,15 +321,7 @@ def forward(self, op: OpBuilder, pixel_values: ir.Value):
317321
def preprocess_weights(
318322
self, state_dict: dict[str, torch.Tensor]
319323
) -> dict[str, torch.Tensor]:
320-
renamed: dict[str, torch.Tensor] = {}
321-
for key, value in state_dict.items():
322-
if not key.startswith("vision_model."):
323-
continue
324-
# VisionModel MLP uses up_proj/down_proj; HF uses fc1/fc2
325-
key = key.replace(".mlp.fc1.", ".mlp.up_proj.")
326-
key = key.replace(".mlp.fc2.", ".mlp.down_proj.")
327-
renamed[key] = value
328-
return renamed
324+
return vlm_vision_weights(state_dict, ("vision_model.",))
329325

330326

331327
class _MllamaEmbeddingModel(nn.Module):

0 commit comments

Comments
 (0)