diff --git a/Qwen-Qwen3.5-35B-A3B/LICENSE b/Qwen-Qwen3.5-35B-A3B/LICENSE new file mode 100644 index 00000000..8c6d46e0 --- /dev/null +++ b/Qwen-Qwen3.5-35B-A3B/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Alibaba Cloud + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Qwen-Qwen3.5-35B-A3B/builtin/README.md b/Qwen-Qwen3.5-35B-A3B/builtin/README.md new file mode 100644 index 00000000..a51f188d --- /dev/null +++ b/Qwen-Qwen3.5-35B-A3B/builtin/README.md @@ -0,0 +1,90 @@ +# Qwen3.5-35B-A3B MoE ONNX Runtime GenAI Example + +This example demonstrates how to convert [Qwen/Qwen3.5-35B-A3B](https://huggingface.co/Qwen/Qwen3.5-35B-A3B) Mixture-of-Experts vision-language model to ONNX format using Olive and run inference with ONNX Runtime GenAI. + +Qwen3.5-35B-A3B is a hybrid MoE model with 256 experts (8 routed + 1 shared per layer), GatedDeltaNet linear attention, and a Qwen3.5 vision encoder. The pipeline exports three sub-models (vision encoder, text embedding, text decoder), applies graph optimizations, and quantizes the text decoder to INT4. + +## Prerequisites + +```bash +pip install olive-ai onnxruntime-genai transformers torch safetensors +``` + +## Steps + +### 1. Export & Optimize Models (CPU) + +```bash +# INT4 text decoder + FP32 vision/embedding (recommended) +python optimize.py --config-dir cpu_and_mobile --device cpu + +# Regenerate configs only (models already exported) +python optimize.py --config-dir cpu_and_mobile --device cpu --skip-export +``` + +| Command | Description | +|---------|-------------| +| `python optimize.py --config-dir cpu_and_mobile --device cpu` | Full pipeline: export, optimize, INT4 quantize | +| `python optimize.py --config-dir cpu_and_mobile --skip-export` | Regenerate configs only (models already exported) | +| `python optimize.py --config-dir cpu_and_mobile --context-length 8192` | Export with custom context length | + +> **Note:** The text decoder is exported as INT4 via ModelBuilder with 256 MoE experts using QMoE symmetric blockwise quantization. The vision encoder and embedding model are exported as FP32 via Olive's OnnxConversion pass with graph surgeries (PackedAttentionToLoopMHA, GemmToMatMulAdd). + +### 2. Run Inference + +```bash +# Text-only prompt +python inference.py --prompt "What is 2+2?" + +# With an image +python inference.py --prompt "Describe this image" --image photo.jpg + +# Interactive mode +python inference.py --interactive +``` + +## Architecture + +Qwen3.5-35B-A3B is a `Qwen3_5MoeForConditionalGeneration` multimodal model with three components: + +``` +Image [B, C, H, W] + | + v +vision.onnx (Qwen3.5 vision encoder) + | + v image_features [num_patches, hidden] + | + +--- input_ids [B, seq_len] ---> embedding.onnx (embed_tokens + scatter) + | + v inputs_embeds [B, seq_len, 2048] + | + +---> text.onnx (40 hybrid layers: GatedDeltaNet + MoE) + | + v logits -> tokens +``` + +- **Vision**: Qwen3.5 vision encoder processes images into patch features. +- **Embedding**: Looks up token embeddings and scatters vision features into image-token positions. +- **Text**: 40 hybrid decoder layers alternating between GatedDeltaNet linear attention and full attention, each with a MoE MLP (256 experts, top-8 routing + shared expert with sigmoid gating). + +## Directory Structure + +``` +Qwen-Qwen3.5-35B-A3B/ +├── LICENSE +└── builtin/ + ├── optimize.py # End-to-end Olive pipeline + GenAI config generation + ├── user_script.py # Olive callbacks: model loading, dummy inputs, IO configs + ├── inference.py # ONNX Runtime GenAI inference + ├── info.yml # Recipe metadata + ├── README.md + ├── codes/ + │ ├── __init__.py + │ └── modeling_qwen3_5_moe.py # Custom ONNX-export-friendly MoE model + └── cpu_and_mobile/ + ├── text.json # Olive config: ModelBuilder INT4 (QMoE) + ├── embedding.json # Olive config: OnnxConversion + graph surgeries + ├── vision.json # Olive config: Dynamo export + graph surgeries + └── models/ # Exported ONNX models (generated) +``` diff --git a/Qwen-Qwen3.5-35B-A3B/builtin/codes/__init__.py b/Qwen-Qwen3.5-35B-A3B/builtin/codes/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/Qwen-Qwen3.5-35B-A3B/builtin/codes/modeling_qwen3_5_moe.py b/Qwen-Qwen3.5-35B-A3B/builtin/codes/modeling_qwen3_5_moe.py new file mode 100644 index 00000000..50a7424e --- /dev/null +++ b/Qwen-Qwen3.5-35B-A3B/builtin/codes/modeling_qwen3_5_moe.py @@ -0,0 +1,502 @@ +# Copyright 2025 The Qwen Team and The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Self-contained ONNX-export-friendly Qwen3.5-MoE model. +# Vision encoder is identical to non-MoE Qwen3.5. MoE text components are +# included for completeness but the text decoder is exported via OGA ModelBuilder. +# Used by user_script.py for vision and embedding ONNX export. +# ------------------------------------------------------------------------- +# Copyright (C) 2026 Advanced Micro Devices, Inc. All rights reserved. +# Portions of this file consist of AI generated content. +# -------------------------------------------------------------------------- +# SPDX-License-Identifier: Apache-2.0 +# -------------------------------------------------------------------------- + + +from typing import Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from transformers.activations import ACT2FN +from transformers.modeling_layers import GradientCheckpointingLayer +from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel +from transformers.utils import auto_docstring, logging + +try: + from transformers.models.qwen3_5_moe.configuration_qwen3_5_moe import ( + Qwen3_5MoeConfig, + Qwen3_5MoeVisionConfig, + Qwen3_5MoeTextConfig, + ) +except ImportError: + from transformers import AutoConfig + Qwen3_5MoeConfig = AutoConfig + Qwen3_5MoeVisionConfig = None + Qwen3_5MoeTextConfig = None + +logger = logging.get_logger(__name__) + + +# ═══════════════════════════════════════════════════════════════ +# Vision encoder components (identical to non-MoE Qwen3.5) +# ═══════════════════════════════════════════════════════════════ + + +class VisionMLP(nn.Module): + def __init__(self, config): + super().__init__() + self.linear_fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=True) + self.linear_fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=True) + self.act_fn = ACT2FN[config.hidden_act] + + def forward(self, hidden_state): + return self.linear_fc2(self.act_fn(self.linear_fc1(hidden_state))) + + +class VisionPatchEmbed(nn.Module): + def __init__(self, config) -> None: + super().__init__() + self.patch_size = config.patch_size + self.temporal_patch_size = config.temporal_patch_size + self.in_channels = config.in_channels + self.embed_dim = config.hidden_size + kernel_size = [self.temporal_patch_size, self.patch_size, self.patch_size] + self.proj = nn.Conv3d(self.in_channels, self.embed_dim, kernel_size=kernel_size, stride=kernel_size, bias=True) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + target_dtype = self.proj.weight.dtype + hidden_states = hidden_states.view( + -1, self.in_channels, self.temporal_patch_size, self.patch_size, self.patch_size + ) + hidden_states = self.proj(hidden_states.to(dtype=target_dtype)).view(-1, self.embed_dim) + return hidden_states + + +class VisionRotaryEmbedding(nn.Module): + inv_freq: torch.Tensor + + def __init__(self, dim: int, theta: float = 10000.0) -> None: + super().__init__() + inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim)) + self.register_buffer("inv_freq", inv_freq, persistent=True) + + def forward(self, seqlen) -> torch.Tensor: + seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype) + freqs = torch.outer(seq, self.inv_freq) + return freqs + + +class VisionPatchMerger(nn.Module): + def __init__(self, config, use_postshuffle_norm=False) -> None: + super().__init__() + self.hidden_size = config.hidden_size * (config.spatial_merge_size ** 2) + self.use_postshuffle_norm = use_postshuffle_norm + self.norm = nn.LayerNorm(self.hidden_size if use_postshuffle_norm else config.hidden_size, eps=1e-6) + self.linear_fc1 = nn.Linear(self.hidden_size, self.hidden_size) + self.act_fn = nn.GELU() + self.linear_fc2 = nn.Linear(self.hidden_size, config.out_hidden_size) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.norm(x.view(-1, self.hidden_size) if self.use_postshuffle_norm else x).view(-1, self.hidden_size) + x = self.linear_fc2(self.act_fn(self.linear_fc1(x))) + return x + + +def rotate_half(x): + x1 = x[..., : x.shape[-1] // 2] + x2 = x[..., x.shape[-1] // 2:] + return torch.cat((-x2, x1), dim=-1) + + +def apply_rotary_pos_emb_vision(q, k, cos, sin): + orig_q_dtype, orig_k_dtype = q.dtype, k.dtype + q, k = q.float(), k.float() + cos, sin = cos.unsqueeze(-2).float(), sin.unsqueeze(-2).float() + q_embed = (q * cos) + (rotate_half(q) * sin) + k_embed = (k * cos) + (rotate_half(k) * sin) + return q_embed.to(orig_q_dtype), k_embed.to(orig_k_dtype) + + +def repeat_kv(hidden_states, n_rep): + batch, num_kv_heads, slen, head_dim = hidden_states.shape + if n_rep == 1: + return hidden_states + return hidden_states[:, :, None, :, :].expand(batch, num_kv_heads, n_rep, slen, head_dim).reshape( + batch, num_kv_heads * n_rep, slen, head_dim + ) + + +def eager_attention_forward(module, query, key, value, attention_mask, scaling, dropout=0.0, **kwargs): + key_states = repeat_kv(key, module.num_key_value_groups) + value_states = repeat_kv(value, module.num_key_value_groups) + attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling + if attention_mask is not None: + attn_weights = attn_weights + attention_mask[:, :, :, :key_states.shape[-2]] + attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype) + attn_weights = F.dropout(attn_weights, p=dropout, training=module.training) + attn_output = torch.matmul(attn_weights, value_states) + return attn_output.transpose(1, 2).contiguous(), attn_weights + + +class VisionAttention(nn.Module): + def __init__(self, config) -> None: + super().__init__() + self.dim = config.hidden_size + self.num_heads = config.num_heads + self.head_dim = self.dim // self.num_heads + self.num_key_value_groups = 1 + self.qkv = nn.Linear(self.dim, self.dim * 3, bias=True) + self.proj = nn.Linear(self.dim, self.dim) + self.scaling = self.head_dim ** -0.5 + self.config = config + self.attention_dropout = 0.0 + self.is_causal = False + + def forward(self, hidden_states, cu_seqlens, rotary_pos_emb=None, position_embeddings=None, **kwargs): + seq_length = hidden_states.shape[0] + q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0) + cos, sin = position_embeddings + q, k = apply_rotary_pos_emb_vision(q, k, cos, sin) + + q = q.transpose(0, 1).unsqueeze(0) + k = k.transpose(0, 1).unsqueeze(0) + v = v.transpose(0, 1).unsqueeze(0) + + attention_interface = eager_attention_forward + if self.config._attn_implementation != "eager": + attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] + + if getattr(torch.compiler, "is_exporting", lambda: False)(): + attn_output = torch.onnx.ops.symbolic( + "custom::PackedAttention", + (q, k, v, cu_seqlens), + dict(scale=self.scaling, num_heads=self.num_heads), + dtype=q.dtype, shape=(q.shape[0], q.shape[2], q.shape[1], q.shape[3]), version=1, + ).to(self.proj.weight.device) + else: + lengths = cu_seqlens[1:] - cu_seqlens[:-1] + splits = [torch.split(t, lengths.tolist(), dim=2) for t in (q, k, v)] + attn_outputs = [] + for qi, ki, vi in zip(*splits): + out = F.scaled_dot_product_attention(qi, ki, vi, attn_mask=None, dropout_p=0.0, scale=self.scaling, is_causal=False) + attn_outputs.append(out.transpose(1, 2)) + attn_output = torch.cat(attn_outputs, dim=1) + + attn_output = attn_output.reshape(seq_length, -1).contiguous() + return self.proj(attn_output) + + +class VisionBlock(GradientCheckpointingLayer): + def __init__(self, config) -> None: + super().__init__() + self.norm1 = nn.LayerNorm(config.hidden_size, eps=1e-6) + self.norm2 = nn.LayerNorm(config.hidden_size, eps=1e-6) + self.attn = VisionAttention(config=config) + self.mlp = VisionMLP(config=config) + + def forward(self, hidden_states, cu_seqlens, rotary_pos_emb=None, position_embeddings=None, **kwargs): + hidden_states = hidden_states + self.attn(self.norm1(hidden_states), cu_seqlens=cu_seqlens, + rotary_pos_emb=rotary_pos_emb, position_embeddings=position_embeddings, **kwargs) + hidden_states = hidden_states + self.mlp(self.norm2(hidden_states)) + return hidden_states + + +# ═══════════════════════════════════════════════════════════════ +# Vision model +# ═══════════════════════════════════════════════════════════════ + + +@auto_docstring +class Qwen3_5MoePreTrainedModel(PreTrainedModel): + config_class = Qwen3_5MoeConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["VisionBlock"] + _skip_keys_device_placement = "past_key_values" + _supports_sdpa = True + _supports_attention_backend = True + + +class Qwen3_5MoeVisionModel(Qwen3_5MoePreTrainedModel): + _no_split_modules = ["VisionBlock"] + + def __init__(self, config, *inputs, **kwargs) -> None: + super().__init__(config, *inputs, **kwargs) + self.spatial_merge_size = config.spatial_merge_size + self.patch_size = config.patch_size + self.spatial_merge_unit = self.spatial_merge_size * self.spatial_merge_size + + self.patch_embed = VisionPatchEmbed(config=config) + self.pos_embed = nn.Embedding(config.num_position_embeddings, config.hidden_size) + self.num_grid_per_side = int(config.num_position_embeddings ** 0.5) + + head_dim = config.hidden_size // config.num_heads + self.rotary_pos_emb = VisionRotaryEmbedding(head_dim // 2) + + self.blocks = nn.ModuleList([VisionBlock(config) for _ in range(config.depth)]) + self.merger = VisionPatchMerger(config=config, use_postshuffle_norm=False) + + self.deepstack_visual_indexes = config.deepstack_visual_indexes + self.deepstack_merger_list = nn.ModuleList( + [VisionPatchMerger(config=config, use_postshuffle_norm=True) for _ in range(len(config.deepstack_visual_indexes))] + ) + self.gradient_checkpointing = False + + def rot_pos_emb(self, grid_thw): + merge_size = self.spatial_merge_size + max_hw = grid_thw[:, 1:].max() + freq_table = self.rotary_pos_emb(max_hw) + device = freq_table.device + + all_embeddings = [] + for num_frames, height, width in grid_thw: + merged_h, merged_w = height // merge_size, width // merge_size + torch._check(merged_h.item() >= 1) + torch._check(merged_w.item() >= 1) + torch._check(num_frames.item() >= 1) + + block_rows = torch.arange(merged_h, device=device) + block_cols = torch.arange(merged_w, device=device) + intra_row = torch.arange(merge_size, device=device) + intra_col = torch.arange(merge_size, device=device) + + row_idx = (block_rows[:, None, None, None] * merge_size + intra_row[None, None, :, None]).expand( + merged_h, merged_w, merge_size, merge_size + ).reshape(-1) + col_idx = (block_cols[None, :, None, None] * merge_size + intra_col[None, None, None, :]).expand( + merged_h, merged_w, merge_size, merge_size + ).reshape(-1) + + coords = torch.stack((row_idx, col_idx), dim=-1) + coords = coords.repeat(num_frames, 1) + all_embeddings.append(freq_table[coords].flatten(1)) + + return torch.cat(all_embeddings, dim=0) + + def fast_pos_embed_interpolate(self, grid_thw): + merge_size = self.config.spatial_merge_size + dev = self.pos_embed.weight.device + dtype = self.pos_embed.weight.dtype + n = self.num_grid_per_side + + all_pos_embeds = [] + for t, h, w in zip(grid_thw[:, 0], grid_thw[:, 1], grid_thw[:, 2]): + torch._check(t.item() >= 1) + torch._check(h.item() >= 2) + torch._check(w.item() >= 2) + + h_idxs = torch.arange(h, dtype=torch.float32, device=dev) * ((n - 1) / (h - 1)) + w_idxs = torch.arange(w, dtype=torch.float32, device=dev) * ((n - 1) / (w - 1)) + + h_floor, w_floor = h_idxs.int(), w_idxs.int() + h_ceil = (h_floor + 1).clamp(max=n - 1) + w_ceil = (w_floor + 1).clamp(max=n - 1) + dh = (h_idxs - h_floor.float()).to(dtype) + dw = (w_idxs - w_floor.float()).to(dtype) + + base_h = h_floor.long() * n + base_hc = h_ceil.long() * n + idx_00 = (base_h[:, None] + w_floor.long()[None]).reshape(-1) + idx_01 = (base_h[:, None] + w_ceil.long()[None]).reshape(-1) + idx_10 = (base_hc[:, None] + w_floor.long()[None]).reshape(-1) + idx_11 = (base_hc[:, None] + w_ceil.long()[None]).reshape(-1) + + wt_00 = ((1.0 - dh)[:, None] * (1.0 - dw)[None]).reshape(-1) + wt_01 = ((1.0 - dh)[:, None] * dw[None]).reshape(-1) + wt_10 = (dh[:, None] * (1.0 - dw)[None]).reshape(-1) + wt_11 = (dh[:, None] * dw[None]).reshape(-1) + + pos = ( + self.pos_embed(idx_00.to(dev)) * wt_00[:, None] + + self.pos_embed(idx_01.to(dev)) * wt_01[:, None] + + self.pos_embed(idx_10.to(dev)) * wt_10[:, None] + + self.pos_embed(idx_11.to(dev)) * wt_11[:, None] + ) + pos = pos.repeat(t, 1) + pos = pos.reshape(t, h // merge_size, merge_size, w // merge_size, merge_size, -1).permute(0, 1, 3, 2, 4, 5).flatten(0, 4) + all_pos_embeds.append(pos) + + return torch.cat(all_pos_embeds) + + def forward(self, hidden_states, grid_thw, **kwargs): + hidden_states = self.patch_embed(hidden_states) + pos_embeds = self.fast_pos_embed_interpolate(grid_thw) + hidden_states = hidden_states + pos_embeds + + rotary_pos_emb = self.rot_pos_emb(grid_thw) + seq_len, _ = hidden_states.size() + hidden_states = hidden_states.reshape(seq_len, -1) + rotary_pos_emb = rotary_pos_emb.reshape(seq_len, -1) + emb = torch.cat((rotary_pos_emb, rotary_pos_emb), dim=-1) + position_embeddings = (emb.cos(), emb.sin()) + + cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum( + dim=0, dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32, + ) + cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0) + + for blk in self.blocks: + hidden_states = blk(hidden_states, cu_seqlens=cu_seqlens, position_embeddings=position_embeddings, **kwargs) + + hidden_states = self.merger(hidden_states) + return hidden_states + + +# ═══════════════════════════════════════════════════════════════ +# MoE text components (for completeness; text decoder exported via OGA) +# ═══════════════════════════════════════════════════════════════ + + +class Qwen3_5MoeRMSNorm(nn.Module): + def __init__(self, hidden_size, eps=1e-6): + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + self.eps = eps + + def forward(self, hidden_states): + input_dtype = hidden_states.dtype + hidden_states = hidden_states.to(torch.float32) + variance = hidden_states.pow(2).mean(-1, keepdim=True) + hidden_states = hidden_states * torch.rsqrt(variance + self.eps) + return (1 + self.weight) * hidden_states.to(input_dtype) + + +class Qwen3_5MoeMLP(nn.Module): + """Dense SwiGLU MLP (used for shared expert).""" + def __init__(self, hidden_size, intermediate_size, hidden_act="silu"): + super().__init__() + self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False) + self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False) + self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False) + self.act_fn = ACT2FN[hidden_act] + + def forward(self, x): + return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) + + +class Qwen3_5MoeTopKRouter(nn.Module): + def __init__(self, num_experts, hidden_size, num_experts_per_tok): + super().__init__() + self.top_k = num_experts_per_tok + self.num_experts = num_experts + self.weight = nn.Parameter(torch.zeros(num_experts, hidden_size)) + + def forward(self, hidden_states): + hidden_states = hidden_states.reshape(-1, hidden_states.shape[-1]) + router_logits = F.linear(hidden_states, self.weight) + router_probs = F.softmax(router_logits, dtype=torch.float, dim=-1) + top_values, top_indices = torch.topk(router_probs, self.top_k, dim=-1) + top_values = top_values / top_values.sum(dim=-1, keepdim=True) + return router_logits, top_values.to(router_logits.dtype), top_indices + + +class Qwen3_5MoeExperts(nn.Module): + """Packed expert weights: gate_up_proj [E, 2*inter, hidden], down_proj [E, hidden, inter].""" + def __init__(self, num_experts, hidden_size, intermediate_size, hidden_act="silu"): + super().__init__() + self.num_experts = num_experts + self.gate_up_proj = nn.Parameter(torch.empty(num_experts, 2 * intermediate_size, hidden_size)) + self.down_proj = nn.Parameter(torch.empty(num_experts, hidden_size, intermediate_size)) + self.act_fn = ACT2FN[hidden_act] + + def forward(self, hidden_states, top_k_index, top_k_weights): + final = torch.zeros_like(hidden_states) + expert_mask = F.one_hot(top_k_index, num_classes=self.num_experts).permute(2, 1, 0) + expert_hit = (expert_mask.sum(dim=(-1, -2)) > 0).nonzero() + + for eidx in expert_hit: + eidx = eidx[0] + top_k_pos, token_idx = torch.where(expert_mask[eidx]) + current = hidden_states[token_idx] + gate, up = F.linear(current, self.gate_up_proj[eidx]).chunk(2, dim=-1) + out = F.linear(self.act_fn(gate) * up, self.down_proj[eidx]) + final.index_add_(0, token_idx, (out * top_k_weights[token_idx, top_k_pos, None]).to(final.dtype)) + return final + + +class Qwen3_5MoeSparseMoeBlock(nn.Module): + """Full MoE block: router + routed experts + shared expert + shared gate.""" + def __init__(self, config): + super().__init__() + self.gate = Qwen3_5MoeTopKRouter(config.num_experts, config.hidden_size, config.num_experts_per_tok) + self.experts = Qwen3_5MoeExperts(config.num_experts, config.hidden_size, config.moe_intermediate_size, config.hidden_act) + self.shared_expert = Qwen3_5MoeMLP(config.hidden_size, config.shared_expert_intermediate_size, config.hidden_act) + self.shared_expert_gate = nn.Linear(config.hidden_size, 1, bias=False) + + def forward(self, hidden_states): + batch_size, seq_len, hidden_dim = hidden_states.shape + flat = hidden_states.view(-1, hidden_dim) + shared_out = self.shared_expert(flat) + _, routing_weights, selected_experts = self.gate(flat) + expert_out = self.experts(flat, selected_experts, routing_weights) + shared_out = torch.sigmoid(self.shared_expert_gate(flat)) * shared_out + return (expert_out + shared_out).reshape(batch_size, seq_len, hidden_dim) + + +# ═══════════════════════════════════════════════════════════════ +# Top-level Qwen3.5-MoE model (vision + embedding shell) +# ═══════════════════════════════════════════════════════════════ + + +class Qwen3_5MoeModel(Qwen3_5MoePreTrainedModel): + """Qwen3.5-MoE composite model for vision + embedding ONNX export. + + The text decoder (with MoE + GatedDeltaNet) is exported via OGA ModelBuilder. + This class provides: + - get_image_features(): vision encoder export + - get_fused_input_embeddings(): embedding fusion export + """ + base_model_prefix = "" + _checkpoint_conversion_mapping = {} + _no_split_modules = ["VisionBlock"] + + def __init__(self, config): + super().__init__(config) + self.visual = Qwen3_5MoeVisionModel._from_config(config.vision_config) + text_config = config.text_config + self.embed_tokens = nn.Embedding(text_config.vocab_size, text_config.hidden_size) + self.post_init() + + def get_input_embeddings(self): + return self.embed_tokens + + def get_image_features(self, pixel_values, image_grid_thw=None): + pixel_values = pixel_values.type(self.visual.dtype) + image_embeds = self.visual(pixel_values, grid_thw=image_grid_thw) + split_sizes = (image_grid_thw.prod(-1) // self.visual.spatial_merge_size ** 2).tolist() + return torch.split(image_embeds, split_sizes) + + def get_fused_input_embeddings(self, input_ids, image_features=None): + mask = input_ids == self.config.image_token_id + safe_ids = torch.where(mask, torch.zeros_like(input_ids), input_ids) + inputs_embeds = self.embed_tokens(safe_ids) + if image_features is not None: + mask_3d = mask.unsqueeze(-1).expand_as(inputs_embeds) + image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype) + inputs_embeds = inputs_embeds.masked_scatter(mask_3d, image_features) + return inputs_embeds + + def forward(self, *args, **kwargs): + raise NotImplementedError( + "Qwen3_5MoeModel.forward() should not be called directly. " + "Use get_image_features() or get_fused_input_embeddings() via method swap." + ) + + +__all__ = [ + "Qwen3_5MoeModel", + "Qwen3_5MoePreTrainedModel", + "Qwen3_5MoeVisionModel", + "Qwen3_5MoeSparseMoeBlock", + "Qwen3_5MoeExperts", + "Qwen3_5MoeTopKRouter", + "Qwen3_5MoeMLP", + "Qwen3_5MoeRMSNorm", +] diff --git a/Qwen-Qwen3.5-35B-A3B/builtin/cpu_and_mobile/embedding.json b/Qwen-Qwen3.5-35B-A3B/builtin/cpu_and_mobile/embedding.json new file mode 100644 index 00000000..cac39ef5 --- /dev/null +++ b/Qwen-Qwen3.5-35B-A3B/builtin/cpu_and_mobile/embedding.json @@ -0,0 +1,42 @@ +{ + "input_model": { + "type": "PyTorchModel", + "model_path": "Qwen/Qwen3.5-35B-A3B", + "model_loader": "get_embedding_model", + "model_script": "user_script.py", + "io_config": "get_embedding_io_config", + "dummy_inputs_func": "get_embedding_dummy_inputs" + }, + "passes": { + "convert": { + "type": "OnnxConversion", + "use_dynamo_exporter": false + }, + "ort": { + "type": "OrtTransformersOptimization", + "model_type": "", + "opt_level": 1, + "only_onnxruntime": true + }, + "cast": { + "type": "OnnxPeepholeOptimizer", + "onnxscript_optimize": false, + "onnxoptimizer_optimize": false, + "fuse_reshape_operations": false, + "fix_com_microsoft_opset": true, + "cast_chain_elimination": true + }, + "gemm2mm": { + "type": "GraphSurgeries", + "surgeries": [ + { + "surgeon": "GemmToMatMulAdd" + } + ], + "save_as_external_data": true, + "external_data_name": "embedding.onnx.data" + } + }, + "no_artifacts": true, + "output_dir": "cpu_and_mobile/models/embedding.onnx" +} diff --git a/Qwen-Qwen3.5-35B-A3B/builtin/cpu_and_mobile/text.json b/Qwen-Qwen3.5-35B-A3B/builtin/cpu_and_mobile/text.json new file mode 100644 index 00000000..4cd6077c --- /dev/null +++ b/Qwen-Qwen3.5-35B-A3B/builtin/cpu_and_mobile/text.json @@ -0,0 +1,19 @@ +{ + "input_model": { + "type": "HfModel", + "model_path": "Qwen/Qwen3.5-35B-A3B" + }, + "passes": { + "m": { + "type": "ModelBuilder", + "precision": "int4", + "int4_block_size": 128, + "int4_accuracy_level": 4, + "extra_options": { + "filename": "text.onnx" + } + } + }, + "no_artifacts": true, + "output_dir": "cpu_and_mobile/models/text.onnx" +} diff --git a/Qwen-Qwen3.5-35B-A3B/builtin/cpu_and_mobile/vision.json b/Qwen-Qwen3.5-35B-A3B/builtin/cpu_and_mobile/vision.json new file mode 100644 index 00000000..9f6f7067 --- /dev/null +++ b/Qwen-Qwen3.5-35B-A3B/builtin/cpu_and_mobile/vision.json @@ -0,0 +1,56 @@ +{ + "input_model": { + "type": "PyTorchModel", + "model_path": "Qwen/Qwen3.5-35B-A3B", + "model_loader": "get_vision_model", + "model_script": "user_script.py", + "io_config": "get_vision_io_config", + "dummy_inputs_func": "get_vision_dummy_inputs" + }, + "passes": { + "c": { + "type": "OnnxConversion", + "use_dynamo_exporter": true + }, + "gs": { + "type": "GraphSurgeries", + "surgeries": [ + { + "surgeon": "PackedAttentionToLoopMHA" + }, + { + "surgeon": "RenameOutputDims", + "output_idx": 0, + "dim_idx": 0, + "dim_name": "num_logical_patches" + } + ] + }, + "ort": { + "type": "OrtTransformersOptimization", + "model_type": "", + "opt_level": 1, + "only_onnxruntime": true + }, + "cast": { + "type": "OnnxPeepholeOptimizer", + "onnxscript_optimize": false, + "onnxoptimizer_optimize": false, + "fuse_reshape_operations": false, + "fix_com_microsoft_opset": true, + "cast_chain_elimination": true + }, + "gs2": { + "type": "GraphSurgeries", + "surgeries": [ + { + "surgeon": "GemmToMatMulAdd" + } + ], + "save_as_external_data": true, + "external_data_name": "vision.onnx.data" + } + }, + "no_artifacts": true, + "output_dir": "cpu_and_mobile/models/vision.onnx" +} diff --git a/Qwen-Qwen3.5-35B-A3B/builtin/inference.py b/Qwen-Qwen3.5-35B-A3B/builtin/inference.py new file mode 100644 index 00000000..963632fa --- /dev/null +++ b/Qwen-Qwen3.5-35B-A3B/builtin/inference.py @@ -0,0 +1,338 @@ +# ------------------------------------------------------------------------- +# Copyright (C) 2026 Advanced Micro Devices, Inc. All rights reserved. +# Portions of this file consist of AI generated content. +# -------------------------------------------------------------------------- +# SPDX-License-Identifier: MIT +# -------------------------------------------------------------------------- +"""ONNX Runtime GenAI inference for Qwen3.5-35B-A3B MoE VLM. + +Usage: + python inference.py --prompt "What is 2+2?" + python inference.py --image photo.jpg --prompt "Describe this image" + python inference.py --interactive + python inference.py --benchmark D:/test-images --verbose + python inference.py --benchmark D:/test-images --pytorch_model Qwen/Qwen3.5-35B-A3B + python inference.py --model_path cuda/models --prompt "Hello" +""" + +import argparse +import json +import os +import time + +import onnxruntime_genai as og + +IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".bmp", ".gif", ".webp", ".tiff"} + + +def main(): + parser = argparse.ArgumentParser( + description="ONNX Runtime GenAI inference for Qwen3.5-35B-A3B MoE VLM" + ) + parser.add_argument( + "--model_path", type=str, default="cpu_and_mobile/models", + help="Path to the model directory containing genai_config.json and ONNX models", + ) + parser.add_argument("--image", type=str, default=None, help="Path to image file") + parser.add_argument("--prompt", type=str, default=None, help="Text prompt") + parser.add_argument( + "--max_length", type=int, default=4096, + help="Maximum total tokens (prompt + generated)", + ) + parser.add_argument("--interactive", action="store_true", help="Run in interactive mode") + parser.add_argument( + "--benchmark", type=str, default=None, + help="Path to a folder of images. Runs inference on each and reports avg TPS/TTFT.", + ) + parser.add_argument( + "--benchmark_prompt", type=str, default="Describe this image in detail.", + help="Prompt used for each image in benchmark mode", + ) + parser.add_argument( + "--pytorch_model", type=str, default=None, + help="HuggingFace model ID for PyTorch comparison (e.g. Qwen/Qwen3.5-35B-A3B)", + ) + parser.add_argument("--verbose", action="store_true", help="Print generated text in benchmark mode") + args = parser.parse_args() + + print(f"Loading model from: {args.model_path}") + model = og.Model(args.model_path) + processor = model.create_multimodal_processor() + tokenizer = og.Tokenizer(model) + tokenizer_stream = processor.create_stream() + + if args.benchmark: + benchmark_folder(model, processor, tokenizer, tokenizer_stream, args) + elif args.interactive: + interactive_mode(model, processor, tokenizer, tokenizer_stream, args) + elif args.prompt: + generate_response(model, processor, tokenizer, tokenizer_stream, args.prompt, args.image, args.max_length) + else: + print("Please provide --prompt, --interactive, or --benchmark ") + parser.print_help() + + +def generate_response(model, processor, tokenizer, tokenizer_stream, prompt, image_path, max_length=4096, quiet=False): + """Run a single generation. Returns (text, token_count, ttft, tps).""" + images = None + if image_path: + if not quiet: + print(f"Loading image: {image_path}") + images = og.Images.open(image_path) + messages = [ + { + "role": "user", + "content": [ + {"type": "image"}, + {"type": "text", "text": prompt}, + ], + } + ] + else: + messages = [ + { + "role": "user", + "content": prompt, + } + ] + + full_prompt = tokenizer.apply_chat_template(json.dumps(messages), add_generation_prompt=True) + + if not quiet: + print(f"\nPrompt: {prompt}") + if image_path: + print(f"Image: {image_path}") + print("\nGenerating response...") + + inputs = processor(full_prompt, images=images) + + params = og.GeneratorParams(model) + params.set_search_options(max_length=max_length) + + generator = og.Generator(model, params) + generator.set_inputs(inputs) + + token_count = 0 + ttft = None + tokens = [] + t_start = time.perf_counter() + + if not quiet: + print("\nResponse: ", end="", flush=True) + while not generator.is_done(): + generator.generate_next_token() + if ttft is None: + ttft = time.perf_counter() - t_start + token_count += 1 + new_token = generator.get_next_tokens()[0] + tokens.append(new_token) + if not quiet: + print(tokenizer_stream.decode(new_token), end="", flush=True) + + t_total = time.perf_counter() - t_start + if not quiet: + print() + del generator + + text = tokenizer.decode(tokens) + + decode_tokens = max(token_count - 1, 1) + decode_time = t_total - (ttft or 0) + tps = decode_tokens / decode_time if decode_time > 0 else 0 + + if not quiet: + print(f"\n Tokens generated : {token_count}") + print(f" TTFT : {ttft * 1000:.1f} ms") + print(f" Decode TPS : {tps:.1f} tokens/sec") + print(f" Total time : {t_total:.2f} s") + + return text, token_count, ttft or 0, tps + + +def benchmark_folder(model, processor, tokenizer, tokenizer_stream, args): + """Run inference on every image in a folder and report avg TPS/TTFT.""" + folder = args.benchmark + prompt = args.benchmark_prompt + max_length = args.max_length + verbose = args.verbose + + image_files = sorted( + os.path.join(folder, f) + for f in os.listdir(folder) + if os.path.splitext(f)[1].lower() in IMAGE_EXTENSIONS + ) + if not image_files: + print(f"No images found in {folder}") + return + + print(f"\nBenchmark: {len(image_files)} images from {folder}") + print(f"Prompt : {prompt}") + print(f"{'=' * 70}") + + onnx_results = _run_benchmark( + image_files, prompt, max_length, verbose, + lambda img, p, ml: generate_response(model, processor, tokenizer, tokenizer_stream, p, img, ml, quiet=not verbose), + label="ONNX", + ) + + pt_results = None + if args.pytorch_model: + pt_model, pt_proc, device = _build_pytorch_runner(args.pytorch_model) + pt_results = _run_benchmark( + image_files, prompt, max_length, verbose, + lambda img, p, ml: _run_pytorch(pt_model, pt_proc, device, p, img, ml), + label="PyTorch", + ) + + print(f"\n{'=' * 70}") + print(f" BENCHMARK SUMMARY ({len(image_files)} images)") + print(f"{'=' * 70}") + _print_summary(onnx_results, "ONNX") + if pt_results: + _print_summary(pt_results, f"PyTorch ({args.pytorch_model})") + + avg_onnx_tps = sum(onnx_results["tps"]) / len(onnx_results["tps"]) if onnx_results["tps"] else 0 + if pt_results and pt_results["tps"] and avg_onnx_tps: + avg_pt_tps = sum(pt_results["tps"]) / len(pt_results["tps"]) + print(f"\n ONNX / PyTorch TPS speedup : {avg_onnx_tps / max(avg_pt_tps, 1e-9):.2f}x") + + +def _run_benchmark(image_files, prompt, max_length, verbose, run_fn, label=""): + """Run a generate function over all images, collect metrics.""" + all_ttft, all_tps, all_tokens = [], [], [] + + if label: + print(f"\n--- {label} ---") + + for i, img_path in enumerate(image_files): + print(f"\n[{i + 1}/{len(image_files)}] {os.path.basename(img_path)}") + try: + text, token_count, ttft, tps = run_fn(img_path, prompt, max_length) + all_ttft.append(ttft) + all_tps.append(tps) + all_tokens.append(token_count) + print(f" tokens={token_count} TTFT={ttft * 1000:.1f}ms TPS={tps:.1f}") + if verbose: + display = text.strip()[:500] + print(f" Output: {display}{'...' if len(text.strip()) > 500 else ''}") + except Exception as e: + print(f" ERROR: {e}") + + return {"ttft": all_ttft, "tps": all_tps, "tokens": all_tokens} + + +def _print_summary(results, label): + """Print avg/min/max for a set of benchmark results.""" + tps_list = results["tps"] + ttft_list = results["ttft"] + tokens_list = results["tokens"] + if not tps_list: + print(f"\n {label}: no successful runs") + return + n = len(tps_list) + print(f"\n {label} ({n} images):") + print(f" Avg TTFT : {sum(ttft_list) / n * 1000:.1f} ms") + print(f" Avg Decode TPS : {sum(tps_list) / n:.1f} tokens/sec") + print(f" Avg tokens/image : {sum(tokens_list) / n:.0f}") + print(f" Min / Max TPS : {min(tps_list):.1f} / {max(tps_list):.1f}") + print(f" Min / Max TTFT : {min(ttft_list) * 1000:.1f} / {max(ttft_list) * 1000:.1f} ms") + + +def _build_pytorch_runner(model_id: str): + """Load a HuggingFace VL model for comparison.""" + print(f"\nLoading PyTorch model: {model_id}") + import torch + from transformers import AutoModelForImageTextToText, AutoProcessor + + device = "cuda" if torch.cuda.is_available() else "cpu" + dtype = torch.float16 if device == "cuda" else torch.float32 + print(f" Device: {device}, dtype: {dtype}") + + pt_model = AutoModelForImageTextToText.from_pretrained(model_id, torch_dtype=dtype).to(device) + pt_proc = AutoProcessor.from_pretrained(model_id) + print(f" PyTorch model loaded ({type(pt_model).__name__}).") + return pt_model, pt_proc, device + + +def _run_pytorch(pt_model, pt_proc, device, prompt, image_path, max_length): + """Run PyTorch generation on one image. Returns (text, token_count, ttft, tps).""" + import torch + from PIL import Image as PILImage + from qwen_vl_utils import process_vision_info + + messages = [ + { + "role": "user", + "content": [ + {"type": "image", "image": PILImage.open(image_path).convert("RGB")}, + {"type": "text", "text": prompt}, + ], + } + ] + text_input = pt_proc.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) + image_inputs, video_inputs = process_vision_info(messages) + inputs = pt_proc( + text=[text_input], images=image_inputs, videos=video_inputs, + padding=True, return_tensors="pt", + ).to(device) + + prompt_len = inputs["input_ids"].shape[-1] + + t_start = time.perf_counter() + with torch.no_grad(): + out = pt_model.generate(**inputs, max_new_tokens=max_length, do_sample=False) + t_total = time.perf_counter() - t_start + + out_ids = out[0][prompt_len:] + token_count = len(out_ids) + text = pt_proc.decode(out_ids, skip_special_tokens=True) + + ttft = t_total / max(token_count, 1) + tps = max(token_count - 1, 1) / max(t_total - ttft, 1e-9) + + return text, token_count, ttft, tps + + +def interactive_mode(model, processor, tokenizer, tokenizer_stream, args): + """Run in interactive mode with text and optional image inputs.""" + print("\n" + "=" * 50) + print("Interactive Mode - Enter 'quit' or 'exit' to stop") + print("To include an image, type: image:/path/to/image.jpg your prompt") + print("=" * 50 + "\n") + + while True: + try: + user_input = input("You: ").strip() + except EOFError: + break + + if user_input.lower() in ("quit", "exit"): + break + if not user_input: + print("Please enter a prompt.") + continue + + image_path = None + prompt = user_input + if user_input.startswith("image:"): + parts = user_input.split(" ", 1) + image_path = parts[0][6:] + prompt = parts[1] if len(parts) > 1 else "Describe this image" + + try: + generate_response( + model, processor, tokenizer, tokenizer_stream, + prompt, image_path, args.max_length, + ) + except Exception as e: + print(f"Error: {e}") + import traceback + traceback.print_exc() + + print("-" * 50 + "\n") + + print("Goodbye!") + + +if __name__ == "__main__": + main() diff --git a/Qwen-Qwen3.5-35B-A3B/builtin/info.yml b/Qwen-Qwen3.5-35B-A3B/builtin/info.yml new file mode 100644 index 00000000..c021bc58 --- /dev/null +++ b/Qwen-Qwen3.5-35B-A3B/builtin/info.yml @@ -0,0 +1,9 @@ +keywords: + - olive-ai +recipes: + - name: qwen3.5-35B-A3B-MoE + file: optimize.py + eps: + - CPUExecutionProvider + devices: + - cpu diff --git a/Qwen-Qwen3.5-35B-A3B/builtin/optimize.py b/Qwen-Qwen3.5-35B-A3B/builtin/optimize.py new file mode 100644 index 00000000..fc5c9514 --- /dev/null +++ b/Qwen-Qwen3.5-35B-A3B/builtin/optimize.py @@ -0,0 +1,203 @@ +# ------------------------------------------------------------------------- +# Copyright (C) 2026 Advanced Micro Devices, Inc. All rights reserved. +# Portions of this file consist of AI generated content. +# -------------------------------------------------------------------------- +# SPDX-License-Identifier: MIT +# -------------------------------------------------------------------------- +"""End-to-end optimization pipeline for Qwen3.5-35B-A3B MoE VLM. + +Exports three sub-models (vision encoder, text embedding, text decoder), +applies graph optimizations and INT4 quantization via Olive passes. + +Usage: + python optimize.py --config-dir cpu_and_mobile --device cpu + python optimize.py --config-dir cpu_and_mobile --device cpu --skip-export +""" +import argparse +import json +import logging +from pathlib import Path + +logging.getLogger("onnxscript").setLevel(logging.WARNING) +logging.getLogger("onnx_ir").setLevel(logging.WARNING) + +MODELS_DIR = "models" + + +def _read_model_name(config_dir: str) -> str: + """Read the HuggingFace model name from the Olive text config.""" + text_cfg = json.loads((Path(config_dir) / "text.json").read_text()) + return text_cfg["input_model"]["model_path"] + + +def export_models(config_dir: str): + """Run Olive for all 3 sub-models (text, embedding, vision).""" + from olive import run + + config_path = Path(config_dir) + print(f"=== Running Olive pipelines (configs from {config_path}) ===") + for config in ("text.json", "embedding.json", "vision.json"): + print(f" Running {config}...") + run(str(config_path / config)) + print() + + +def update_genai_config(output_dir: str, model_name: str, device: str = "cpu", context_length: int = 4096): + """Patch genai_config.json with embedding/vision sections and processor_config. + + Reads token IDs, vision parameters, and preprocessor settings from the + HuggingFace model config rather than hardcoding them. + """ + from transformers import AutoConfig, GenerationConfig + from huggingface_hub import hf_hub_download + + hf_config = AutoConfig.from_pretrained(model_name) + gen_config = GenerationConfig.from_pretrained(model_name) + vc = hf_config.vision_config + + config_path = Path(output_dir) / "genai_config.json" + with open(config_path) as f: + config = json.load(f) + + if device == "gpu": + provider_options = [ + {"cuda": {"enable_cuda_graph": "1", "enable_skip_layer_norm_strict_mode": "1"}} + ] + vision_provider_options = [ + {"cuda": {"enable_cuda_graph": "0", "enable_skip_layer_norm_strict_mode": "1"}} + ] + else: + provider_options = [] + vision_provider_options = [] + + vision_session_options = {"log_id": "onnxruntime-genai", "provider_options": vision_provider_options} + + config["model"]["decoder"]["filename"] = "text.onnx" + + config["model"]["embedding"] = { + "filename": "embedding.onnx", + "inputs": {"input_ids": "input_ids", "image_features": "image_features"}, + "outputs": {"inputs_embeds": "inputs_embeds"}, + "session_options": vision_session_options, + } + + config["model"]["vision"] = { + "filename": "vision.onnx", + "config_filename": "processor_config.json", + "spatial_merge_size": vc.spatial_merge_size, + "tokens_per_second": 2.0, + "patch_size": vc.patch_size, + "inputs": {"pixel_values": "pixel_values", "image_grid_thw": "image_grid_thw"}, + "outputs": {"image_features": "image_features"}, + "session_options": vision_session_options, + } + + config["model"]["bos_token_id"] = gen_config.bos_token_id + config["model"]["context_length"] = context_length + config["model"]["eos_token_id"] = gen_config.eos_token_id + config["model"]["pad_token_id"] = gen_config.pad_token_id + config["model"]["image_token_id"] = hf_config.image_token_id + config["model"]["video_token_id"] = hf_config.video_token_id + config["model"]["vision_start_token_id"] = hf_config.vision_start_token_id + + config["search"]["max_length"] = context_length + if gen_config.top_k is not None: + config["search"]["top_k"] = gen_config.top_k + if gen_config.top_p is not None and config["search"].get("top_p") is None: + config["search"]["top_p"] = gen_config.top_p + + with open(config_path, "w") as f: + json.dump(config, f, indent=4) + print(f" Updated {config_path}") + + pp_path = hf_hub_download(model_name, "preprocessor_config.json") + with open(pp_path) as f: + pp = json.load(f) + pp_size = pp.get("size", {}) + + processor_config = { + "processor": { + "name": "qwen2_5_image_processor", + "transforms": [ + {"operation": {"name": "decode_image", "type": "DecodeImage", "attrs": {"color_space": "RGB"}}}, + {"operation": {"name": "convert_to_rgb", "type": "ConvertRGB"}}, + {"operation": {"name": "resize", "type": "Resize", "attrs": { + "width": 960, "height": 672, "smart_resize": 1, + "min_pixels": pp_size.get("shortest_edge", 65536), + "max_pixels": pp_size.get("longest_edge", 16777216), + "patch_size": vc.patch_size, + "merge_size": vc.spatial_merge_size, + }}}, + {"operation": {"name": "rescale", "type": "Rescale", "attrs": { + "rescale_factor": 1.0 / 255, + }}}, + {"operation": {"name": "normalize", "type": "Normalize", "attrs": { + "mean": pp.get("image_mean", [0.5, 0.5, 0.5]), + "std": pp.get("image_std", [0.5, 0.5, 0.5]), + "qwen2_5_vl": 1, + }}}, + {"operation": {"name": "patch_image", "type": "PatchImage", "attrs": { + "patch_size": vc.patch_size, + "temporal_patch_size": vc.temporal_patch_size, + "merge_size": vc.spatial_merge_size, + }}}, + ], + } + } + + processor_path = Path(output_dir) / "processor_config.json" + with open(processor_path, "w") as f: + json.dump(processor_config, f, indent=2) + print(f" Created {processor_path}") + + +def fix_tokenizer(output_dir: str = MODELS_DIR): + """Fix tokenizer.json for C++ std::regex compatibility.""" + tk_path = Path(output_dir) / "tokenizer.json" + if not tk_path.exists(): + return + tk = json.loads(tk_path.read_text(encoding="utf-8")) + pt = tk.get("pre_tokenizer", {}) + if pt.get("type") == "Sequence": + pt["pretokenizers"] = [s for s in pt["pretokenizers"] if s.get("type") == "ByteLevel"] + for s in pt["pretokenizers"]: + s["use_regex"] = True + tk_path.write_text(json.dumps(tk, ensure_ascii=False), encoding="utf-8") + + tc_path = Path(output_dir) / "tokenizer_config.json" + if tc_path.exists(): + tc = json.loads(tc_path.read_text(encoding="utf-8")) + tc["tokenizer_class"] = "Qwen2Tokenizer" + tc_path.write_text(json.dumps(tc, indent=2, ensure_ascii=False), encoding="utf-8") + print(f" Fixed tokenizer for C++ std::regex compatibility") + + +def main(): + parser = argparse.ArgumentParser(description="Optimize Qwen3.5-35B-A3B MoE VLM") + parser.add_argument("--device", choices=["gpu", "cpu"], default="cpu") + parser.add_argument("--config-dir", default="cpu_and_mobile") + parser.add_argument("--skip-export", action="store_true") + parser.add_argument("--models-dir", default=None) + parser.add_argument("--context-length", type=int, default=4096) + args = parser.parse_args() + + models_dir = args.models_dir or str(Path(args.config_dir) / MODELS_DIR) + model_name = _read_model_name(args.config_dir) + + if not args.skip_export: + export_models(args.config_dir) + + print("=== Generating configs ===") + update_genai_config( + output_dir=models_dir, + model_name=model_name, + device=args.device, + context_length=args.context_length, + ) + fix_tokenizer(output_dir=models_dir) + print() + print("Done.") + + +if __name__ == "__main__": + main() diff --git a/Qwen-Qwen3.5-35B-A3B/builtin/user_script.py b/Qwen-Qwen3.5-35B-A3B/builtin/user_script.py new file mode 100644 index 00000000..8eeb69ae --- /dev/null +++ b/Qwen-Qwen3.5-35B-A3B/builtin/user_script.py @@ -0,0 +1,126 @@ +# ------------------------------------------------------------------------- +# Copyright (C) 2026 Advanced Micro Devices, Inc. All rights reserved. +# Portions of this file consist of AI generated content. +# -------------------------------------------------------------------------- +# SPDX-License-Identifier: MIT +# -------------------------------------------------------------------------- +import os +import sys +import torch + +_script_dir = os.path.dirname(os.path.abspath(__file__)) +if _script_dir not in sys.path: + sys.path.insert(0, _script_dir) + +from codes.modeling_qwen3_5_moe import Qwen3_5MoeModel +from transformers import AutoConfig + +model_name = "Qwen/Qwen3.5-35B-A3B" +config = AutoConfig.from_pretrained(model_name) + + +_NEEDED_PREFIXES = ("model.visual.", "model.language_model.embed_tokens.") + + +def _load_model(model_path): + """Load weights into the ONNX-export-friendly Qwen3_5MoeModel. + + Only loads vision encoder and embedding weights (~4 GB) rather than the + full 35B MoE checkpoint (~67 GB) to avoid unnecessary memory usage. + """ + from safetensors import safe_open + from huggingface_hub import hf_hub_download + import glob + + cfg_path = hf_hub_download(model_path, "config.json") + model_dir = os.path.dirname(cfg_path) + st_files = sorted(glob.glob(os.path.join(model_dir, "*.safetensors"))) + + state_dict = {} + for sf in st_files: + with safe_open(sf, framework="pt") as f: + for k in f.keys(): + if not any(k.startswith(p) for p in _NEEDED_PREFIXES): + continue + stripped = k[len("model."):] + state_dict[stripped] = f.get_tensor(k) + if stripped.startswith("language_model.embed_tokens."): + state_dict[stripped[len("language_model."):]] = state_dict[stripped] + + custom_model = Qwen3_5MoeModel(config) + custom_model.load_state_dict(state_dict, strict=False) + custom_model = custom_model.to(torch.bfloat16).eval() + del state_dict + return custom_model + + +# ── Embedding ──────────────────────────────────────────────────────────── + +def get_embedding_model(model_path=None): + """Load the custom MoE model and swap forward with get_fused_input_embeddings.""" + model = _load_model(model_path or model_name) + model = model.to(torch.float32) + model.get_fused_input_embeddings, model.forward = ( + model.forward, + model.get_fused_input_embeddings, + ) + return model + + +def get_embedding_io_config(model_path=None): + return { + "input_names": ["input_ids", "image_features"], + "output_names": ["inputs_embeds"], + "dynamic_axes": { + "input_ids": {0: "batch_size", 1: "sequence_length"}, + "image_features": {0: "num_logical_patches"}, + "inputs_embeds": {0: "batch_size", 1: "sequence_length"}, + }, + } + + +def get_embedding_dummy_inputs(model=None): + out_hidden_size = config.vision_config.out_hidden_size + batch_size, sequence_length, patches_per_image = 2, 216, 187 + num_logical_patches = batch_size * patches_per_image + + inputs = { + "input_ids": torch.randint(0, config.image_token_id, (batch_size, sequence_length), dtype=torch.int64), + "image_features": torch.randn(num_logical_patches, out_hidden_size, dtype=torch.float32), + } + + img_start_index = 3 + img_end_index = img_start_index + patches_per_image + for b in range(batch_size): + inputs["input_ids"][b][2] = config.vision_start_token_id + inputs["input_ids"][b][img_start_index:img_end_index] = config.image_token_id + inputs["input_ids"][b][img_end_index] = config.vision_end_token_id + + return inputs + + +# ── Vision ─────────────────────────────────────────────────────────────── + +def get_vision_model(model_path=None): + model = _load_model(model_path or model_name) + model = model.to(torch.float32) + model.forward, model.get_image_features = model.get_image_features, model.forward + return model + + +def get_vision_io_config(model_path=None): + return { + "input_names": ["pixel_values", "image_grid_thw"], + "output_names": ["image_features"], + "dynamic_shapes": { + "pixel_values": {0: "num_patches"}, + "image_grid_thw": None, + }, + } + + +def get_vision_dummy_inputs(model=None): + patches = 22 * 34 + pixel_values = torch.randn((patches, 1536), dtype=torch.float32) + grid_thw = torch.tensor([[1, 22, 34]], dtype=torch.int64) + return {"pixel_values": pixel_values, "image_grid_thw": grid_thw}