19-Hugging Face Transformers之Qwen3.5-MoE 系列详解:混合专家 + 线性注意力 + 多模态的完整生命周期
Qwen3.5-MoE 系列详解:混合专家 + 线性注意力 + 多模态的完整生命周期
本文档以 Qwen3.5-MoE 模型为例,将 Transformers 框架的所有模块串联起来,深度剖析最前沿的 混合专家 + 多模态 + 线性注意力 模型在 Transformers 中的完整生命周期。
源码文件:
- [configuration_qwen3_5_moe.py](file:///workspace/src/transformers/models/qwen3_5_moe/configuration_qwen3_5_moe.py)
- [modeling_qwen3_5_moe.py](file:///workspace/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py)
- [modular_qwen3_5_moe.py](file:///workspace/src/transformers/models/qwen3_5_moe/modular_qwen3_5_moe.py)
相关文章:
Hugging Face Transformers 源码全景解读
01-Hugging Face Transformers 核心基础设施深度分析
02-Hugging Face Transformers 配置系统深度分析
03-Hugging Face Transformers 模型系统深度分析
04-Hugging Face Transformers 注意力与掩码系统深度分析
05-Hugging Face Transformers 缓存系统深度分析
06-Hugging Face Transformers 生成系统深度分析
07-Hugging Face Transformers 分词器系统深度分析
08-Hugging Face Transformers 多模态处理系统深度分析
09-Hugging Face Transformers 训练系统深度分析
10-Hugging Face Transformers 量化系统深度分析
11-Hugging Face Transformers 分布式与并行系统深度分析
12-Hugging Face Transformers之Pipeline 推理管道深入分析
13-Hugging Face Transformers之AutoModel 自动分发机制深入分析
14-Hugging Face Transformers 模型实现模式深度分析
15-Hugging Face Transformers之CLI 与工具架构总览
16-Hugging Face Transformers之测试体系架构总览
17-Hugging Face Transformers之BERT 案例详解:Transformers 框架全模块串联
18-Hugging Face Transformers之GPT-2 案例详解:Decoder-only 自回归模型的完整生命周期
19-Hugging Face Transformers之Qwen3.5-MoE 系列详解:混合专家 + 线性注意力 + 多模态的完整生命周期
1. Qwen3.5-MoE 在 Transformers 中的定位
Qwen3.5-MoE 是 Qwen 系列中最前沿的混合架构模型,它同时融合了三大创新:混合注意力层(full_attention + linear_attention 交替)、MoE 专家路由(256 专家 Top-8 路由 + 共享专家)和多模态视觉编码器(Vision Transformer + PatchMerger)。
1.1 架构定位图
1.2 三大创新点图示
1.3 继承关系
从 [modular_qwen3_5_moe.py](file:///workspace/src/transformers/models/qwen3_5_moe/modular_qwen3_5_moe.py) 可以看出,Qwen3.5-MoE 的类继承链非常清晰:
| Qwen3.5-MoE 类 | 直接父类 | 来源模块 |
|---|---|---|
Qwen3_5MoeTextConfig |
Qwen3NextConfig |
qwen3_next |
Qwen3_5MoeVisionConfig |
Qwen3_5VisionConfig |
qwen3_5 |
Qwen3_5MoeConfig |
Qwen3VLConfig |
qwen3_vl |
Qwen3_5MoeGatedDeltaNet |
Qwen3_5GatedDeltaNet |
qwen3_5 |
Qwen3_5MoeAttention |
Qwen3NextAttention |
qwen3_next |
Qwen3_5MoeExperts |
Qwen3NextExperts |
qwen3_next |
Qwen3_5MoeTopKRouter |
Qwen3VLMoeTextTopKRouter |
qwen3_vl_moe |
Qwen3_5MoeSparseMoeBlock |
Qwen3NextSparseMoeBlock |
qwen3_next |
Qwen3_5MoeForConditionalGeneration |
Qwen3VLMoeForConditionalGeneration |
qwen3_vl_moe |
2. Config 三层嵌套设计
Qwen3.5-MoE 采用三层 Config 嵌套设计,顶层 Qwen3_5MoeConfig 包含 text_config 和 vision_config 两个子配置。
2.1 Config 嵌套类图
2.2 sub_configs 机制图
sub_configs 是 Transformers 中多模态模型的标准机制,定义在 [configuration_qwen3_5_moe.py:171](file:///workspace/src/transformers/models/qwen3_5_moe/configuration_qwen3_5_moe.py#L171):
class Qwen3_5MoeConfig(PreTrainedConfig):
sub_configs = {"vision_config": Qwen3_5MoeVisionConfig, "text_config": Qwen3_5MoeTextConfig}
关键代码在 [configuration_qwen3_5_moe.py:183-194](file:///workspace/src/transformers/models/qwen3_5_moe/configuration_qwen3_5_moe.py#L183):
def __post_init__(self, **kwargs):
if isinstance(self.vision_config, dict):
self.vision_config = self.sub_configs["vision_config"](**self.vision_config)
elif self.vision_config is None:
self.vision_config = self.sub_configs["vision_config"]()
if isinstance(self.text_config, dict):
self.text_config = self.sub_configs["text_config"](**self.text_config)
elif self.text_config is None:
self.text_config = self.sub_configs["text_config"]()
super().__post_init__(**kwargs)
2.3 base_model_tp_plan / base_model_pp_plan 并行策略声明图
Qwen3_5MoeTextConfig 在 [configuration_qwen3_5_moe.py:59-77](file:///workspace/src/transformers/models/qwen3_5_moe/configuration_qwen3_5_moe.py#L59) 声明了张量并行(TP)和流水线并行(PP)策略:
3. from_pretrained 完整时序
从 Qwen3_5MoeForConditionalGeneration.from_pretrained('Qwen/Qwen3.5-35B-A3B') 到模型就绪的完整流程。
3.1 时序图
3.2 MoE 权重加载特殊处理
Qwen3.5-MoE 的专家权重以 3D 张量存储,这是 MoE 模型与 Dense 模型的关键区别。在 [modeling_qwen3_5_moe.py:736-772](file:///workspace/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L736) 中:
@use_experts_implementation
class Qwen3_5MoeExperts(nn.Module):
def __init__(self, config):
super().__init__()
self.num_experts = config.num_experts # 256
self.hidden_dim = config.hidden_size # 2048
self.intermediate_dim = config.moe_intermediate_size # 512
# 3D 参数张量:[num_experts, intermediate_dim*2, hidden_dim]
self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim))
# 3D 参数张量:[num_experts, hidden_dim, intermediate_dim]
self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim))
4. 混合注意力层架构
Qwen3.5-MoE 的核心创新在于 full_attention 层和 linear_attention 层交替排列,这是混合注意力架构的首次大规模应用。
4.1 层类型分布图
layer_types 在 [configuration_qwen3_5_moe.py:112-119](file:///workspace/src/transformers/models/qwen3_5_moe/configuration_qwen3_5_moe.py#L112) 中自动生成,默认 full_attention_interval=4:
def __post_init__(self, **kwargs):
if self.layer_types is None:
interval_pattern = kwargs.pop("full_attention_interval", 4)
self.layer_types = [
"linear_attention" if bool((i + 1) % interval_pattern) else "full_attention"
for i in range(self.num_hidden_layers)
]
规律:每 4 层中,第 0-2 层为 linear_attention,第 3 层为 full_attention。40 层中共有 10 个 full_attention 层和 30 个 linear_attention 层。
4.2 Qwen3_5MoeAttention 内部结构图
定义在 [modeling_qwen3_5_moe.py:642-716](file:///workspace/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L642):
三大创新点:
- QK Norm:
q_norm和k_norm对 Q/K 做 RMSNorm,稳定训练 - Gate 机制:
q_proj输出维度翻倍(head_dim * 2),一半作为 query,一半经 sigmoid 门控 - M-RoPE:多模态旋转位置编码,支持文本/图像/视频的 3D 位置
4.3 Qwen3_5MoeGatedDeltaNet 内部结构图
定义在 [modeling_qwen3_5_moe.py:367-555](file:///workspace/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L367):
GatedDeltaNet 核心公式:
# 递推模式(单 token 解码):
S_t = S_{t-1} * exp(g_t) # 衰减旧状态
kv_mem = (S_t * k_t).sum(dim=-2) # 检索记忆
δ_t = (v_t - kv_mem) * β_t # 计算修正量
S_t = S_t + k_t^T * δ_t # 更新状态
o_t = (S_t * q_t).sum(dim=-2) # 查询输出
4.4 两种注意力层的数据流对比图
| 特性 | full_attention | linear_attention |
|---|---|---|
| 复杂度 | O(n²) | O(n) |
| 缓存类型 | KV Cache | conv_state + recurrent_state |
| 位置编码 | M-RoPE | 无(卷积隐式编码) |
| QK Norm | ✅ | ❌(使用 L2 Norm) |
| Gate 机制 | Sigmoid Gate on Q | RMSNormGated with z |
| 适用场景 | 精确长程依赖 | 高效序列建模 |
5. MoE 专家路由系统
Qwen3.5-MoE 采用 256 专家 Top-8 路由 + 共享专家的混合架构,每个 token 同时经过 8 个路由专家和 1 个共享专家。
5.1 MoE 路由流程图
5.2 Qwen3_5MoeSparseMoeBlock 内部结构图
定义在 [modeling_qwen3_5_moe.py:794-813](file:///workspace/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L794):
关键代码:
class Qwen3_5MoeSparseMoeBlock(nn.Module):
def __init__(self, config):
self.gate = Qwen3_5MoeTopKRouter(config)
self.experts = Qwen3_5MoeExperts(config)
self.shared_expert = Qwen3_5MoeMLP(config, intermediate_size=config.shared_expert_intermediate_size)
self.shared_expert_gate = torch.nn.Linear(config.hidden_size, 1, bias=False)
def forward(self, hidden_states):
shared_expert_output = self.shared_expert(hidden_states_reshaped)
_, routing_weights, selected_experts = self.gate(hidden_states_reshaped)
expert_output = self.experts(hidden_states_reshaped, selected_experts, routing_weights)
shared_expert_output = F.sigmoid(self.shared_expert_gate(hidden_states_reshaped)) * shared_expert_output
expert_output = expert_output + shared_expert_output
5.3 @use_experts_implementation 装饰器的工作原理
定义在 [integrations/moe.py:523](file:///workspace/src/transformers/integrations/moe.py),该装饰器允许将默认的 PyTorch 专家实现替换为优化版本(如 megablocks、grouped_gemm):
5.4 负载均衡损失计算图
定义在 [modeling_qwen3_5_moe.py:1755-1834](file:///workspace/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L1755):
公式:L_aux = N × Σ_i(f_i × P_i),其中 f_i 是分配给专家 i 的 token 比例,P_i 是路由到专家 i 的平均概率。
6. 多模态视觉编码器
6.1 视觉编码流程图
6.2 3D 位置编码(M-RoPE)计算图
视觉 token 的 3D 位置编码由 get_vision_position_ids 方法计算,定义在 [modeling_qwen3_5_moe.py:1394-1450](file:///workspace/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L1394):
关键代码:
def get_vision_position_ids(self, start_position, grid_thw, ...):
llm_grid_t = grid_thw[0] // temp_merge_size
llm_grid_h = grid_thw[1] // spatial_merge_size
llm_grid_w = grid_thw[2] // spatial_merge_size
position_temporal = torch.arange(llm_grid_t) * time_interval
position_width = torch.arange(llm_grid_w) + start_position
position_height = torch.arange(llm_grid_h) + start_position
position_width = position_width.repeat(llm_grid_h * llm_grid_t)
position_height = position_height.repeat_interleave(llm_grid_w).repeat(llm_grid_t)
position_temporal = position_temporal.repeat_interleave(llm_grid_h * llm_grid_w) + start_position
return torch.stack([position_temporal, position_height, position_width], dim=0)
6.3 视觉 token 与文本 token 的融合流程图
在 [modeling_qwen3_5_moe.py:1707-1727](file:///workspace/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L1707) 中,使用 masked_scatter 将视觉嵌入融合到文本嵌入中:
关键代码:
if pixel_values is not None:
image_embeds = self.get_image_features(pixel_values, image_grid_thw)
image_mask, _ = self.get_placeholder_mask(input_ids, inputs_embeds=inputs_embeds, image_features=image_embeds)
inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds)
if pixel_values_videos is not None:
video_embeds = self.get_video_features(pixel_values_videos, video_grid_thw)
_, video_mask = self.get_placeholder_mask(input_ids, inputs_embeds=inputs_embeds, video_features=video_embeds)
inputs_embeds = inputs_embeds.masked_scatter(video_mask, video_embeds)
7. RoPE 与 M-RoPE 位置编码
M-RoPE(Multimodal Rotary Position Embedding)是 Qwen3.5 系列的核心位置编码方案,支持文本的 1D 位置和图像/视频的 3D 位置。
7.1 M-RoPE 原理图
7.2 apply_interleaved_mrope 交错排列图
在 [modeling_qwen3_5_moe.py:165-180](file:///workspace/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L165) 中,M-RoPE 将三维频率交错排列:
关键代码:
def apply_interleaved_mrope(self, freqs, mrope_section):
freqs_t = freqs[0] # 以 T 维度为基底
for dim, offset in enumerate((1, 2), start=1): # H, W
length = mrope_section[dim] * 3
idx = slice(offset, length, 3) # 交错索引
freqs_t[..., idx] = freqs[dim, ..., idx]
return freqs_t
7.3 get_rope_index 位置计算流程图
定义在 [modeling_qwen3_5_moe.py:1452-1543](file:///workspace/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L1452):
视频特殊处理:由于 Qwen3.5 使用时间戳分隔视频帧,video_grid_thw 需要按帧拆分:
if video_grid_thw is not None:
video_grid_thw = torch.repeat_interleave(video_grid_thw, video_grid_thw[:, 0], dim=0)
video_grid_thw[:, 0] = 1 # 每帧独立
8. 缓存系统
Qwen3.5-MoE 的混合注意力架构需要混合缓存:full_attention 层使用 KV Cache,linear_attention 层使用 conv_state + recurrent_state。
8.1 混合缓存架构图
DynamicCache 在初始化时根据 config.layer_types 自动判断每层的缓存类型,定义在 [cache_utils.py:1229](file:///workspace/src/transformers/cache_utils.py)。
8.2 linear_attention 层的缓存更新流程
关键代码在 [modeling_qwen3_5_moe.py:449-546](file:///workspace/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L449):
use_precomputed_states = cache_params is not None and cache_params.has_previous_state(self.layer_idx)
if use_precomputed_states:
conv_state = cache_params.layers[self.layer_idx].conv_states
recurrent_state = cache_params.layers[self.layer_idx].recurrent_states
# Prefill: 多 token,使用 chunk 模式
if not (use_precomputed_states and seq_len == 1):
if cache_params is not None:
new_conv_state = F.pad(mixed_qkv, (self.conv_kernel_size - mixed_qkv.shape[-1], 0))
cache_params.update_conv_state(new_conv_state, self.layer_idx)
core_attn_out, last_recurrent_state = self.chunk_gated_delta_rule(...)
# Decode: 单 token,使用 recurrent 模式
else:
mixed_qkv = self.causal_conv1d_update(mixed_qkv, conv_state, ...)
core_attn_out, last_recurrent_state = self.recurrent_gated_delta_rule(...)
if cache_params is not None:
cache_params.update_recurrent_state(last_recurrent_state, self.layer_idx)
9. generate() 生成全流程
9.1 生成循环时序图
9.2 prepare_inputs_for_generation 的特殊处理
定义在 [modeling_qwen3_5_moe.py:2106-2142](file:///workspace/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L2106):
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, ...,
pixel_values=None, pixel_values_videos=None,
image_grid_thw=None, video_grid_thw=None,
is_first_iteration=False, **kwargs):
model_inputs = super().prepare_inputs_for_generation(...)
# 首次迭代后清除视觉输入,避免重复编码
if not is_first_iteration and use_cache:
model_inputs["pixel_values"] = None
model_inputs["pixel_values_videos"] = None
return model_inputs
9.3 _prepare_position_ids_for_generation 的 3D 位置编码处理
定义在 [modeling_qwen3_5_moe.py:2144-2180](file:///workspace/src/transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py#L2144):
关键代码:
def _prepare_position_ids_for_generation(self, inputs_tensor, model_kwargs):
text_positions = super()._prepare_position_ids_for_generation(inputs_tensor, model_kwargs)
# 增量生成:直接用缓存的 rope_deltas
past_length = 0
if (cache := model_kwargs.get("past_key_values")) is not None:
past_length = cache.get_seq_length()
if past_length != 0 and self.model.rope_deltas is not None:
position_ids = text_positions[None, ...] + self.model.rope_deltas
return position_ids
# 首次生成:计算 3D 位置
if is_input_ids and model_kwargs.get("mm_token_type_ids") is not None and ...:
vision_positions, rope_deltas = self.model.get_rope_index(inputs_tensor, **model_kwargs)
self.model.rope_deltas = rope_deltas
else:
vision_positions = text_positions.unsqueeze(0).expand(3, -1, -1)
self.model.rope_deltas = torch.zeros(...)
# 拼接 [text, T, H, W] → [4, bs, seq]
text_positions = text_positions[None, ...]
position_ids = torch.cat([text_positions, vision_positions], dim=0)
return position_ids
10. 分布式并行
10.1 TP 策略映射图
定义在 [configuration_qwen3_5_moe.py:59-72](file:///workspace/src/transformers/models/qwen3_5_moe/configuration_qwen3_5_moe.py#L59):
10.2 MoE 专家并行(moe_tp_experts)原理图
moe_tp_experts 与普通 colwise/rowwise 的区别:
colwise/rowwise:切分单个线性层的权重矩阵moe_tp_experts:按专家维度切分,每个 GPU 持有256/tp_size个完整专家
11. 状态与生命周期总结
11.1 状态机图
linea... -----------------------^ Expecting 'SPACE', 'NL', 'HIDE_EMPTY', 'scale', 'COMPOSIT_STATE', 'STRUCT_STOP', 'STATE_DESCR', 'ID', 'FORK', 'JOIN', 'CHOICE', 'CONCURRENT', 'note', 'acc_title', 'acc_descr', 'acc_descr_multiline_value', 'CLICK', 'classDef', 'style', 'class', 'direction_tb', 'direction_bt', 'direction_rl', 'direction_lr', 'EDGE_STATE', got 'DESCR'
11.2 关键数据流总结
11.3 核心设计哲学
Qwen3.5-MoE 在 Transformers 中的实现体现了以下设计哲学:
- 模块化继承:通过
modular_qwen3_5_moe.py中的类继承(Qwen3_5MoeGatedDeltaNet ← Qwen3_5GatedDeltaNet),最大化代码复用,最小化重复 - 混合架构统一管理:
DynamicCache根据config.layer_types自动分发不同缓存类型,上层代码无需感知底层差异 - 多模态位置编码:M-RoPE 将文本 1D 位置和视觉 3D 位置统一到同一框架,通过
rope_deltas在增量生成时高效推算 - MoE 专家并行:
moe_tp_experts策略让 256 个专家可以跨 GPU 分布,配合@use_experts_implementation装饰器支持多种优化后端 - 生成效率:
linear_attention层的 O(n) 复杂度 +recurrent_state缓存,使得增量解码无需维护完整的 KV Cache,大幅降低长序列生成的内存开销
更多推荐



所有评论(0)