|
|
|
|
|
import torch |
|
import torch.nn as nn |
|
import torch.nn.functional as F |
|
|
|
|
|
from transformers.models.olmoe.modeling_olmoe import OlmoeForCausalLM, OlmoeSparseMoeBlock, OlmoeMLP |
|
from .configuration_densebackward_olmoe0125 import DenseBackwardOLMoEConfig |
|
|
|
|
|
class DenseBackwardOlmoeSparseMoeBlock(OlmoeSparseMoeBlock): |
|
""" |
|
继承自官方 OlmoeSparseMoeBlock,实现 dense backward 功能: |
|
前向输出依旧保持与官方相同(即稀疏计算结果), |
|
但在反向传播时,通过直通梯度让 dense 计算的梯度传递回来, |
|
dense 输出通过对每个专家在所有 token 上进行计算,并利用全 routing 权重加权获得。 |
|
|
|
输入: |
|
hidden_states: Tensor, shape (batch_size, sequence_length, hidden_dim) |
|
输出: |
|
final_output: Tensor, shape (batch_size, sequence_length, hidden_dim) |
|
router_logits: Tensor, shape (batch_size * sequence_length, num_experts) |
|
""" |
|
def forward(self, hidden_states: torch.Tensor): |
|
|
|
batch_size, seq_length, hidden_dim = hidden_states.shape |
|
flat_hidden = hidden_states.view(-1, hidden_dim) |
|
total_tokens = flat_hidden.size(0) |
|
|
|
|
|
router_logits = self.gate(flat_hidden) |
|
routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float) |
|
|
|
|
|
routing_weights_topk, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1) |
|
if self.norm_topk_prob: |
|
routing_weights_topk = routing_weights_topk / routing_weights_topk.sum(dim=-1, keepdim=True) |
|
routing_weights_topk = routing_weights_topk.to(flat_hidden.dtype) |
|
|
|
|
|
|
|
sparse_output = torch.zeros((total_tokens, hidden_dim), dtype=flat_hidden.dtype, device=flat_hidden.device) |
|
|
|
|
|
|
|
all_expert_outputs = torch.zeros((total_tokens, self.num_experts, hidden_dim), |
|
dtype=flat_hidden.dtype, device=flat_hidden.device) |
|
|
|
|
|
|
|
expert_activated = torch.zeros((total_tokens, self.num_experts), |
|
dtype=torch.bool, device=flat_hidden.device) |
|
|
|
|
|
expert_mask = F.one_hot(selected_experts, num_classes=self.num_experts) |
|
expert_mask = expert_mask.permute(2, 1, 0) |
|
|
|
for expert_idx in range(self.num_experts): |
|
expert_layer = self.experts[expert_idx] |
|
idx, top_x = torch.where(expert_mask[expert_idx]) |
|
if top_x.numel() > 0: |
|
current_state = flat_hidden[top_x] |
|
current_output = expert_layer(current_state) |
|
weight = routing_weights_topk[top_x, idx].unsqueeze(-1) |
|
weighted_output = current_output * weight |
|
sparse_output.index_add_(0, top_x, weighted_output.to(flat_hidden.dtype)) |
|
|
|
|
|
for i in range(top_x.shape[0]): |
|
token_idx = top_x[i] |
|
all_expert_outputs[token_idx, expert_idx] = current_output[i] |
|
expert_activated[token_idx, expert_idx] = True |
|
|
|
|
|
|
|
|
|
|
|
selected_experts_gpu = selected_experts |
|
|
|
|
|
dense_outputs = torch.zeros_like(sparse_output) |
|
|
|
|
|
dense_outputs = self.estimate_dense_output_batch( |
|
total_tokens=total_tokens, |
|
selected_experts=selected_experts_gpu, |
|
routing_weights=routing_weights, |
|
expert_activated=expert_activated, |
|
all_expert_outputs=all_expert_outputs |
|
) |
|
|
|
|
|
|
|
final_flat = sparse_output.detach() + (dense_outputs - dense_outputs.detach()) |
|
final_output = final_flat.view(batch_size, seq_length, hidden_dim) |
|
return final_output, router_logits |
|
|
|
def estimate_dense_output_batch(self, total_tokens, selected_experts, routing_weights, |
|
expert_activated, all_expert_outputs): |
|
""" |
|
批量估计所有token的dense输出,优化版本。 |
|
|
|
参数: |
|
total_tokens: token总数 |
|
selected_experts: 每个token激活的专家索引,形状 (total_tokens, top_k) |
|
routing_weights: 路由权重,形状 (total_tokens, num_experts) |
|
expert_activated: 掩码张量,标记每个token激活了哪些专家,形状 (total_tokens, num_experts) |
|
all_expert_outputs: 专家输出,形状 (total_tokens, num_experts, hidden_dim) |
|
|
|
返回: |
|
dense_outputs: 形状 (total_tokens, hidden_dim) |
|
""" |
|
hidden_dim = all_expert_outputs.size(-1) |
|
num_experts = routing_weights.size(1) |
|
device = all_expert_outputs.device |
|
|
|
|
|
dense_outputs = torch.zeros((total_tokens, hidden_dim), dtype=all_expert_outputs.dtype, device=device) |
|
|
|
|
|
for token_idx in range(total_tokens): |
|
|
|
activated_mask = expert_activated[token_idx] |
|
|
|
|
|
for expert_idx in range(num_experts): |
|
if activated_mask[expert_idx]: |
|
|
|
expert_output = all_expert_outputs[token_idx, expert_idx] |
|
else: |
|
|
|
|
|
tokens_with_expert = expert_activated[:, expert_idx] |
|
|
|
|
|
|
|
current_activated = selected_experts[token_idx] |
|
|
|
|
|
valid_tokens = torch.zeros(total_tokens, dtype=torch.bool, device=device) |
|
|
|
|
|
for other_token in range(total_tokens): |
|
if other_token == token_idx: |
|
continue |
|
|
|
|
|
if expert_activated[other_token, expert_idx]: |
|
|
|
other_experts = selected_experts[other_token] |
|
common = torch.any(torch.isin(other_experts, current_activated)) |
|
if common: |
|
valid_tokens[other_token] = True |
|
|
|
|
|
if valid_tokens.any(): |
|
|
|
valid_outputs = all_expert_outputs[valid_tokens, expert_idx] |
|
|
|
mask = (valid_outputs.sum(dim=-1) != 0).to(valid_outputs.dtype).unsqueeze(-1) |
|
if mask.sum() > 0: |
|
expert_output = (valid_outputs * mask).sum(dim=0) / mask.sum() |
|
else: |
|
expert_output = torch.zeros(hidden_dim, dtype=all_expert_outputs.dtype, device=device) |
|
else: |
|
|
|
if tokens_with_expert.any(): |
|
all_valid_outputs = all_expert_outputs[tokens_with_expert, expert_idx] |
|
mask = (all_valid_outputs.sum(dim=-1) != 0).to(all_valid_outputs.dtype).unsqueeze(-1) |
|
if mask.sum() > 0: |
|
expert_output = (all_valid_outputs * mask).sum(dim=0) / mask.sum() |
|
else: |
|
expert_output = torch.zeros(hidden_dim, dtype=all_expert_outputs.dtype, device=device) |
|
else: |
|
expert_output = torch.zeros(hidden_dim, dtype=all_expert_outputs.dtype, device=device) |
|
|
|
|
|
dense_outputs[token_idx] += routing_weights[token_idx, expert_idx] * expert_output |
|
|
|
return dense_outputs |
|
|
|
def estimate_dense_output(self, token_idx, activated, gate_prob, activated_outputs, all_routing, all_expert_outputs): |
|
""" |
|
对于当前 token,根据 mini-batch 中的信息估计 dense 输出。 |
|
参数: |
|
token_idx: 当前 token 的索引(标量) |
|
activated: 当前 token 激活的专家列表,例如 [1, 3] |
|
gate_prob: 当前 token 的 routing 权重,形状 (num_experts,) |
|
activated_outputs: dict,当前 token 对激活专家的实际输出,形状 (hidden_dim,) |
|
all_routing: list,每个 token 的激活专家列表(长度为 N,每个元素为 list) |
|
all_expert_outputs: Tensor, (N, num_experts, hidden_dim) |
|
返回: |
|
estimated_dense: Tensor, (hidden_dim,) |
|
""" |
|
num_experts = gate_prob.size(0) |
|
dense_parts = {} |
|
|
|
for idx in activated: |
|
dense_parts[idx] = activated_outputs[idx] |
|
|
|
non_activated = [i for i in range(num_experts) if i not in activated] |
|
for i in non_activated: |
|
indices = [] |
|
for idx, r_dec in enumerate(all_routing): |
|
if (i in r_dec) and (len(set(r_dec) & set(activated)) > 0): |
|
indices.append(idx) |
|
if indices: |
|
selected_outputs = all_expert_outputs[indices, i, :] |
|
|
|
mask = (selected_outputs.sum(dim=-1) != 0).to(selected_outputs.dtype).unsqueeze(-1) |
|
if mask.sum() > 0: |
|
estimated = (selected_outputs * mask).sum(dim=0) / mask.sum() |
|
else: |
|
|
|
estimated = torch.zeros_like(selected_outputs[0]) |
|
else: |
|
all_outputs = all_expert_outputs[:, i, :] |
|
mask = (all_outputs.sum(dim=-1) != 0).to(all_outputs.dtype).unsqueeze(-1) |
|
if mask.sum() > 0: |
|
estimated = (all_outputs * mask).sum(dim=0) / mask.sum() |
|
else: |
|
|
|
estimated = torch.zeros_like(all_outputs[0]) |
|
dense_parts[i] = estimated |
|
|
|
estimated_dense = 0 |
|
for i in range(num_experts): |
|
estimated_dense += gate_prob[i] * dense_parts[i] |
|
return estimated_dense |
|
|
|
|
|
class DenseBackwardOLMoEForCausalLM(OlmoeForCausalLM): |
|
""" |
|
自定义的 Olmoe ForCausalLM 模型,使用新的 DenseBackwardOlmoeSparseMoeBlock 替换原版的 MoE 模块, |
|
以实现 dense backward 功能。 |
|
|
|
配置类:DenseBackwardOLMoEConfig |
|
""" |
|
config_class = DenseBackwardOLMoEConfig |
|
base_model_prefix = "olmoe" |
|
|
|
def __init__(self, config): |
|
|
|
super().__init__(config) |
|
|
|
|
|
pretrained_model = OlmoeForCausalLM.from_pretrained("allenai/OLMoE-1B-7B-0125") |
|
|
|
|
|
self.config = pretrained_model.config |
|
self.model = pretrained_model.model |
|
self.vocab_size = pretrained_model.vocab_size |
|
self.router_aux_loss_coef = pretrained_model.router_aux_loss_coef |
|
self.num_experts = pretrained_model.num_experts |
|
self.lm_head = pretrained_model.lm_head |
|
|
|
|
|
|
|
|
|
for layer in self.model.layers: |
|
if hasattr(layer.mlp, "gate"): |
|
print("111") |
|
orig_block = layer.mlp |
|
|
|
new_block = DenseBackwardOlmoeSparseMoeBlock(config) |
|
|
|
new_block.gate = orig_block.gate |
|
new_block.experts = orig_block.experts |
|
new_block.num_experts = orig_block.num_experts |
|
new_block.top_k = orig_block.top_k |
|
new_block.norm_topk_prob = orig_block.norm_topk_prob |
|
layer.mlp = new_block |
|
print(type(layer.mlp)) |
|
|
|
def main(): |
|
config = DenseBackwardOLMoEConfig( |
|
model_marker="DenseBackward_olmoe_marker", |
|
) |
|
|
|
model = DenseBackwardOLMoEForCausalLM(config) |
|
print(type(model)) |
|
print(type(model.model)) |
|
print(type(model.model.layers[0])) |
|
print(type(model.model.layers[0].mlp)) |
|
print(type(model.model.layers[0].mlp.experts)) |
|
|
|
if __name__ == "__main__": |
|
main() |