Skip to content

Commit f853cd6

Browse files
authored
Merge branch 'main' into justinchu/docs-skills-update
2 parents ef81d1b + 3e99081 commit f853cd6

11 files changed

Lines changed: 262 additions & 127 deletions

File tree

‎src/mobius/_weight_utils.py‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
import logging
1818
import math
19+
from collections.abc import Sequence
1920

2021
import torch
2122

@@ -271,6 +272,52 @@ def rename_mlp_projections(
271272
)
272273

273274

275+
def rename_weight_keys(
276+
state_dict: dict[str, torch.Tensor],
277+
replacements: Sequence[tuple[str, str]],
278+
) -> dict[str, torch.Tensor]:
279+
"""Apply ordered substring replacements to every key in a state dict.
280+
281+
Centralises the ``for name, tensor in state_dict.items(): name =
282+
name.replace(...)`` rename loop that is duplicated across many model
283+
``preprocess_weights`` implementations. Each ``(old, new)`` pair is
284+
applied with :py:meth:`str.replace` to the *progressively updated* key,
285+
so the replacements are **ordered** and may cascade (the output of an
286+
earlier replacement can match the input of a later one) — this matches
287+
the semantics of the hand-written loops it replaces. Use substrings
288+
specific enough (e.g. dot-delimited like ``".attention_layernorm."``)
289+
to avoid renaming unintended portions of a key.
290+
291+
Tensor values are shared with *state_dict* (not cloned), matching the
292+
behaviour of the loops this replaces.
293+
294+
Args:
295+
state_dict: Weight dictionary to transform (not modified).
296+
replacements: Ordered sequence of ``(old, new)`` substring pairs.
297+
298+
Returns:
299+
A new dictionary with renamed keys.
300+
301+
Raises:
302+
ValueError: If two distinct source keys map to the same renamed key
303+
(a collision that would otherwise silently drop a tensor).
304+
"""
305+
result: dict[str, torch.Tensor] = {}
306+
producers: dict[str, str] = {}
307+
for name, tensor in state_dict.items():
308+
new_name = name
309+
for old, new in replacements:
310+
new_name = new_name.replace(old, new)
311+
if new_name in result:
312+
raise ValueError(
313+
f"Weight key collision after rename: {name!r} -> {new_name!r} "
314+
f"(already produced by {producers[new_name]!r})"
315+
)
316+
result[new_name] = tensor
317+
producers[new_name] = name
318+
return result
319+
320+
274321
def split_codegen_qkv(
275322
weight: torch.Tensor,
276323
num_heads: int,
@@ -474,6 +521,39 @@ def vlm_embedding_weights(
474521
return renamed
475522

476523

524+
def vlm_vision_weights(
525+
state_dict: dict[str, torch.Tensor],
526+
prefixes: tuple[str, ...],
527+
) -> dict[str, torch.Tensor]:
528+
"""Extract vision-tower weights for a VLM vision sub-model.
529+
530+
Keeps only keys starting with one of *prefixes* and renames the vision
531+
MLP projections ``mlp.fc1`` → ``mlp.up_proj`` and ``mlp.fc2`` →
532+
``mlp.down_proj`` to match our ``FCMLP`` component naming.
533+
534+
This is the standard pattern for VLM vision sub-models (LLaVA, Gemma3,
535+
Mllama) whose HuggingFace vision encoders use ``fc1``/``fc2`` MLP names.
536+
537+
Args:
538+
state_dict: Full model state dict.
539+
prefixes: Prefixes identifying vision-tower weights to keep, e.g.
540+
``("vision_tower.", "multi_modal_projector.")`` or
541+
``("vision_model.",)``.
542+
543+
Returns:
544+
New dictionary with the kept vision weights and renamed MLP keys.
545+
"""
546+
renamed: dict[str, torch.Tensor] = {}
547+
for key, value in state_dict.items():
548+
if not key.startswith(prefixes):
549+
continue
550+
new_key = key.replace(".mlp.fc1.", ".mlp.up_proj.").replace(
551+
".mlp.fc2.", ".mlp.down_proj."
552+
)
553+
renamed[new_key] = value
554+
return renamed
555+
556+
477557
def _reshape_packed_qweight(value: torch.Tensor, blob_size: int) -> torch.Tensor:
478558
"""Transpose and reshape a packed qweight tensor for MatMulNBits.
479559

‎src/mobius/_weight_utils_test.py‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
merge_lora_weights,
1313
preprocess_awq_weights,
1414
preprocess_gptq_weights,
15+
rename_weight_keys,
1516
split_codegen_qkv,
1617
split_fused_qkv,
1718
split_gate_up_proj,
@@ -20,6 +21,7 @@
2021
tie_word_embeddings,
2122
vlm_decoder_weights,
2223
vlm_embedding_weights,
24+
vlm_vision_weights,
2325
)
2426

2527

@@ -169,6 +171,71 @@ def test_preserves_tensor_values(self):
169171
assert result["key"].data_ptr() == t.data_ptr()
170172

171173

174+
class TestRenameWeightKeys:
175+
"""Tests for rename_weight_keys."""
176+
177+
def test_applies_replacements(self):
178+
"""Each (old, new) pair is applied to every key."""
179+
state_dict = {
180+
"model.layers.0.attention_layernorm.weight": torch.tensor(1.0),
181+
"model.layers.0.feedforward_layernorm.weight": torch.tensor(2.0),
182+
"model.embed.weight": torch.tensor(3.0),
183+
}
184+
result = rename_weight_keys(
185+
state_dict,
186+
[
187+
(".attention_layernorm.", ".input_layernorm."),
188+
(".feedforward_layernorm.", ".post_attention_layernorm."),
189+
],
190+
)
191+
assert set(result.keys()) == {
192+
"model.layers.0.input_layernorm.weight",
193+
"model.layers.0.post_attention_layernorm.weight",
194+
"model.embed.weight",
195+
}
196+
197+
def test_replacements_are_ordered_and_cascade(self):
198+
"""Replacements apply to the progressively updated key, in order."""
199+
state_dict = {"a.weight": torch.tensor(1.0)}
200+
result = rename_weight_keys(state_dict, [("a.", "b."), ("b.", "c.")])
201+
assert list(result.keys()) == ["c.weight"]
202+
203+
def test_no_replacements_is_identity(self):
204+
"""An empty replacement list returns a key-equivalent copy."""
205+
state_dict = {"x.weight": torch.tensor(1.0)}
206+
result = rename_weight_keys(state_dict, [])
207+
assert list(result.keys()) == ["x.weight"]
208+
assert result is not state_dict
209+
210+
def test_shares_tensor_values(self):
211+
"""Tensor values are shared, not cloned."""
212+
t = torch.randn(2, 3)
213+
result = rename_weight_keys({"old.k": t}, [("old.", "new.")])
214+
assert result["new.k"].data_ptr() == t.data_ptr()
215+
216+
def test_collision_raises(self):
217+
"""Two source keys mapping to the same renamed key raises.
218+
219+
The error message must name both the colliding key and the original
220+
producer key to aid debugging in large checkpoints.
221+
"""
222+
state_dict = {
223+
"a.weight": torch.tensor(1.0),
224+
"b.weight": torch.tensor(2.0),
225+
}
226+
with pytest.raises(ValueError, match="collision") as exc_info:
227+
rename_weight_keys(state_dict, [("a.", "x."), ("b.", "x.")])
228+
message = str(exc_info.value)
229+
# The producer ("a.weight", processed first) and the colliding key
230+
# ("b.weight") must both appear.
231+
assert "a.weight" in message
232+
assert "b.weight" in message
233+
234+
def test_empty_state_dict(self):
235+
"""Empty input returns empty output."""
236+
assert rename_weight_keys({}, [("a", "b")]) == {}
237+
238+
172239
class TestSplitFusedQkvValidation:
173240
"""Tests for QKV dimension mismatch detection."""
174241

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

332399

400+
class TestVlmVisionWeights:
401+
"""Tests for vlm_vision_weights."""
402+
403+
def test_filters_and_renames(self):
404+
"""Keeps prefixed keys and renames fc1/fc2."""
405+
fc1 = torch.randn(4, 8)
406+
fc2 = torch.randn(8, 4)
407+
sd = {
408+
"vision_tower.encoder.layers.0.mlp.fc1.weight": fc1,
409+
"vision_tower.encoder.layers.0.mlp.fc2.weight": fc2,
410+
"multi_modal_projector.linear.weight": torch.randn(4),
411+
"language_model.model.layers.0.weight": torch.randn(4),
412+
}
413+
result = vlm_vision_weights(sd, ("vision_tower.", "multi_modal_projector."))
414+
assert set(result.keys()) == {
415+
"vision_tower.encoder.layers.0.mlp.up_proj.weight",
416+
"vision_tower.encoder.layers.0.mlp.down_proj.weight",
417+
"multi_modal_projector.linear.weight",
418+
}
419+
assert result["vision_tower.encoder.layers.0.mlp.up_proj.weight"].data_ptr() == (
420+
fc1.data_ptr()
421+
)
422+
423+
def test_single_prefix(self):
424+
"""Works with a single-element prefix tuple."""
425+
sd = {
426+
"vision_model.layers.0.mlp.fc1.weight": torch.randn(2),
427+
"other.weight": torch.randn(2),
428+
}
429+
result = vlm_vision_weights(sd, ("vision_model.",))
430+
assert list(result.keys()) == ["vision_model.layers.0.mlp.up_proj.weight"]
431+
432+
def test_empty_when_no_match(self):
433+
"""Returns empty dict when no key matches the prefixes."""
434+
sd = {"language_model.layers.0.weight": torch.randn(2)}
435+
assert vlm_vision_weights(sd, ("vision_tower.",)) == {}
436+
437+
333438
class TestPreprocessGptqWeights:
334439
"""Tests for GPTQ weight preprocessing.
335440

‎src/mobius/models/chatglm.py‎

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
import torch
77

8+
from mobius._weight_utils import rename_weight_keys
89
from mobius.models.base import CausalLMModel
910

1011

@@ -19,16 +20,14 @@ def preprocess_weights(
1920
self, state_dict: dict[str, torch.Tensor]
2021
) -> dict[str, torch.Tensor]:
2122
state_dict = super().preprocess_weights(state_dict)
22-
for key in list(state_dict.keys()):
23-
# Map ChatGLM MLP attribute names
24-
if "dense_4h_to_h" in key:
25-
new_key = key.replace("dense_4h_to_h", "down_proj")
26-
state_dict[new_key] = state_dict.pop(key)
27-
elif "dense_h_to_4h" in key:
28-
new_key = key.replace("dense_h_to_4h", "up_proj")
29-
state_dict[new_key] = state_dict.pop(key)
30-
# Map ChatGLM attention attribute names
31-
if "self_attention" in key:
32-
new_key = key.replace("self_attention", "self_attn")
33-
state_dict[new_key] = state_dict.pop(key)
34-
return state_dict
23+
# ChatGLM uses HF-specific attribute names:
24+
# dense_h_to_4h / dense_4h_to_h → up_proj / down_proj (FCMLP naming)
25+
# self_attention → self_attn
26+
return rename_weight_keys(
27+
state_dict,
28+
[
29+
("dense_4h_to_h", "down_proj"),
30+
("dense_h_to_4h", "up_proj"),
31+
("self_attention", "self_attn"),
32+
],
33+
)

‎src/mobius/models/cogvideox.py‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
from onnxscript import OpBuilder, nn
2929

3030
from mobius._diffusers_configs import CogVideoXConfig
31+
from mobius._weight_utils import rename_weight_keys
3132
from mobius.components import LayerNorm as _LayerNorm
3233
from mobius.components import Linear as _Linear
3334
from mobius.components._activations import SiLU as _SiLU
@@ -648,9 +649,10 @@ def preprocess_weights(
648649
- ``ff.net.0.proj.*`` → ``ff.gelu_proj.*``
649650
- ``ff.net.2.*`` → ``ff.linear_out.*``
650651
"""
651-
new_state_dict: dict[str, torch.Tensor] = {}
652-
for name, tensor in state_dict.items():
653-
name = name.replace(".ff.net.0.proj.", ".ff.gelu_proj.")
654-
name = name.replace(".ff.net.2.", ".ff.linear_out.")
655-
new_state_dict[name] = tensor
656-
return new_state_dict
652+
return rename_weight_keys(
653+
state_dict,
654+
[
655+
(".ff.net.0.proj.", ".ff.gelu_proj."),
656+
(".ff.net.2.", ".ff.linear_out."),
657+
],
658+
)

‎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/hunyuan_dit.py‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
import torch
3333
from onnxscript import OpBuilder, nn
3434

35+
from mobius._weight_utils import rename_weight_keys
3536
from mobius.components import LayerNorm as _LayerNorm
3637
from mobius.components import Linear as _Linear
3738
from mobius.components import SiLU as _SiLU
@@ -577,13 +578,14 @@ def preprocess_weights(
577578
- blocks.{i}.ff.net.2 → blocks.{i}.ff.linear_out
578579
- time_extra_emb.timestep_embedder → time_embed (simplified)
579580
"""
580-
new_state_dict: dict[str, torch.Tensor] = {}
581-
for key, value in state_dict.items():
582-
new_key = key
583-
# GEGLU FFN renames
584-
new_key = new_key.replace(".ff.net.0.proj.", ".ff.geglu.proj.")
585-
new_key = new_key.replace(".ff.net.2.", ".ff.linear_out.")
586-
# Timestep embedding (simplified from HF's combined embedding)
587-
new_key = new_key.replace("time_extra_emb.timestep_embedder.", "time_embed.")
588-
new_state_dict[new_key] = value
581+
new_state_dict: dict[str, torch.Tensor] = rename_weight_keys(
582+
state_dict,
583+
[
584+
# GEGLU FFN renames
585+
(".ff.net.0.proj.", ".ff.geglu.proj."),
586+
(".ff.net.2.", ".ff.linear_out."),
587+
# Timestep embedding (simplified from HF's combined embedding)
588+
("time_extra_emb.timestep_embedder.", "time_embed."),
589+
],
590+
)
589591
return new_state_dict

‎src/mobius/models/hunyuan_v1.py‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import torch
2020

2121
from mobius._configs import ArchitectureConfig
22+
from mobius._weight_utils import rename_weight_keys
2223
from mobius.models.base import CausalLMModel
2324

2425

@@ -42,9 +43,10 @@ def preprocess_weights(
4243
state_dict = super().preprocess_weights(state_dict)
4344
# HF uses .query_layernorm. / .key_layernorm.;
4445
# ONNX Attention uses .q_norm. / .k_norm.
45-
return {
46-
k.replace(".query_layernorm.", ".q_norm.").replace(
47-
".key_layernorm.", ".k_norm."
48-
): v
49-
for k, v in state_dict.items()
50-
}
46+
return rename_weight_keys(
47+
state_dict,
48+
[
49+
(".query_layernorm.", ".q_norm."),
50+
(".key_layernorm.", ".k_norm."),
51+
],
52+
)

0 commit comments

Comments
 (0)