Skip to content

Commit 28c0252

Browse files
authored
Merge branch 'main' into asonawane/gemma
2 parents f535aa4 + db0ae40 commit 28c0252

15 files changed

Lines changed: 702 additions & 135 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2525

2626
---
2727

28+
### Qwen3.6-27B Support
29+
30+
#### Added
31+
32+
- Qwen3.6-27B is now supported via the existing `qwen3_5` model type
33+
(`Qwen35VL3ModelCausalLMModel`). Qwen3.6 uses the same architecture as
34+
Qwen3.5 with `tie_word_embeddings=false` and larger dimensions (64
35+
layers, 5120 hidden size). No code changes required — fully config-driven.
36+
2837
### Mistral-3 / Pixtral VLM Support
2938

3039
#### Added

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@ multi-component export for pipelines.
2020

2121
| Category | Examples |
2222
|---|---|
23-
| **Text Generation** | Llama 2/3/4, Mistral, Qwen 2/2.5/3, Phi-3/3.5, Gemma 1/2/3, Granite, GPT-2, OPT, OLMo, SmolLM3, and many more |
23+
| **Text Generation** | Llama 2/3/4, Mistral, Qwen 2/2.5/3/3.5/3.6, Phi-3/3.5, Gemma 1/2/3, Granite, GPT-2, OPT, OLMo, SmolLM3, and many more |
2424
| **Mixture of Experts** | PhiMoE, GPTOSS, Mixtral, OLMoE, DeepSeek-V2/V3, Qwen2-MoE, Qwen3-MoE, Arctic, DBRX, Jamba |
25-
| **Multimodal** | Gemma 3, Phi-3V, Phi-4MM (vision + audio + LoRA), LLaVA, InternVL2, Qwen2.5-VL, Qwen3-VL, Pixtral |
25+
| **Multimodal** | Gemma 3, Phi-3V, Phi-4MM (vision + audio + LoRA), LLaVA, InternVL2, Qwen2.5-VL, Qwen3-VL, Qwen3.5/3.6-VL, Pixtral |
2626
| **Encoder-only** | BERT, RoBERTa, ALBERT, DeBERTa, DistilBERT, ELECTRA, XLNet |
2727
| **Encoder-Decoder** | BART, T5/mT5, Marian, M2M-100, Pegasus, BigBird-Pegasus |
2828
| **Speech-to-Text** | Whisper |

‎docs/model-catalog.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ Standard autoregressive language models using rotary position embeddings.
2828
| `phi3` | `Phi3CausalLMModel` | `microsoft/Phi-3-mini-4k-instruct` |
2929
| `phi3small` | `Phi3SmallCausalLMModel` | `microsoft/Phi-3-small-8k-instruct` |
3030
| `smollm3` | `SmolLM3CausalLMModel` | `HuggingFaceTB/SmolLM3-3B` |
31-
| `qwen3_5_text` | `Qwen35CausalLMModel` | `Qwen/Qwen3.5-VL-32B` |
31+
| `qwen3_5_text` | `Qwen35CausalLMModel` | `Qwen/Qwen3.5-2B` |
3232
| `falcon` | `FalconCausalLMModel` | `tiiuae/falcon-7b` |
3333
| `bloom` | `FalconCausalLMModel` | `bigscience/bloom-560m` |
3434
| `mpt` | `FalconCausalLMModel` | `mosaicml/mpt-7b` |
@@ -116,7 +116,7 @@ Models that process both images and text.
116116
| `qwen2_vl` | `Qwen25VLCausalLMModel` | `qwen-vl` | `Qwen/Qwen2-VL-7B-Instruct` |
117117
| `qwen2_5_vl` | `Qwen25VLCausalLMModel` | `qwen-vl` | `Qwen/Qwen2.5-VL-3B-Instruct` |
118118
| `qwen3_vl` | `Qwen3VL3ModelCausalLMModel` | `qwen-vl` | `Qwen/Qwen3-VL-2B-Instruct` |
119-
| `qwen3_5_vl` | `Qwen35VL3ModelCausalLMModel` | `hybrid-qwen-vl` | — |
119+
| `qwen3_5_vl` | `Qwen35VL3ModelCausalLMModel` | `hybrid-qwen-vl` | `Qwen/Qwen3.5-2B`, `Qwen/Qwen3.6-27B` |
120120
| `gemma3_multimodal` | `Gemma3MultiModalModel` | `vision-language` | `google/gemma-3-4b-it` |
121121
| `mllama` | `MllamaCausalLMModel` | `mllama-vision-language` | `meta-llama/Llama-3.2-11B-Vision` |
122122
| `phi4mm` | `Phi4MMMultiModalModel` | `multimodal` | `microsoft/Phi-4-multimodal-instruct` |

‎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",

‎scripts/generate_golden.py‎

Lines changed: 52 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,25 @@ def _patched_prepare(input_ids, **kwargs):
180180
model.prepare_inputs_for_generation = _patched_prepare
181181

182182

183+
# ---- Device helpers ----
184+
185+
186+
def _get_model_device(model: object, device: str):
187+
"""Return the concrete ``torch.device`` where model inputs should go.
188+
189+
``device_map="auto"`` is valid for ``from_pretrained()`` (it
190+
distributes layers across available GPUs), but ``.to("auto")`` is
191+
not valid for tensors or BatchEncoding objects. When *device* is
192+
``"auto"``, we inspect the model's first parameter to find the
193+
actual device that inputs should be placed on.
194+
"""
195+
import torch
196+
197+
if device == "auto":
198+
return next(model.parameters()).device
199+
return torch.device(device)
200+
201+
183202
# ---- Task-specific generators ----
184203
# Each generator loads a HF model, runs inference, and calls
185204
# save_golden_ref() from golden.py. Heavy imports (torch,
@@ -214,9 +233,10 @@ def _generate_causal_lm(case: TestCase, json_path: Path, device: str) -> None:
214233

215234
_apply_nemotron_h_generate_patch(model)
216235

236+
model_device = _get_model_device(model, device)
217237
with torch.no_grad():
218238
gen_output = model.generate(
219-
torch.from_numpy(input_ids).to(device),
239+
torch.from_numpy(input_ids).to(model_device),
220240
max_new_tokens=case.generation_params.get("max_new_tokens", 20),
221241
do_sample=False,
222242
)
@@ -392,7 +412,14 @@ def _generate_vision_language(case: TestCase, json_path: Path, device: str) -> N
392412
text=prompt_text,
393413
images=images if images else None,
394414
return_tensors="pt",
395-
).to(device)
415+
)
416+
417+
# Normalize the CLI/device-map selection to a concrete runtime device
418+
# before moving any tensors. `device="auto"` is handled by Transformers/
419+
# Accelerate during model loading, but `.to("auto")` is not valid for
420+
# BatchEncoding or Tensor objects.
421+
model_device = _get_model_device(model, device)
422+
processed = processed.to(model_device)
396423

397424
# L4: single forward pass
398425
with torch.no_grad():
@@ -456,16 +483,19 @@ def _generate_speech_to_text(case: TestCase, json_path: Path, device: str) -> No
456483
# Load and preprocess audio
457484
audio_path = Path("testdata") / case.audio[0]
458485
audio_array, sample_rate = librosa.load(str(audio_path), sr=16000)
486+
model_device = _get_model_device(model, device)
459487
processed = processor(audio_array, sampling_rate=sample_rate, return_tensors="pt").to(
460-
device
488+
model_device
461489
)
462490
input_features = processed["input_features"]
463491

464492
# L4: single decoder step with forced decoder start token
465493
decoder_start_id = (
466494
model.config.decoder_start_token_id or model.generation_config.decoder_start_token_id
467495
)
468-
decoder_input_ids = torch.tensor([[decoder_start_id]], dtype=torch.long, device=device)
496+
decoder_input_ids = torch.tensor(
497+
[[decoder_start_id]], dtype=torch.long, device=model_device
498+
)
469499
with torch.no_grad():
470500
outputs = model(
471501
input_features=input_features,
@@ -625,10 +655,16 @@ def _load_speech_language_model(case: TestCase, device: str) -> tuple:
625655
Qwen3ASRForConditionalGeneration,
626656
)
627657

628-
model = Qwen3ASRForConditionalGeneration.from_pretrained(
629-
case.model_id, torch_dtype=torch.float32
630-
)
631-
model = model.to(device).eval()
658+
if device == "auto":
659+
model = Qwen3ASRForConditionalGeneration.from_pretrained(
660+
case.model_id, torch_dtype=torch.float32, device_map=device
661+
)
662+
else:
663+
model = Qwen3ASRForConditionalGeneration.from_pretrained(
664+
case.model_id, torch_dtype=torch.float32
665+
)
666+
model = model.to(device)
667+
model.eval()
632668
processor = transformers.AutoProcessor.from_pretrained(
633669
case.model_id, trust_remote_code=True
634670
)
@@ -684,11 +720,12 @@ def _prepare_speech_language_inputs(
684720
if case.prompts:
685721
force_prefix = case.prompts[0]
686722
text_prompt = text_prompt + force_prefix
723+
model_device = _get_model_device(model, device)
687724
processed = processor(
688725
text=text_prompt,
689726
audio=[audio_array],
690727
return_tensors="pt",
691-
).to(device)
728+
).to(model_device)
692729
prompt_for_golden = force_prefix or str(audio_path)
693730
else:
694731
# Gemma4-style: text prompt + audio
@@ -702,11 +739,12 @@ def _prepare_speech_language_inputs(
702739
prompt_text = processor.apply_chat_template(
703740
messages, tokenize=False, add_generation_prompt=True
704741
)
742+
model_device = _get_model_device(model, device)
705743
processed = processor(
706744
text=prompt_text,
707745
audio=[audio_array],
708746
return_tensors="pt",
709-
).to(device)
747+
).to(model_device)
710748
prompt_for_golden = case.prompts[0]
711749

712750
return processed, prompt_for_golden
@@ -1047,7 +1085,8 @@ def _generate_phi4mm_multimodal(case: TestCase, json_path: Path, device: str) ->
10471085
call_kwargs["audios"] = audios
10481086
call_kwargs["return_tensors"] = "pt"
10491087

1050-
processed = processor(**call_kwargs).to(device)
1088+
model_device = _get_model_device(model, device)
1089+
processed = processor(**call_kwargs).to(model_device)
10511090

10521091
# L4: single forward pass for prefill logits
10531092
with torch.no_grad():
@@ -1087,13 +1126,13 @@ def _generate_phi4mm_multimodal(case: TestCase, json_path: Path, device: str) ->
10871126
1,
10881127
kv_len + 1,
10891128
dtype=torch.long,
1090-
device=device,
1129+
device=model_device,
10911130
),
10921131
)
10931132
next_id = int(out.logits[0, -1, :].argmax())
10941133
past_kv = out.past_key_values
10951134
gen_ids.append(next_id)
1096-
cur_input_ids = torch.tensor([[next_id]], dtype=torch.long, device=device)
1135+
cur_input_ids = torch.tensor([[next_id]], dtype=torch.long, device=model_device)
10971136
# Stop on EOS
10981137
eos = getattr(model.config, "eos_token_id", None)
10991138
if eos is not None and next_id == eos:

‎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

0 commit comments

Comments
 (0)