回滚到逻辑正确版本
Browse files- modeling_densebackward_olmoe0125.py +47 -165
modeling_densebackward_olmoe0125.py
CHANGED
@@ -23,10 +23,27 @@ class DenseBackwardOlmoeSparseMoeBlock(OlmoeSparseMoeBlock):
|
|
23 |
router_logits: Tensor, shape (batch_size * sequence_length, num_experts)
|
24 |
"""
|
25 |
def forward(self, hidden_states: torch.Tensor):
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
batch_size, seq_length, hidden_dim = hidden_states.shape
|
28 |
flat_hidden = hidden_states.view(-1, hidden_dim) # (B*seq_len, hidden_dim)
|
29 |
-
total_tokens = flat_hidden.size(0)
|
30 |
|
31 |
# 计算路由 logits 和全专家 routing 权重
|
32 |
router_logits = self.gate(flat_hidden) # (B*seq_len, num_experts)
|
@@ -40,18 +57,9 @@ class DenseBackwardOlmoeSparseMoeBlock(OlmoeSparseMoeBlock):
|
|
40 |
|
41 |
# ---------- 稀疏计算部分 ----------
|
42 |
# 初始化稀疏输出,shape: (B*seq_len, hidden_dim)
|
43 |
-
sparse_output = torch.zeros((
|
44 |
-
|
45 |
-
|
46 |
-
# shape: (B*seq_len, num_experts, hidden_dim)
|
47 |
-
all_expert_outputs = torch.zeros((total_tokens, self.num_experts, hidden_dim),
|
48 |
-
dtype=flat_hidden.dtype, device=flat_hidden.device)
|
49 |
-
|
50 |
-
# 使用张量掩码跟踪哪些专家被激活
|
51 |
-
# shape: (B*seq_len, num_experts)
|
52 |
-
expert_activated = torch.zeros((total_tokens, self.num_experts),
|
53 |
-
dtype=torch.bool, device=flat_hidden.device)
|
54 |
-
|
55 |
# one-hot 编码 top-k 专家,shape: (B*seq_len, top_k, num_experts)
|
56 |
expert_mask = F.one_hot(selected_experts, num_classes=self.num_experts) # (B*seq_len, top_k, num_experts)
|
57 |
expert_mask = expert_mask.permute(2, 1, 0) # (num_experts, top_k, B*seq_len)
|
@@ -65,30 +73,29 @@ class DenseBackwardOlmoeSparseMoeBlock(OlmoeSparseMoeBlock):
|
|
65 |
weight = routing_weights_topk[top_x, idx].unsqueeze(-1) # (n, 1)
|
66 |
weighted_output = current_output * weight
|
67 |
sparse_output.index_add_(0, top_x, weighted_output.to(flat_hidden.dtype))
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
token_idx = top_x[i]
|
72 |
-
all_expert_outputs[token_idx, expert_idx] = current_output[i]
|
73 |
-
expert_activated[token_idx, expert_idx] = True
|
74 |
-
|
75 |
# ---------- 稀疏计算结束 ----------
|
76 |
|
77 |
# ---------- Dense估计部分 ----------
|
78 |
-
#
|
79 |
-
|
80 |
-
|
81 |
-
#
|
82 |
-
dense_outputs = torch.zeros_like(sparse_output)
|
83 |
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
|
|
|
|
|
|
|
|
92 |
# ---------- Dense估计结束 ----------
|
93 |
|
94 |
# 使用直通梯度:前向输出用稀疏结果,但反向传播时梯度来源于 dense 估计
|
@@ -96,90 +103,6 @@ class DenseBackwardOlmoeSparseMoeBlock(OlmoeSparseMoeBlock):
|
|
96 |
final_output = final_flat.view(batch_size, seq_length, hidden_dim)
|
97 |
return final_output, router_logits
|
98 |
|
99 |
-
def estimate_dense_output_batch(self, total_tokens, selected_experts, routing_weights,
|
100 |
-
expert_activated, all_expert_outputs):
|
101 |
-
"""
|
102 |
-
批量估计所有token的dense输出,优化版本。
|
103 |
-
|
104 |
-
参数:
|
105 |
-
total_tokens: token总数
|
106 |
-
selected_experts: 每个token激活的专家索引,形状 (total_tokens, top_k)
|
107 |
-
routing_weights: 路由权重,形状 (total_tokens, num_experts)
|
108 |
-
expert_activated: 掩码张量,标记每个token激活了哪些专家,形状 (total_tokens, num_experts)
|
109 |
-
all_expert_outputs: 专家输出,形状 (total_tokens, num_experts, hidden_dim)
|
110 |
-
|
111 |
-
返回:
|
112 |
-
dense_outputs: 形状 (total_tokens, hidden_dim)
|
113 |
-
"""
|
114 |
-
hidden_dim = all_expert_outputs.size(-1)
|
115 |
-
num_experts = routing_weights.size(1)
|
116 |
-
device = all_expert_outputs.device
|
117 |
-
|
118 |
-
# 预分配结果张量,注意是hidden_dim而不是num_experts
|
119 |
-
dense_outputs = torch.zeros((total_tokens, hidden_dim), dtype=all_expert_outputs.dtype, device=device)
|
120 |
-
|
121 |
-
# 对每个token单独处理(此处仍需循环,但后续可进一步优化)
|
122 |
-
for token_idx in range(total_tokens):
|
123 |
-
# 对于激活的专家,直接使用输出
|
124 |
-
activated_mask = expert_activated[token_idx] # (num_experts,)
|
125 |
-
|
126 |
-
# 对于未激活的专家,找到估计值
|
127 |
-
for expert_idx in range(num_experts):
|
128 |
-
if activated_mask[expert_idx]:
|
129 |
-
# 直接使用激活专家的输出
|
130 |
-
expert_output = all_expert_outputs[token_idx, expert_idx]
|
131 |
-
else:
|
132 |
-
# 寻找可以用于估计的输出
|
133 |
-
# 找出其他激活了当前专家的token
|
134 |
-
tokens_with_expert = expert_activated[:, expert_idx]
|
135 |
-
|
136 |
-
# 找出同时激活了当前token的某些专家和当前专家的其他token
|
137 |
-
# 首先获取当前token激活的专家
|
138 |
-
current_activated = selected_experts[token_idx]
|
139 |
-
|
140 |
-
# 在其他token中寻找同时激活了current_activated中专家和expert_idx的token
|
141 |
-
valid_tokens = torch.zeros(total_tokens, dtype=torch.bool, device=device)
|
142 |
-
|
143 |
-
# 对于每个其他token,检查它是否同时激活了当前token的某个专家和当前专家
|
144 |
-
for other_token in range(total_tokens):
|
145 |
-
if other_token == token_idx:
|
146 |
-
continue
|
147 |
-
|
148 |
-
# 检查其他token是否激活了当前专家
|
149 |
-
if expert_activated[other_token, expert_idx]:
|
150 |
-
# 检查是否有共同激活的专家
|
151 |
-
other_experts = selected_experts[other_token]
|
152 |
-
common = torch.any(torch.isin(other_experts, current_activated))
|
153 |
-
if common:
|
154 |
-
valid_tokens[other_token] = True
|
155 |
-
|
156 |
-
# 如果找到了有效token
|
157 |
-
if valid_tokens.any():
|
158 |
-
# 获取有效token对当前专家的输出
|
159 |
-
valid_outputs = all_expert_outputs[valid_tokens, expert_idx]
|
160 |
-
# 只计算非零值的平均值
|
161 |
-
mask = (valid_outputs.sum(dim=-1) != 0).to(valid_outputs.dtype).unsqueeze(-1)
|
162 |
-
if mask.sum() > 0:
|
163 |
-
expert_output = (valid_outputs * mask).sum(dim=0) / mask.sum()
|
164 |
-
else:
|
165 |
-
expert_output = torch.zeros(hidden_dim, dtype=all_expert_outputs.dtype, device=device)
|
166 |
-
else:
|
167 |
-
# 如果没有找到有效token,使用所有激活了当前专家的token的输出
|
168 |
-
if tokens_with_expert.any():
|
169 |
-
all_valid_outputs = all_expert_outputs[tokens_with_expert, expert_idx]
|
170 |
-
mask = (all_valid_outputs.sum(dim=-1) != 0).to(all_valid_outputs.dtype).unsqueeze(-1)
|
171 |
-
if mask.sum() > 0:
|
172 |
-
expert_output = (all_valid_outputs * mask).sum(dim=0) / mask.sum()
|
173 |
-
else:
|
174 |
-
expert_output = torch.zeros(hidden_dim, dtype=all_expert_outputs.dtype, device=device)
|
175 |
-
else:
|
176 |
-
expert_output = torch.zeros(hidden_dim, dtype=all_expert_outputs.dtype, device=device)
|
177 |
-
|
178 |
-
# 根据routing权重加权
|
179 |
-
dense_outputs[token_idx] += routing_weights[token_idx, expert_idx] * expert_output
|
180 |
-
|
181 |
-
return dense_outputs
|
182 |
-
|
183 |
def estimate_dense_output(self, token_idx, activated, gate_prob, activated_outputs, all_routing, all_expert_outputs):
|
184 |
"""
|
185 |
对于当前 token,根据 mini-batch 中的信息估计 dense 输出。
|
@@ -207,21 +130,9 @@ class DenseBackwardOlmoeSparseMoeBlock(OlmoeSparseMoeBlock):
|
|
207 |
indices.append(idx)
|
208 |
if indices:
|
209 |
selected_outputs = all_expert_outputs[indices, i, :] # (n, hidden_dim)
|
210 |
-
|
211 |
-
mask = (selected_outputs.sum(dim=-1) != 0).to(selected_outputs.dtype).unsqueeze(-1)
|
212 |
-
if mask.sum() > 0:
|
213 |
-
estimated = (selected_outputs * mask).sum(dim=0) / mask.sum()
|
214 |
-
else:
|
215 |
-
# 如果全是零,返回零向量
|
216 |
-
estimated = torch.zeros_like(selected_outputs[0])
|
217 |
else:
|
218 |
-
|
219 |
-
mask = (all_outputs.sum(dim=-1) != 0).to(all_outputs.dtype).unsqueeze(-1)
|
220 |
-
if mask.sum() > 0:
|
221 |
-
estimated = (all_outputs * mask).sum(dim=0) / mask.sum()
|
222 |
-
else:
|
223 |
-
# 如果全是零,返回零向量
|
224 |
-
estimated = torch.zeros_like(all_outputs[0])
|
225 |
dense_parts[i] = estimated
|
226 |
# 按 gate_prob 加权求和各专家输出
|
227 |
estimated_dense = 0
|
@@ -241,49 +152,20 @@ class DenseBackwardOLMoEForCausalLM(OlmoeForCausalLM):
|
|
241 |
base_model_prefix = "olmoe"
|
242 |
|
243 |
def __init__(self, config):
|
244 |
-
# 首先调用父类初始化方法
|
245 |
super().__init__(config)
|
246 |
-
|
247 |
-
# 不要尝试重新赋值self,而是从预训练模型加载并更新当前模型
|
248 |
-
pretrained_model = OlmoeForCausalLM.from_pretrained("allenai/OLMoE-1B-7B-0125")
|
249 |
-
|
250 |
-
# 复制预训练模型的状态到当前模型
|
251 |
-
self.config = pretrained_model.config
|
252 |
-
self.model = pretrained_model.model
|
253 |
-
self.vocab_size = pretrained_model.vocab_size
|
254 |
-
self.router_aux_loss_coef = pretrained_model.router_aux_loss_coef
|
255 |
-
self.num_experts = pretrained_model.num_experts
|
256 |
-
self.lm_head = pretrained_model.lm_head
|
257 |
-
|
258 |
# 遍历模型中所有 decoder 层,替换每个 OlmoeSparseMoeBlock 为 DenseBackward 版本
|
259 |
# 此处假设官方模型在 self.model.layers 中组织 decoder 层,
|
260 |
# 且每层中 mlp 模块包含属性 sparse_moe_block。
|
261 |
for layer in self.model.layers:
|
262 |
-
if hasattr(layer.mlp, "
|
263 |
-
|
264 |
-
orig_block = layer.mlp
|
265 |
# 通过直接复制原版属性创建新的块
|
266 |
new_block = DenseBackwardOlmoeSparseMoeBlock(config) # 或其他适当参数
|
267 |
# 然后手动复制需要共享的属性:
|
268 |
new_block.gate = orig_block.gate
|
269 |
new_block.experts = orig_block.experts
|
|
|
270 |
new_block.num_experts = orig_block.num_experts
|
271 |
new_block.top_k = orig_block.top_k
|
272 |
new_block.norm_topk_prob = orig_block.norm_topk_prob
|
273 |
-
layer.mlp = new_block
|
274 |
-
print(type(layer.mlp))
|
275 |
-
|
276 |
-
def main():
|
277 |
-
config = DenseBackwardOLMoEConfig( # 官方模型参数
|
278 |
-
model_marker="DenseBackward_olmoe_marker",
|
279 |
-
)
|
280 |
-
# 创建自定义模��实例
|
281 |
-
model = DenseBackwardOLMoEForCausalLM(config)
|
282 |
-
print(type(model))
|
283 |
-
print(type(model.model))
|
284 |
-
print(type(model.model.layers[0]))
|
285 |
-
print(type(model.model.layers[0].mlp))
|
286 |
-
print(type(model.model.layers[0].mlp.experts))
|
287 |
-
|
288 |
-
if __name__ == "__main__":
|
289 |
-
main()
|
|
|
23 |
router_logits: Tensor, shape (batch_size * sequence_length, num_experts)
|
24 |
"""
|
25 |
def forward(self, hidden_states: torch.Tensor):
|
26 |
+
"""
|
27 |
+
输入:
|
28 |
+
hidden_states: Tensor, shape (batch_size, sequence_length, hidden_dim)
|
29 |
+
输出:
|
30 |
+
final_output: Tensor, shape (batch_size, sequence_length, hidden_dim)
|
31 |
+
router_logits: Tensor, shape (batch_size * sequence_length, num_experts)
|
32 |
+
实现思路:
|
33 |
+
1. 将输入展平为 (B*seq_len, hidden_dim),通过 self.gate 得到 router_logits,
|
34 |
+
并计算全专家的 routing 权重(softmax 后)。
|
35 |
+
2. 对 routing 权重取 top-k,得到 routing_weights_topk 与 selected_experts;
|
36 |
+
如配置要求,归一化 top-k 概率。
|
37 |
+
3. 稀疏计算部分:仅计算每个 token 对于 top-k 专家的输出,
|
38 |
+
并累加得到 sparse_output(保留原版计算流程,同时记录激活专家的实际输出)。
|
39 |
+
4. Dense 估计部分:先计算所有专家对所有 token 的输出(all_expert_outputs),
|
40 |
+
再逐 token 调用 estimate_dense_output 得到 dense 输出(dense_estimated)。
|
41 |
+
5. 使用直通梯度技巧:前向输出用 sparse_output,但梯度来源于 dense_estimated。
|
42 |
+
6. 最后 reshape 为 (batch_size, sequence_length, hidden_dim) 并返回 final_output 及 router_logits.
|
43 |
+
"""
|
44 |
+
#determine the shape of hidden_states
|
45 |
batch_size, seq_length, hidden_dim = hidden_states.shape
|
46 |
flat_hidden = hidden_states.view(-1, hidden_dim) # (B*seq_len, hidden_dim)
|
|
|
47 |
|
48 |
# 计算路由 logits 和全专家 routing 权重
|
49 |
router_logits = self.gate(flat_hidden) # (B*seq_len, num_experts)
|
|
|
57 |
|
58 |
# ---------- 稀疏计算部分 ----------
|
59 |
# 初始化稀疏输出,shape: (B*seq_len, hidden_dim)
|
60 |
+
sparse_output = torch.zeros((flat_hidden.size(0), hidden_dim), dtype=flat_hidden.dtype, device=flat_hidden.device)
|
61 |
+
# 用于记录每个 token 对激活专家的实际输出
|
62 |
+
activated_outputs = [{} for _ in range(flat_hidden.size(0))]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
# one-hot 编码 top-k 专家,shape: (B*seq_len, top_k, num_experts)
|
64 |
expert_mask = F.one_hot(selected_experts, num_classes=self.num_experts) # (B*seq_len, top_k, num_experts)
|
65 |
expert_mask = expert_mask.permute(2, 1, 0) # (num_experts, top_k, B*seq_len)
|
|
|
73 |
weight = routing_weights_topk[top_x, idx].unsqueeze(-1) # (n, 1)
|
74 |
weighted_output = current_output * weight
|
75 |
sparse_output.index_add_(0, top_x, weighted_output.to(flat_hidden.dtype))
|
76 |
+
# 保存当前 token 对该专家的实际输出
|
77 |
+
for pos, token_idx in enumerate(top_x.tolist()):
|
78 |
+
activated_outputs[token_idx][expert_idx] = current_output[pos]
|
|
|
|
|
|
|
|
|
79 |
# ---------- 稀疏计算结束 ----------
|
80 |
|
81 |
# ---------- Dense估计部分 ----------
|
82 |
+
# 计算所有专家对所有 token 的 dense 输出,shape: (B*seq_len, num_experts, hidden_dim)
|
83 |
+
all_expert_outputs = torch.stack([expert(flat_hidden) for expert in self.experts], dim=1)
|
84 |
+
# 将 selected_experts 转换为 list,每个 token 的激活专家列表
|
85 |
+
all_routing = selected_experts.tolist() # 长度为 (B*seq_len)
|
|
|
86 |
|
87 |
+
dense_outputs = []
|
88 |
+
for i in range(flat_hidden.size(0)):
|
89 |
+
dense_est = self.estimate_dense_output(
|
90 |
+
token_idx=i,
|
91 |
+
activated=all_routing[i], # 当前 token 激活的专家列表,例如 [a, b]
|
92 |
+
gate_prob=routing_weights[i], # 当前 token 的完整 routing 权重 (num_experts,)
|
93 |
+
activated_outputs=activated_outputs[i], # 当前 token 对激活专家的实际输出
|
94 |
+
all_routing=all_routing, # 全 batch 每个 token 的激活专家列表(list of lists)
|
95 |
+
all_expert_outputs=all_expert_outputs # (B*seq_len, num_experts, hidden_dim)
|
96 |
+
)
|
97 |
+
dense_outputs.append(dense_est.unsqueeze(0))
|
98 |
+
dense_outputs = torch.cat(dense_outputs, dim=0) # (B*seq_len, hidden_dim)
|
99 |
# ---------- Dense估计结束 ----------
|
100 |
|
101 |
# 使用直通梯度:前向输出用稀疏结果,但反向传播时梯度来源于 dense 估计
|
|
|
103 |
final_output = final_flat.view(batch_size, seq_length, hidden_dim)
|
104 |
return final_output, router_logits
|
105 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
def estimate_dense_output(self, token_idx, activated, gate_prob, activated_outputs, all_routing, all_expert_outputs):
|
107 |
"""
|
108 |
对于当前 token,根据 mini-batch 中的信息估计 dense 输出。
|
|
|
130 |
indices.append(idx)
|
131 |
if indices:
|
132 |
selected_outputs = all_expert_outputs[indices, i, :] # (n, hidden_dim)
|
133 |
+
estimated = selected_outputs.mean(dim=0)
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
else:
|
135 |
+
estimated = all_expert_outputs[:, i, :].mean(dim=0)
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
dense_parts[i] = estimated
|
137 |
# 按 gate_prob 加权求和各专家输出
|
138 |
estimated_dense = 0
|
|
|
152 |
base_model_prefix = "olmoe"
|
153 |
|
154 |
def __init__(self, config):
|
|
|
155 |
super().__init__(config)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
156 |
# 遍历模型中所有 decoder 层,替换每个 OlmoeSparseMoeBlock 为 DenseBackward 版本
|
157 |
# 此处假设官方模型在 self.model.layers 中组织 decoder 层,
|
158 |
# 且每层中 mlp 模块包含属性 sparse_moe_block。
|
159 |
for layer in self.model.layers:
|
160 |
+
if hasattr(layer.mlp, "sparse_moe_block"):
|
161 |
+
orig_block = layer.mlp.sparse_moe_block
|
|
|
162 |
# 通过直接复制原版属性创建新的块
|
163 |
new_block = DenseBackwardOlmoeSparseMoeBlock(config) # 或其他适当参数
|
164 |
# 然后手动复制需要共享的属性:
|
165 |
new_block.gate = orig_block.gate
|
166 |
new_block.experts = orig_block.experts
|
167 |
+
new_block.router = orig_block.router
|
168 |
new_block.num_experts = orig_block.num_experts
|
169 |
new_block.top_k = orig_block.top_k
|
170 |
new_block.norm_topk_prob = orig_block.norm_topk_prob
|
171 |
+
layer.mlp.sparse_moe_block = new_block
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|