Skip to content

Commit a8e4ca2

Browse files
justinchubyCopilot
andauthored
fix: integration test failures and add CUDA device support (#221)
## Summary Fix integration test failures in `tests/integration_test.py` and add CUDA device support via `MOBIUS_TEST_DEVICE` env var. ## Changes ### Key Fixes - **ModelPackage key rename** (PR #205 follow-up): Update `"vision"` → `"vision_encoder"` in 5 test assertions and 2 print statements - **ViT weight name mapping** (`vit.py`): Fix DINOv2 (`fc1`/`fc2`, `norm1`/`norm2`), BeiT (`pooler.layernorm`), and SAM (`lin1`/`lin2`) weight mappings ### Test Skips (with reasons) - **HF transformers incompatibilities**: phi3.5-mini (DynamicCache removed), qwen35_deltanet (Qwen3_5DynamicCache import) - **Missing packages**: phi-tiny-moe (flash_attn), QwenImageVAE (diffusers via importorskip) - **Unavailable models**: wav2vec2-base, hubert-base (404 no safetensors) - **Unsupported features**: DINOv2/BeiT (layer_scale), SAM (4D SkipLayerNorm), bloom (weight tying), qwen3_next (CausalConvWithState custom op), gemma4 bf16 (mixed types) - **Too slow**: qwen-moe-2.7b (>300s timeout) - **Encoder issues**: roberta-base (position offset; dedicated test exists), albert-base (embedding_size≠hidden_size) ### CUDA Device Support - Added `_get_test_device()` helper reading `MOBIUS_TEST_DEVICE` env var - Updated `TestForwardNumerical`, `TestGreedyGeneration`, `TestEncoderOnlyForward`, and `TestVisionForward` to pass device to `OnnxModelSession` ## Testing - `build_graph_test.py`: 1182 passed, 40 skipped ✅ - `src/` unit tests: 1397 passed ✅ - Lint: clean ✅ - Integration fast tests: 58 passed, 22 skipped (previously 14 failed) --------- Signed-off-by: Justin Chu <[email protected]> Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot <[email protected]>
1 parent c96f52a commit a8e4ca2

8 files changed

Lines changed: 524 additions & 114 deletions

File tree

‎pyproject.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ transformers = ["transformers", "safetensors"]
3232
gguf = ["gguf>=0.10.0"]
3333
testing = [
3434
"accelerate",
35+
"diffusers",
3536
"onnxruntime-easy>=0.1.1",
3637
"torch",
3738
"transformers>=5.0",

‎src/mobius/components/_sam_vision.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -511,3 +511,43 @@ def forward(self, op: builder.OpBuilder, pixel_values: ir.Value):
511511
x = self.net_3(op, x) # (B, 896, 16, 16)
512512

513513
return x
514+
515+
516+
def preprocess_sam_encoder_weights(
517+
hf_state_dict: dict[str, object],
518+
) -> dict[str, object]:
519+
"""Map HuggingFace SamVisionEncoder weight names to SAMVisionEncoder names.
520+
521+
HF → ONNX mappings:
522+
- patch_embed.projection.* → patch_embed.proj.*
523+
- layers.N.layer_norm1.* → blocks.N.norm1.*
524+
- layers.N.layer_norm2.* → blocks.N.norm2.*
525+
- layers.N.attn.* → blocks.N.attn.* (sublayer names match)
526+
- layers.N.mlp.* → blocks.N.mlp.* (sublayer names match)
527+
- neck.conv1.* → neck.0.*
528+
- neck.layer_norm1.* → neck.1.*
529+
- neck.conv2.* → neck.2.*
530+
- neck.layer_norm2.* → neck.3.*
531+
- mlp.lin1.* → mlp.up_proj.*
532+
- mlp.lin2.* → mlp.down_proj.*
533+
"""
534+
renamed = {}
535+
for key, value in hf_state_dict.items():
536+
new_key = key
537+
# patch_embed.projection → patch_embed.proj (our nn.Parameter)
538+
new_key = new_key.replace("patch_embed.projection.", "patch_embed.proj.")
539+
# Neck conv/layernorm to indexed (BEFORE generic layer_norm)
540+
new_key = new_key.replace("neck.conv1.", "neck.0.")
541+
new_key = new_key.replace("neck.layer_norm1.", "neck.1.")
542+
new_key = new_key.replace("neck.conv2.", "neck.2.")
543+
new_key = new_key.replace("neck.layer_norm2.", "neck.3.")
544+
# layers → blocks
545+
new_key = new_key.replace("layers.", "blocks.")
546+
# Block-level: layer_norm1 → norm1, layer_norm2 → norm2
547+
new_key = new_key.replace(".layer_norm1.", ".norm1.")
548+
new_key = new_key.replace(".layer_norm2.", ".norm2.")
549+
# MLP: HF lin1/lin2 → ONNX FCMLP up_proj/down_proj
550+
new_key = new_key.replace(".mlp.lin1.", ".mlp.up_proj.")
551+
new_key = new_key.replace(".mlp.lin2.", ".mlp.down_proj.")
552+
renamed[new_key] = value
553+
return renamed
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
"""Unit tests for SAM vision encoder weight rename logic."""
5+
6+
from __future__ import annotations
7+
8+
from mobius.components._sam_vision import preprocess_sam_encoder_weights
9+
10+
11+
class TestPreprocessSamEncoderWeights:
12+
"""Test preprocess_sam_encoder_weights with fake state dicts."""
13+
14+
def test_patch_embed_projection(self):
15+
sd = {"patch_embed.projection.weight": "w"}
16+
result = preprocess_sam_encoder_weights(sd)
17+
assert "patch_embed.proj.weight" in result
18+
19+
def test_neck_conv1_to_indexed(self):
20+
sd = {"neck.conv1.weight": "w"}
21+
result = preprocess_sam_encoder_weights(sd)
22+
assert "neck.0.weight" in result
23+
24+
def test_neck_layer_norm1_to_indexed(self):
25+
sd = {"neck.layer_norm1.weight": "w", "neck.layer_norm1.bias": "b"}
26+
result = preprocess_sam_encoder_weights(sd)
27+
assert "neck.1.weight" in result
28+
assert "neck.1.bias" in result
29+
30+
def test_neck_conv2_to_indexed(self):
31+
sd = {"neck.conv2.weight": "w"}
32+
result = preprocess_sam_encoder_weights(sd)
33+
assert "neck.2.weight" in result
34+
35+
def test_neck_layer_norm2_to_indexed(self):
36+
sd = {"neck.layer_norm2.weight": "w"}
37+
result = preprocess_sam_encoder_weights(sd)
38+
assert "neck.3.weight" in result
39+
40+
def test_layers_to_blocks(self):
41+
sd = {"layers.0.attn.q_proj.weight": "w"}
42+
result = preprocess_sam_encoder_weights(sd)
43+
assert "blocks.0.attn.q_proj.weight" in result
44+
45+
def test_layer_norm1_to_norm1(self):
46+
sd = {"layers.0.layer_norm1.weight": "w"}
47+
result = preprocess_sam_encoder_weights(sd)
48+
assert "blocks.0.norm1.weight" in result
49+
50+
def test_layer_norm2_to_norm2(self):
51+
sd = {"layers.1.layer_norm2.bias": "b"}
52+
result = preprocess_sam_encoder_weights(sd)
53+
assert "blocks.1.norm2.bias" in result
54+
55+
def test_mlp_lin1_to_up_proj(self):
56+
sd = {"layers.0.mlp.lin1.weight": "w"}
57+
result = preprocess_sam_encoder_weights(sd)
58+
assert "blocks.0.mlp.up_proj.weight" in result
59+
60+
def test_mlp_lin2_to_down_proj(self):
61+
sd = {"layers.0.mlp.lin2.bias": "b"}
62+
result = preprocess_sam_encoder_weights(sd)
63+
assert "blocks.0.mlp.down_proj.bias" in result
64+
65+
def test_full_state_dict_roundtrip(self):
66+
"""All keys in a typical SAM state dict get renamed."""
67+
fake_sd = {
68+
"patch_embed.projection.weight": "w",
69+
"patch_embed.projection.bias": "b",
70+
"layers.0.layer_norm1.weight": "w",
71+
"layers.0.layer_norm1.bias": "b",
72+
"layers.0.attn.q_proj.weight": "w",
73+
"layers.0.attn.k_proj.weight": "w",
74+
"layers.0.attn.v_proj.weight": "w",
75+
"layers.0.attn.proj.weight": "w",
76+
"layers.0.layer_norm2.weight": "w",
77+
"layers.0.mlp.lin1.weight": "w",
78+
"layers.0.mlp.lin2.weight": "w",
79+
"neck.conv1.weight": "w",
80+
"neck.layer_norm1.weight": "w",
81+
"neck.layer_norm1.bias": "b",
82+
"neck.conv2.weight": "w",
83+
"neck.layer_norm2.weight": "w",
84+
"neck.layer_norm2.bias": "b",
85+
"pos_embed": "pe",
86+
}
87+
result = preprocess_sam_encoder_weights(fake_sd)
88+
expected_keys = {
89+
"patch_embed.proj.weight",
90+
"patch_embed.proj.bias",
91+
"blocks.0.norm1.weight",
92+
"blocks.0.norm1.bias",
93+
"blocks.0.attn.q_proj.weight",
94+
"blocks.0.attn.k_proj.weight",
95+
"blocks.0.attn.v_proj.weight",
96+
"blocks.0.attn.proj.weight",
97+
"blocks.0.norm2.weight",
98+
"blocks.0.mlp.up_proj.weight",
99+
"blocks.0.mlp.down_proj.weight",
100+
"neck.0.weight",
101+
"neck.1.weight",
102+
"neck.1.bias",
103+
"neck.2.weight",
104+
"neck.3.weight",
105+
"neck.3.bias",
106+
"pos_embed",
107+
}
108+
assert set(result.keys()) == expected_keys

‎src/mobius/models/falcon.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -617,6 +617,10 @@ def __init__(self, config: ArchitectureConfig):
617617
config = dataclasses.replace(config, alibi=True)
618618
super().__init__(config)
619619
self.transformer = _BloomTextModel(config)
620+
# Re-tie lm_head after overriding self.transformer; the parent's
621+
# __init__ tied lm_head to the old _FalconTextModel's embeddings.
622+
if config.tie_word_embeddings:
623+
self.lm_head.weight = self.transformer.word_embeddings.weight
620624

621625
def preprocess_weights(
622626
self, state_dict: dict[str, torch.Tensor]

‎src/mobius/models/gemma4.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1600,7 +1600,10 @@ def forward(
16001600
logits = self.lm_head(op, hidden_states)
16011601
# Optional final logit soft-capping (tanh scaled): logit_cap * tanh(x / logit_cap)
16021602
if self.config.final_logit_softcapping:
1603-
cap = float(self.config.final_logit_softcapping)
1603+
cap = op.CastLike(
1604+
self.config.final_logit_softcapping,
1605+
logits,
1606+
)
16041607
logits = op.Mul(op.Tanh(op.Div(logits, cap)), cap)
16051608
return logits, present_key_values
16061609

@@ -1691,7 +1694,10 @@ def forward(
16911694
logits = self.lm_head(op, hidden_states)
16921695
# Gemma4 applies final logit soft-capping: logit_cap * tanh(x / logit_cap)
16931696
if self.config.final_logit_softcapping:
1694-
cap = float(self.config.final_logit_softcapping)
1697+
cap = op.CastLike(
1698+
self.config.final_logit_softcapping,
1699+
logits,
1700+
)
16951701
logits = op.Mul(op.Tanh(op.Div(logits, cap)), cap)
16961702
return logits, present_key_values
16971703

‎src/mobius/models/vit.py‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,11 @@ def _rename_vit_weight(name: str) -> str | None:
188188
):
189189
name = after
190190

191-
# Skip pooler and classifier heads
191+
# Skip most pooler/classifier weights, but keep pooler.layernorm
192+
# (BeiT uses pooler.layernorm as the final layernorm)
193+
if name.startswith("pooler.layernorm."):
194+
suffix = name[len("pooler.layernorm.") :]
195+
return f"layernorm.{suffix}"
192196
if name.startswith(("pooler.", "classifier.")):
193197
return None
194198

@@ -197,6 +201,9 @@ def _rename_vit_weight(name: str) -> str | None:
197201
return "embeddings.cls_token"
198202
if name == "embeddings.position_embeddings":
199203
return "embeddings.position_embeddings"
204+
# DINOv2 mask_token: used during pre-training only; not needed for inference
205+
if name == "embeddings.mask_token":
206+
return None
200207
if name.startswith("embeddings.patch_embeddings.projection."):
201208
suffix = name[len("embeddings.patch_embeddings.projection.") :]
202209
return f"embeddings.patch_embeddings.projection.{suffix}"
@@ -212,6 +219,30 @@ def _rename_vit_weight(name: str) -> str | None:
212219
# layernorm_before / layernorm_after pass through
213220
if suffix.startswith("layernorm_"):
214221
return f"encoder.layer.{layer_idx}.{suffix}"
222+
# DINOv2/DeiT-style norm1/norm2 → layernorm_before/layernorm_after
223+
if suffix.startswith("norm1"):
224+
remainder = suffix[len("norm1") :]
225+
return f"encoder.layer.{layer_idx}.layernorm_before{remainder}"
226+
if suffix.startswith("norm2"):
227+
remainder = suffix[len("norm2") :]
228+
return f"encoder.layer.{layer_idx}.layernorm_after{remainder}"
229+
# DINOv2-style MLP: fc1 → up_proj, fc2 → down_proj
230+
if suffix.startswith("mlp.fc1"):
231+
remainder = suffix[len("mlp.fc1") :]
232+
return f"encoder.layer.{layer_idx}.mlp.up_proj{remainder}"
233+
if suffix.startswith("mlp.fc2"):
234+
remainder = suffix[len("mlp.fc2") :]
235+
return f"encoder.layer.{layer_idx}.mlp.down_proj{remainder}"
236+
# DINOv2 layer_scale: layer_scale1/layer_scale2 (skip — not
237+
# used in our ViT implementation)
238+
if suffix.startswith("layer_scale"):
239+
return None
240+
# BeiT lambda_1/lambda_2 (layer scale — not implemented)
241+
if suffix in ("lambda_1", "lambda_2"):
242+
return None
243+
# BeiT relative_position_bias (not implemented in base ViT)
244+
if "relative_position_bias" in suffix:
245+
return None
215246
for old, new in _VIT_LAYER_RENAMES.items():
216247
if suffix.startswith(old):
217248
remainder = suffix[len(old) :]

0 commit comments

Comments
 (0)