Update modeling_densebackward_olmoe0125.py
Browse files- modeling_densebackward_olmoe0125.py +161 -160
modeling_densebackward_olmoe0125.py
CHANGED
@@ -23,173 +23,173 @@ 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 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
# 创建一个张量存储激活专家的输出,避免使用Python字典
|
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)
|
58 |
-
|
59 |
-
for expert_idx in range(self.num_experts):
|
60 |
-
expert_layer = self.experts[expert_idx]
|
61 |
-
idx, top_x = torch.where(expert_mask[expert_idx])
|
62 |
-
if top_x.numel() > 0:
|
63 |
-
current_state = flat_hidden[top_x] # (n, hidden_dim)
|
64 |
-
current_output = expert_layer(current_state) # (n, hidden_dim)
|
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 |
-
all_expert_outputs.index_copy_(0, top_x,
|
71 |
-
torch.zeros_like(all_expert_outputs[0:top_x.size(0)]).scatter_(
|
72 |
-
1, expert_idx * torch.ones((top_x.size(0), 1),
|
73 |
-
dtype=torch.long,
|
74 |
-
device=flat_hidden.device),
|
75 |
-
current_output.unsqueeze(1)))
|
76 |
-
|
77 |
-
# 标记哪些专家被激活
|
78 |
-
expert_activated.index_copy_(0, top_x,
|
79 |
-
torch.zeros_like(expert_activated[0:top_x.size(0)]).scatter_(
|
80 |
-
1, expert_idx * torch.ones((top_x.size(0), 1),
|
81 |
-
dtype=torch.long,
|
82 |
-
device=flat_hidden.device),
|
83 |
-
torch.ones((top_x.size(0), 1),
|
84 |
-
dtype=torch.bool,
|
85 |
-
device=flat_hidden.device)))
|
86 |
-
# ---------- 稀疏计算结束 ----------
|
87 |
-
|
88 |
-
# ---------- Dense估计部分 ----------
|
89 |
-
# 从GPU获取必要信息,避免过多的tensor->list转换
|
90 |
-
selected_experts_gpu = selected_experts # 保持在GPU上
|
91 |
-
|
92 |
-
# 预分配结果张量,避免在循环中append
|
93 |
-
dense_outputs = torch.zeros_like(sparse_output)
|
94 |
-
|
95 |
-
# 使用向量化的estimate_dense_output函数
|
96 |
-
dense_outputs = self.estimate_dense_output_batch(
|
97 |
-
total_tokens=total_tokens,
|
98 |
-
selected_experts=selected_experts_gpu,
|
99 |
-
routing_weights=routing_weights,
|
100 |
-
expert_activated=expert_activated,
|
101 |
-
all_expert_outputs=all_expert_outputs
|
102 |
-
)
|
103 |
-
# ---------- Dense估计结束 ----------
|
104 |
-
|
105 |
-
# 使用直通梯度:前向输出用稀疏结果,但反向传播时梯度来源于 dense 估计
|
106 |
-
final_flat = sparse_output.detach() + (dense_outputs - dense_outputs.detach())
|
107 |
-
final_output = final_flat.view(batch_size, seq_length, hidden_dim)
|
108 |
-
return final_output, router_logits
|
109 |
-
|
110 |
-
def estimate_dense_output_batch(self, total_tokens, selected_experts, routing_weights,
|
111 |
-
expert_activated, all_expert_outputs):
|
112 |
-
"""
|
113 |
-
批量估计所有token的dense输出,优化版本。
|
114 |
-
|
115 |
-
参数:
|
116 |
-
total_tokens: token总数
|
117 |
-
selected_experts: 每个token激活的专家索引,形状 (total_tokens, top_k)
|
118 |
-
routing_weights: 路由权重,形状 (total_tokens, num_experts)
|
119 |
-
expert_activated: 掩码张量,标记每个token激活了哪些专家,形状 (total_tokens, num_experts)
|
120 |
-
all_expert_outputs: 专家输出,形状 (total_tokens, num_experts, hidden_dim)
|
121 |
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
num_experts = routing_weights.size(1)
|
127 |
-
device = all_expert_outputs.device
|
128 |
-
|
129 |
-
# 预分配结果张量
|
130 |
-
dense_outputs = torch.zeros((total_tokens, hidden_dim), dtype=all_expert_outputs.dtype, device=device)
|
131 |
-
|
132 |
-
# 对每个token单独处理(此处仍需循环,但后续可进一步优化)
|
133 |
-
for token_idx in range(total_tokens):
|
134 |
-
# 对于激活的专家,直接使用输出
|
135 |
-
activated_mask = expert_activated[token_idx] # (num_experts,)
|
136 |
|
137 |
-
#
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
#
|
152 |
-
|
|
|
|
|
153 |
|
154 |
-
#
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
# 检查是否有共同激活的专家
|
162 |
-
other_experts = selected_experts[other_token]
|
163 |
-
common = torch.any(torch.isin(other_experts, current_activated))
|
164 |
-
if common:
|
165 |
-
valid_tokens[other_token] = True
|
166 |
|
167 |
-
#
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
177 |
else:
|
178 |
-
#
|
179 |
-
|
180 |
-
|
181 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
182 |
if mask.sum() > 0:
|
183 |
-
expert_output = (
|
184 |
else:
|
185 |
expert_output = torch.zeros(hidden_dim, dtype=all_expert_outputs.dtype, device=device)
|
186 |
else:
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
193 |
|
194 |
|
195 |
class DenseBackwardOLMoEForCausalLM(OlmoeForCausalLM):
|
@@ -238,13 +238,14 @@ class DenseBackwardOLMoEForCausalLM(OlmoeForCausalLM):
|
|
238 |
def main():
|
239 |
config = DenseBackwardOLMoEConfig( # 官方模型参数
|
240 |
model_marker="DenseBackward_olmoe_marker",
|
241 |
-
)
|
242 |
-
# 创建自定义模型实例
|
243 |
model = DenseBackwardOLMoEForCausalLM(config)
|
244 |
print(type(model))
|
245 |
print(type(model.model))
|
246 |
print(type(model.model.layers[0]))
|
247 |
print(type(model.model.layers[0].mlp))
|
248 |
print(type(model.model.layers[0].mlp.experts))
|
|
|
249 |
if __name__ == "__main__":
|
250 |
main()
|
|
|
23 |
router_logits: Tensor, shape (batch_size * sequence_length, num_experts)
|
24 |
"""
|
25 |
def forward(self, hidden_states: torch.Tensor):
|
26 |
+
# determine the shape of hidden_states
|
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)
|
33 |
+
routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float) # (B*seq_len, num_experts)
|
34 |
+
|
35 |
+
# Top-k 选择
|
36 |
+
routing_weights_topk, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
|
37 |
+
if self.norm_topk_prob:
|
38 |
+
routing_weights_topk = routing_weights_topk / routing_weights_topk.sum(dim=-1, keepdim=True)
|
39 |
+
routing_weights_topk = routing_weights_topk.to(flat_hidden.dtype)
|
40 |
+
|
41 |
+
# ---------- 稀疏计算部分 ----------
|
42 |
+
# 初始化稀疏输出,shape: (B*seq_len, hidden_dim)
|
43 |
+
sparse_output = torch.zeros((total_tokens, hidden_dim), dtype=flat_hidden.dtype, device=flat_hidden.device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
+
# 创建一个张量存储激活专家的输出,避免使用Python字典
|
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)
|
58 |
+
|
59 |
+
for expert_idx in range(self.num_experts):
|
60 |
+
expert_layer = self.experts[expert_idx]
|
61 |
+
idx, top_x = torch.where(expert_mask[expert_idx])
|
62 |
+
if top_x.numel() > 0:
|
63 |
+
current_state = flat_hidden[top_x] # (n, hidden_dim)
|
64 |
+
current_output = expert_layer(current_state) # (n, hidden_dim)
|
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 |
+
all_expert_outputs.index_copy_(0, top_x,
|
71 |
+
torch.zeros_like(all_expert_outputs[0:top_x.size(0)]).scatter_(
|
72 |
+
1, expert_idx * torch.ones((top_x.size(0), 1),
|
73 |
+
dtype=torch.long,
|
74 |
+
device=flat_hidden.device),
|
75 |
+
current_output.unsqueeze(1)))
|
|
|
|
|
|
|
|
|
|
|
76 |
|
77 |
+
# 标记哪些专家被激活
|
78 |
+
expert_activated.index_copy_(0, top_x,
|
79 |
+
torch.zeros_like(expert_activated[0:top_x.size(0)]).scatter_(
|
80 |
+
1, expert_idx * torch.ones((top_x.size(0), 1),
|
81 |
+
dtype=torch.long,
|
82 |
+
device=flat_hidden.device),
|
83 |
+
torch.ones((top_x.size(0), 1),
|
84 |
+
dtype=torch.bool,
|
85 |
+
device=flat_hidden.device)))
|
86 |
+
# ---------- 稀疏计算结束 ----------
|
87 |
+
|
88 |
+
# ---------- Dense估计部分 ----------
|
89 |
+
# 从GPU获取必要信息,避免过多的tensor->list转换
|
90 |
+
selected_experts_gpu = selected_experts # 保持在GPU上
|
91 |
+
|
92 |
+
# 预分配结果张量,避免在循环中append
|
93 |
+
dense_outputs = torch.zeros_like(sparse_output)
|
94 |
+
|
95 |
+
# 使用向量化的estimate_dense_output函数
|
96 |
+
dense_outputs = self.estimate_dense_output_batch(
|
97 |
+
total_tokens=total_tokens,
|
98 |
+
selected_experts=selected_experts_gpu,
|
99 |
+
routing_weights=routing_weights,
|
100 |
+
expert_activated=expert_activated,
|
101 |
+
all_expert_outputs=all_expert_outputs
|
102 |
+
)
|
103 |
+
# ---------- Dense估计结束 ----------
|
104 |
+
|
105 |
+
# 使用直通梯度:前向输出用稀疏结果,但反向传播时梯度来源于 dense 估计
|
106 |
+
final_flat = sparse_output.detach() + (dense_outputs - dense_outputs.detach())
|
107 |
+
final_output = final_flat.view(batch_size, seq_length, hidden_dim)
|
108 |
+
return final_output, router_logits
|
109 |
+
|
110 |
+
def estimate_dense_output_batch(self, total_tokens, selected_experts, routing_weights,
|
111 |
+
expert_activated, all_expert_outputs):
|
112 |
+
"""
|
113 |
+
批量估计所有token的dense输出,优化版本。
|
114 |
+
|
115 |
+
参数:
|
116 |
+
total_tokens: token总数
|
117 |
+
selected_experts: 每个token激活的专家索引,形状 (total_tokens, top_k)
|
118 |
+
routing_weights: 路由权重,形状 (total_tokens, num_experts)
|
119 |
+
expert_activated: 掩码张量,标记每个token激活了哪些专家,形状 (total_tokens, num_experts)
|
120 |
+
all_expert_outputs: 专家输出,形状 (total_tokens, num_experts, hidden_dim)
|
121 |
+
|
122 |
+
返回:
|
123 |
+
dense_outputs: 形状 (total_tokens, hidden_dim)
|
124 |
+
"""
|
125 |
+
hidden_dim = all_expert_outputs.size(-1)
|
126 |
+
num_experts = routing_weights.size(1)
|
127 |
+
device = all_expert_outputs.device
|
128 |
+
|
129 |
+
# 预分配结果张量
|
130 |
+
dense_outputs = torch.zeros((total_tokens, hidden_dim), dtype=all_expert_outputs.dtype, device=device)
|
131 |
+
|
132 |
+
# 对每个token单独处理(此处仍需循环,但后续可进一步优化)
|
133 |
+
for token_idx in range(total_tokens):
|
134 |
+
# 对于激活的专家,直接使用输出
|
135 |
+
activated_mask = expert_activated[token_idx] # (num_experts,)
|
136 |
+
|
137 |
+
# 对于未激活的专家,找到估计值
|
138 |
+
for expert_idx in range(num_experts):
|
139 |
+
if activated_mask[expert_idx]:
|
140 |
+
# 直接使用激活专家的输出
|
141 |
+
expert_output = all_expert_outputs[token_idx, expert_idx]
|
142 |
else:
|
143 |
+
# 寻找可以用于估计的输出
|
144 |
+
# 找出其他激活了当前专家的token
|
145 |
+
tokens_with_expert = expert_activated[:, expert_idx]
|
146 |
+
|
147 |
+
# 找出同时激活了当前token的某些专家和当前专家的其他token
|
148 |
+
# 首先获取当前token激活的专家
|
149 |
+
current_activated = selected_experts[token_idx]
|
150 |
+
|
151 |
+
# 在其他token中寻找同时激活了current_activated中专家和expert_idx的token
|
152 |
+
valid_tokens = torch.zeros(total_tokens, dtype=torch.bool, device=device)
|
153 |
+
|
154 |
+
# 对于每个其他token,检查它是否同时激活了当前token的某个专家和当前专家
|
155 |
+
for other_token in range(total_tokens):
|
156 |
+
if other_token == token_idx:
|
157 |
+
continue
|
158 |
+
|
159 |
+
# 检查其他token是否激活了当前专家
|
160 |
+
if expert_activated[other_token, expert_idx]:
|
161 |
+
# 检查是否有共同激活的专家
|
162 |
+
other_experts = selected_experts[other_token]
|
163 |
+
common = torch.any(torch.isin(other_experts, current_activated))
|
164 |
+
if common:
|
165 |
+
valid_tokens[other_token] = True
|
166 |
+
|
167 |
+
# 如果找到了有效token
|
168 |
+
if valid_tokens.any():
|
169 |
+
# 获取有效token对当前专家的输出
|
170 |
+
valid_outputs = all_expert_outputs[valid_tokens, expert_idx]
|
171 |
+
# 只计算非零值的平均值
|
172 |
+
mask = (valid_outputs.sum(dim=-1) != 0).to(valid_outputs.dtype).unsqueeze(-1)
|
173 |
if mask.sum() > 0:
|
174 |
+
expert_output = (valid_outputs * mask).sum(dim=0) / mask.sum()
|
175 |
else:
|
176 |
expert_output = torch.zeros(hidden_dim, dtype=all_expert_outputs.dtype, device=device)
|
177 |
else:
|
178 |
+
# 如果没有找到有效token,使用所有激活了当前专家的token的输出
|
179 |
+
if tokens_with_expert.any():
|
180 |
+
all_valid_outputs = all_expert_outputs[tokens_with_expert, expert_idx]
|
181 |
+
mask = (all_valid_outputs.sum(dim=-1) != 0).to(all_valid_outputs.dtype).unsqueeze(-1)
|
182 |
+
if mask.sum() > 0:
|
183 |
+
expert_output = (all_valid_outputs * mask).sum(dim=0) / mask.sum()
|
184 |
+
else:
|
185 |
+
expert_output = torch.zeros(hidden_dim, dtype=all_expert_outputs.dtype, device=device)
|
186 |
+
else:
|
187 |
+
expert_output = torch.zeros(hidden_dim, dtype=all_expert_outputs.dtype, device=device)
|
188 |
+
|
189 |
+
# 根据routing权重加权
|
190 |
+
dense_outputs[token_idx] += routing_weights[token_idx, expert_idx] * expert_output
|
191 |
+
|
192 |
+
return dense_outputs
|
193 |
|
194 |
|
195 |
class DenseBackwardOLMoEForCausalLM(OlmoeForCausalLM):
|
|
|
238 |
def main():
|
239 |
config = DenseBackwardOLMoEConfig( # 官方模型参数
|
240 |
model_marker="DenseBackward_olmoe_marker",
|
241 |
+
)
|
242 |
+
# 创建自定义模型实例
|
243 |
model = DenseBackwardOLMoEForCausalLM(config)
|
244 |
print(type(model))
|
245 |
print(type(model.model))
|
246 |
print(type(model.model.layers[0]))
|
247 |
print(type(model.model.layers[0].mlp))
|
248 |
print(type(model.model.layers[0].mlp.experts))
|
249 |
+
|
250 |
if __name__ == "__main__":
|
251 |
main()
|