qwen-moe

一、定義

  1. qwen-moe 代碼講解, 代碼qwen-moe與Mixtral-moe 一樣, 專家模塊
  2. qwen-moe 開源教程
  3. Mixture of Experts (MoE) 模型在Transformer結構中如何實現,Gate的實現一般采用什么函數? Sparse MoE的優勢有哪些?MoE是如何提高模型容量而不顯著增加計算負
    擔的?

二、實現

  1. qwen-moe 代碼講解
    參考:https://blog.csdn.net/v_JULY_v/article/details/135176583?utm_medium=distribute.pc_relevant.none-task-blog-2defaultbaidujs_baidulandingword~default-0-135176583-blog-135046508.235v43pc_blog_bottom_relevance_base4&spm=1001.2101.3001.4242.1&utm_relevant_index=3
import torch
from torch import nn
from torch.nn import functional as F
from transformers.activations import ACT2FNclass Qwen2MoeMLP(nn.Module):def __init__(self, config, intermediate_size=None):super().__init__()self.config = configself.hidden_size = config.hidden_sizeself.intermediate_size = intermediate_sizeself.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)#self.act_fn = ACT2FN[config.hidden_act]def forward(self, x):return self.down_proj(self.gate_proj(x) * self.up_proj(x))class Qwen2MoeSparseMoeBlock(nn.Module):def __init__(self, config):super().__init__()self.num_experts = config.num_expertsself.top_k = config.num_experts_per_tokself.norm_topk_prob = config.norm_topk_prob# gatingself.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)self.experts = nn.ModuleList([Qwen2MoeMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(self.num_experts)])self.shared_expert = Qwen2MoeMLP(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: torch.Tensor) -> torch.Tensor:""" """batch_size, sequence_length, hidden_dim = hidden_states.shapehidden_states = hidden_states.view(-1, hidden_dim)# router_logits: (batch * sequence_length, n_experts)router_logits = self.gate(hidden_states)routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)#選取每個token 對應的前k 個專家routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)if self.norm_topk_prob:routing_weights /= routing_weights.sum(dim=-1, keepdim=True)   #權重歸一化  確保每個token的專家權重之和為1# we cast back to the input dtyperouting_weights = routing_weights.to(hidden_states.dtype)#全為0的張量final_hidden_states = torch.zeros((batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device)# One hot encode the selected experts to create an expert mask# this will be used to easily index which expert is going to be sollicitatedexpert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)  #稀疏矩陣# Loop over all available experts in the model and perform the computation on each expertfor expert_idx in range(self.num_experts):expert_layer = self.experts[expert_idx]                   # 第idx 專家對應的函數idx, top_x = torch.where(expert_mask[expert_idx])         #idx 專家,關注的token, top_x 對應第x 個tokenprint(expert_idx,top_x.cpu().tolist() )   #專家,處理的token# Index the correct hidden states and compute the expert hidden state for# the current expert. We need to make sure to multiply the output hidden# states by `routing_weights` on the corresponding tokens (top-1 and top-2)   專家輸入信息:current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)             #取出對應的token信息current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]       #專家輸出# However `index_add_` only support torch tensors for indexing so we'll use# the `top_x` tensor here. 使用.index_add_函數后在指定位置(top_x)加上了指定值(current_hidden_states)final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))shared_expert_output = self.shared_expert(hidden_states)shared_expert_output = F.sigmoid(self.shared_expert_gate(hidden_states)) * shared_expert_outputfinal_hidden_states = final_hidden_states + shared_expert_outputfinal_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)return final_hidden_states, router_logits# 假設的配置
class Config:def __init__(self):self.num_experts = 8self.num_experts_per_tok = 2self.norm_topk_prob = Trueself.hidden_size = 2self.moe_intermediate_size = 209self.shared_expert_intermediate_size = 20# 檢查是否有可用的GPUdevice = torch.device("cpu")# 創建模型實例
config = Config()
model = Qwen2MoeSparseMoeBlock(config).to(device)input_tensor = torch.randn(1,3,2).to(device)# 前向傳播
output = model(input_tensor)
print(output)

注意:1. 常規思路: 每個token 選擇2 個專家, 然后每個token 傳入2個專家中,進行處理。----->為了加快推理速度----->關注視角由token 轉為專家。在這里插入圖片描述
便把關注視角從“各個token”變成了“各個專家”,當然,大部分情況下 token數遠遠不止下圖這5個,而是比專家數多很多。總之,這么一轉換,最終可以省掉很多循環。
遍歷每個專家,對token 對應的信息整體輸入專家模塊。

# 【代碼塊A】routing_weights
# 每行對應1個token,第0列為其對應排位第1的expert、第1列為其對應排位第2的expert,元素值為相應權重
[[0.5310, 0.4690],[0.5087, 0.4913],[0.5014, 0.4986],[0.5239, 0.4761],[0.5817, 0.4183],[0.5126, 0.4874]]
# 【代碼塊B】expert_mask[expert_idx]
# 下述兩行例子的物理含義為:
# 第一行是“該expert作為排位1的exert存在時,需要處理第9個token;
# 第二行是“該expert作為排位2的expert存在時,需要處理第10、11個token”
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0]]
# 【代碼塊C】idx, top_x = torch.where(expert_mask[expert_idx])
# 以上述expert_mask[expert_idx]樣例為例,對應的torch.where(expert_mask[expert_idx])結果如下
idx: [0, 1, 1]
top_x: [9, 10, 11]
idx對應行索引,top_x對應列索引,例如張量expert_mask[expert_idx]中,出現元素1的索引為(0, 9)(1, 10)(1, 11)
從物理含義來理解,top_x實際上就對應著“關乎當前expert的token索引”,第9、第10、第11個token被“路由”導向了當前所關注的expert,通過top_x可以取到“需要傳入該expert的輸入”,也即第9、第10、第11個token對應的隱向量因此top_x將作為索引用于從全部token的隱向量hidden_states中取出對應token的隱向量
而idx和top_x也會組合起來被用于從expert權重張量routing_weights中取出對應的權重
current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)             #取出top_x的token信息
current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]       #專家輸出# However `index_add_` only support torch tensors for indexing so we'll use
# the `top_x` tensor here. 使用.index_add_函數后在指定位置(top_x)加上了指定值(current_hidden_states)
final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
  1. 開源教程
    https://developer.aliyun.com/article/1471903?spm=a2c6h.28954702.blog-index-detail.67.536b4c2d9ZzdBw

  2. Mixture of Experts (MoE) 模型在Transformer結構中如何實現,Gate的實現一般采用什么函數? Sparse MoE的優勢有哪些?MoE是如何提高模型容量而不顯著增加計算負擔的?

self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=False)

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/20514.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/20514.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/20514.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

C++學習 const 上

🌈 C Primer 的學習筆記 前言 這篇blog 主要是想具體講講新學到的const 當然不止是const 而是基于這個const引申出來的指針和引用。還是需要捋一捋的,這還是有點困難的。 我會把每一節的重點都摘出來,放在前面~ 1??首先講講const 2??…

Linux C/C++動態庫制作

概念:程序在編譯時不會把庫文件的二進制代碼鏈接到目標程序中,而是在運行時候才被載入。 如果多個進程中用到了同一動態庫中的函數或類,那么在內存中只有一份,避免了空間浪費問題。 特點: 程序運行在運行的過程中&…

統計信號處理基礎 習題解答10-6

題目 在例10.1中,把數據模型修正為: 其中是WGN,如果,那么方差,如果,那么方差。求PDF 。把它與經典情況PDF 進行比較,在經典的情況下A是確定性的,是WGN,它的方差為&#…

5.算法講解之-二分查找(簡單易懂)

1.簡介 1.二分查找的思路簡單易懂,較難的是如何處理查找過程中的邊界條件,當較長時間沒寫二分查找的時候就容易忘記如何處理邊界條件。 2.只有多寫代碼,多做筆記就不易忘記邊界條件 2.算法思路 正常查找都是從頭到尾查找一個數字是否在數組中…

使用pycharm+opencv進行視頻抽幀(可以用來擴充數據集)+ labelimg的使用(數據標準)

一.視頻抽幀 1.新創建一個空Pycharm項目文件,命名為streach zhen 注:然后要做一個前期工作 創建opencv環境 (1)我們在這個pycharm項目的終端里面輸入下面的命令: pip install opencv-python --user -i https://pypi.t…

SettingWithCopyWarning: A value is trying to be set on a copy of a slice fro

SettingWithCopyWarning: A value is trying to be set on a copy of a slice fro 錯誤代碼&#xff1a; while i < len(data_csv_data):if data_csv_data[flowmember][i] j:data_csv_data[label][i] data_csv_label[label][j-1]data_csv_data[classes][i]data_csv_label[…

[數據集][目標檢測]獼猴桃檢測數據集VOC+YOLO格式1838張1類別

數據集格式&#xff1a;Pascal VOC格式YOLO格式(不包含分割路徑的txt文件&#xff0c;僅僅包含jpg圖片以及對應的VOC格式xml文件和yolo格式txt文件) 圖片數量(jpg文件個數)&#xff1a;1838 標注數量(xml文件個數)&#xff1a;1838 標注數量(txt文件個數)&#xff1a;1838 標注…

企業級寬表建設

1 寬表概述 寬表&#xff0c;從字面意義上講就是字段比較多的數據庫表&#xff0c;通常情況下是講很多相關的數據&#xff0c;包括實時表、維度表、指標等格言錄在一起形成的一張數據表。 2 寬表的優點 2.1 開發效率提升 由于把不同的信息放在同一張表存儲&#xff0c;寬表…

sensitive-word 敏感詞 v0.17.0 新特性之 IPV4 檢測

敏感詞系列 sensitive-word-admin 敏感詞控臺 v1.2.0 版本開源 sensitive-word-admin v1.3.0 發布 如何支持分布式部署&#xff1f; 01-開源敏感詞工具入門使用 02-如何實現一個敏感詞工具&#xff1f;違禁詞實現思路梳理 03-敏感詞之 StopWord 停止詞優化與特殊符號 04-…

詳解 Spark 核心編程之 RDD 持久化

一、問題引出 /** 案例&#xff1a;對同一份數據文件分別做 WordCount 聚合操作和 Word 分組操作 期望&#xff1a;針對數據文件只進行一次分詞、轉換操作得到 RDD 對象&#xff0c;然后再對該對象分別進行聚合和分組&#xff0c;實現數據重用 */ object TestRDDPersist {def …

Jupyter Notebook快速搭建

Jupyter Notebook why Jupyter Notebook Jupyter Notebook 是一個開源的 Web 應用程序&#xff0c;允許你創建和分享包含實時代碼、方程、可視化和解釋性文本的文檔。其應用包括&#xff1a;數據清洗和轉換、數值模擬、統計建模、數據可視化、機器學習等等。 Jupyter Notebo…

東芝機械人電池低報警解除與機器人多旋轉數據清零

今天啟動一臺設備,觸摸屏一直顯示機器人報警(翻譯過后為電池電量低),更換電池后關機重啟后也不能消除,所以打開示教器,下面就來說說怎么解決此項問題(可以參考官方發的手冊,已手冊為主)。 一,設備 下面來看看機械手的照片與示教器的照片 四軸機械手(六軸機器人有可…

可視化大屏也在卷組件化設計了?分享一些可視化組件

hello&#xff0c;我是大千UI工場&#xff0c;這次分享一些可視化大屏的組件&#xff0c;供大家欣賞。&#xff08;本人沒有源文件提供&#xff09;

動態內存基礎實踐

文章目錄 1.new 創建堆內存對象2.delete釋放內存空間3.malloc申請內存4.free釋放malloc申請的內存空間 1.new 創建堆內存對象 2.delete釋放內存空間 3.malloc申請內存 4.free釋放malloc申請的內存空間 #include <iostream> #include <string>using namespace s…

基礎數學內容重構(后綴0個數)

今天也是參加了一下寧波大學的校賽&#xff0c;其中有一道題是求后綴0的個數&#xff0c;題意是讓我們求一下式子的后綴0個數&#xff1a; 看上去比較復雜&#xff0c;但是通過化簡我們可以知道以上式子就是求&#xff08;n 1&#xff09;&#xff01;&#xff0c;這里化簡的過…

用貪心算法計算十進制數轉二進制數(小數部分)

在上一篇博文用貪心算法計算十進制數轉二進制數&#xff08;整數部分&#xff09;-CSDN博客中&#xff0c;小編介紹了用貪心算法進行十進制整數轉化為二進制數的操作步驟&#xff0c;那么有朋友問我&#xff0c;那十進制小數轉二進制&#xff0c;可以用貪心算法來計算嗎&#x…

[C++]vector的模擬實現

下面是簡單的實現vector的功能&#xff0c;沒有涉及使用內存池等復雜算法來提高效率。 一、vector的概述 &#xff08;一&#xff09;、抽象數據類型定義 容器&#xff1a;向量&#xff08;vector&#xff09;vector是表示大小可以變化的數組的序列容器。像數組一樣&#xf…

帶你學習Mybatis之Mybatis映射文件

Mybatis映射文件 增刪改查 簡單地增刪改查 <select id"selectUser" resultType"User"> select * from user where id #{id}</select><insert id"addUser"> insert into user (name,account) values (#{name},#{account…

[sylar]后端學習:配置環境(一)

1.介紹 基于sylar大神的C高性能后端網絡框架來進行環境配置和后續學習。網站鏈接&#xff1a;sylar的Linux環境配置 2.下載 按照視頻進行下載&#xff0c;并進行下載&#xff0c;并最好還要下載一個vssh的軟件。可以直接在網上搜索即可。 sylar_環境配置&#xff0c;vssh下…

CentOS 運維常用的shell腳本

文章目錄 一、操作系統磁盤空間查看實時獲取系統運行狀態獲取cpu、內存等系統運行狀態獲取系統信息二、應用程序獲取進程運行狀態查看有多少遠程的 IP 在連接本機三、用戶管理統計當前 Linux 系統中可以登錄計算機的賬戶有多少個創建用戶四、自動化管理自動備份日志文件監控的頁…