MNN Model Support: Qwen3.5 #4354
wangzhaode
announced in
Technical Blog
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Introduction
Qwen3.5 was officially open-sourced on Chinese New Year's Eve, and the MNN team quickly completed comprehensive adaptation and optimization, simultaneously releasing Qwen3.5 MNN models that can be efficiently deployed on edge devices.
Qwen3.5 is the latest generation of large language models in the Qwen (Tongyi Qianwen) series. From Qwen to Qwen2, Qwen2.5, and Qwen3, each generation's upgrades have primarily focused on training data, model scale, and fine-tuning strategies, while the core architecture has always remained within the standard Transformer Decoder framework. Qwen3.5, however, represents the most significant architectural overhaul in this series, introducing disruptive designs across almost every key module:
This article provides a detailed introduction to the core adaptation work and technical implementations MNN has made to support Qwen3.5.
Overview of Qwen3.5 Architectural Changes
1. DeltaNet: Linear Attention Mechanism
1.1 Comparison with Standard Attention
Standard Transformer Attention and DeltaNet linear attention are both sequence modeling mechanisms at their core, but they differ fundamentally in computation patterns and resource consumption:
Qwen3.5 combines these two attention types at a 3:1 ratio -- out of every 4 layers, 3 use DeltaNet linear attention and 1 uses standard Full Attention. This design significantly reduces inference costs while relying on the periodically inserted standard Attention layers to maintain precise capture of critical information.
1.2 Algorithm Principles
The core of DeltaNet is the Gated Delta Rule, which maintains a Key-Value memory matrix S ∈ ℝ^{d_k × d_v}, updating at each time step through the following five steps:
Here,
gate(decay factor) andbeta(learning rate) control the forgetting and update strength of memory, enabling the model to maintain fine-grained control over contextual information while preserving linear complexity.Notably, the computation of
gateis carefully parameterized to ensure it is always non-positive (guaranteeing memory decay):Both
A_loganddt_biasare learnable parameters.exp(A_log)ensures positivity,softplus(...)ensures non-negativity, and the leading negative sign ensuresgateis always ≤ 0, yielding a decay coefficient in (0, 1] after applyingexp(gate).1.3 Reverse GQA
Qwen3.5's Linear Attention features a unique design: the number of V heads exceeds the number of K/Q heads (e.g., in the 7B model,
num_v_heads=32,num_k_heads=16). This is the opposite of standard GQA (Grouped-Query Attention), where K/V heads are fewer than Q heads. Before computation, K and Q are expanded viarepeat_interleaveto match the number of V heads:This means the recurrent state S has dimensions
[B, num_v_heads, d_k, d_v], with each V head possessing its own independent memory matrix. More V heads give the model richer expressive capacity at the output side, while keeping the computational cost of K/Q low.1.4 MNN Implementation
To support DeltaNet, MNN introduced a new
OpType_LinearAttentionoperator (ID=305), with a newLinearAttentionParamparameter table in the FlatBuffers Schema:This operator has complete implementations across four backends:
CPU Backend (
CPULinearAttention.cpp): Leverages multi-threading parallelism, channel-level parallel computation for Conv1D+SiLU, head-level parallel computation for the Gated Delta Rule, and uses MNN's built-in optimized functions such asMNNSiLu,MNNScaleAndAddBiasScalar, andMNNComputeMatMulForE_1to accelerate core computations.Metal Backend (
MetalLinearAttention.mm): Implements three Metal Compute Kernels --linear_attn_conv_silu,linear_attn_conv_state_update,linear_attn_gated_delta_rule-- compiled via inline shaders usingR"metal(...)", with a Pipeline caching mechanism to avoid redundant compilation.OpenCL Backend (
LinearAttentionBufExecution.cpp): Three OpenCL Kernels are written as.clfiles, automatically converted to C++ source code and embedded during compilation via a Codegen script. All usefloatprecision to ensure numerical stability in recurrence.Vulkan Backend (
VulkanLinearAttention.cpp): Three GLSL Compute Shaders compiled to SPIR-V, registered viaVulkanShaderMap, following the Vulkan backend's standard Descriptor Set + Uniform Buffer pattern.All four backends share the same algorithmic logic and must manage two persistent states:
[B, D, K-1]: Sliding window history for causal convolution[B, H, d_k, d_v]: Key-Value memory matrix for the Delta RuleThese states are allocated using
Backend::STATIC, zero-initialized on the first inference step, and persist across Decode steps.1.5 Hybrid Attention Decoder Structure
Qwen3.5 adopts a hybrid architecture alternating 3 layers of Linear Attention with 1 layer of Full Attention. In the Decoder, each layer automatically selects the attention type based on the original model's configuration:
Differences between the two layer types during inference:
This means Qwen3.5's KV Cache size is only about 1/4 that of a pure Transformer model, significantly reducing memory overhead for long-sequence inference.
2. Gated RMSNorm
Qwen3.5 introduces Gated RMSNorm, an extension of standard RMSNorm that additionally receives a gating signal, multiplying the normalized result by a SiLU-activated gate value:
Gated RMSNorm is applied to both attention layer types in Qwen3.5:
In Linear Attention layers, the gate comes from an independent
in_proj_zprojection:In Full Attention layers, the gate comes from the expanded output of
q_proj. Whenq_proj's output dimension is2 * num_heads * head_dim, the output is split into query and gate parts:Note that the two layer types use different gating activation functions: Linear Attention layers use SiLU (
norm(x) * silu(z)), while Full Attention layers use Sigmoid (attn_output * sigmoid(gate)). SiLU outputs in the range (-0.28, +∞), allowing mild suppression; Sigmoid outputs are strictly in (0, 1), serving purely as a scaling mechanism.3. MoE Architecture Changes: Shared Expert
3.1 What Changed
Qwen3.5's MoE (Mixture of Experts) layer introduces a Shared Expert mechanism. Unlike traditional MoE where each token is routed only to Top-k experts, the Shared Expert is a common expert that all tokens pass through, and its output is added to the routed experts' output:
3.2 Significance of Shared Expert
3.3 MNN Adaptation
In MNN's export pipeline, the Shared Expert is exported as an independent linear layer, and its output is modulated by
shared_expert_gate(Sigmoid gating) before being added to the MoE output. Themodel_mapper.pyadds corresponding mappings:Additionally, the Expert weight format for MoE modules changes from
ModuleListto PackedMLP format -- all expert weights are stored in a unified 3D tensor[num_experts, ...], accessible by index slicing (gate_up_proj.data[i]can be used directly without.transpose(0, 1)), simplifying the export process. Furthermore, Qwen3.5 MoE routing weights are normalized after Top-k selection (routing_weights /= routing_weights.sum()), ensuring the sum of all expert contributions equals 1.4. Default Multimodal: Native Vision Support
4.1 Architectural Features
Unlike Qwen3, which released text-only and vision-language models separately, Qwen3.5 is released by default as a multimodal Vision-Language Model (VLM). This means:
text_configstructure (e.g.,text_config.hidden_size), distinguishing text and vision configurations.model.language_model.layersrather thanmodel.layers.model.language_model.embed_tokens.model.visual.4.2 Vision Encoder (Qwen3_5Vision)
Qwen3.5's vision encoder is largely consistent with Qwen3-VL, inheriting its ViT + Merger architecture design, Interleaved M-RoPE position encoding scheme, learnable position encoding (
pos_embed+ bilinear interpolation), and dynamic resolution handling. The main difference is:deepstack_merger_list, used for multi-scale deep fusion of visual tokens) has been removed in Qwen3.5, simplifying the vision encoder structure.4.3 Interleaved M-RoPE Adaptation for Text-Only Scenarios
Qwen3.5 inherits the Interleaved M-RoPE position encoding scheme introduced in Qwen3-VL. This scheme alternates frequency components across time (T), height (H), and width (W) dimensions, rather than concatenating them along the feature dimension as in earlier M-RoPE:
In vision processing, the T/H/W dimensions each carry genuine spatiotemporal position information. For text-only inference, since text lacks spatial dimensions, the MNN inference engine replicates the same position ID three times (T=H=W), automatically handling this via the
is_mropeconfiguration flag:4.4 Partial Rotary
Qwen3.5 introduces a
partial_rotary_factorparameter, applying rotary position encoding to only a subset of dimensions withinhead_dim, while the remaining dimensions pass through unchanged:During
apply_rotary_pos, this mechanism follows the same approach used by the Phi series models -- splitting the feature vector into two parts, applying rotation only to the firstrotary_dimdimensions, and concatenating the remaining dimensions as-is:This differs from models like LLaMA, which apply rotation to all dimensions. Partial rotary allows the model to preserve position information encoding capability while maintaining a portion of "position-invariant" feature dimensions. Qwen3.5's
model_typeis routed into the Phi branch for RoPE processing:Note that partial rotary is only applied to Full Attention layers. LinearAttention layers do not use RoPE; position information is provided entirely by causal convolution.
5. Tokenizer Upgrade
Qwen3.5 significantly expands its vocabulary from the 151,936 tokens used throughout the Qwen series to 248,320, an increase of over 63%. A larger vocabulary better covers token distributions across multiple languages and specialized domains, reducing fragmentation during tokenization. This results in shorter token sequences for the same text, improving inference efficiency.
6. MTP (Multi-Token Prediction)
Qwen3.5's configuration includes
mtp_num_hidden_layers: 1, indicating the model has built-in MTP (Multi-Token Prediction) capability. MTP is a speculative decoding technique -- building on standard LLMs that predict only the next token per step, additional MTP layers parallelly predict multiple subsequent tokens, generating several candidate tokens in a single forward pass, significantly boosting inference throughput.The MTP module is a lightweight Decoder layer that takes the main model's final layer hidden states and the current token's embedding as input:
MNN's export framework has built a complete export channel for MTP (
export_mtp), supporting exporting the MTP layer as an independent ONNX model and converting it to MNN format. The MTP layer shareslm_headweights with the main model and maintains its own independent KV Cache.7. MNN Framework-Level Improvements
During the Qwen3.5 adaptation, MNN's LLM export framework underwent significant refactoring:
past_key_valuespassing: KV Cache management changed from external model input to internal self-management (self.past_key_value), simplifying both export and inference pipelines.forwardreturn value changed from(hidden_states, present_key_value)to simplyhidden_states.export_fused_attnenabled, without distinguishing MoE models.kv_cacheattribute: Distinguishes standard Attention layers (which need KV Cache) from LinearAttention layers (which do not need KV Cache).8. Quick Start
Exporting the Model
# Export Qwen3.5 model python llmexport.py --path /path/to/model --export mnn --hqqInference
# Inference using MNN LLM engine ./llm_demo /path/to/exported/model/config.json prompt.txtSummary
The transition from Qwen3 to Qwen3.5 represents the most significant architectural overhaul in the Qwen series to date. MNN's support for Qwen3.5 covers all of the model's core innovations:
LinearAttentionoperator implemented across CPU, Metal, OpenCL, and Vulkan backends; the 3:1 Linear + Full hybrid architecture reduces KV Cache to 1/4.These efforts enable MNN to efficiently deploy Qwen3.5 series models on mobile and embedded devices.
Resource Links
We welcome developers to try, provide feedback, and contribute, together advancing the development of on-device large language model inference technology.
Beta Was this translation helpful? Give feedback.
All reactions