|
|
|
|
|
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_v1 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 |
|
|
|
dtype = hidden_states.dtype |
|
device = hidden_states.device |
|
|
|
flat_hidden = hidden_states.view(-1, hidden_dim) |
|
N_tokens = flat_hidden.size(0) |
|
|
|
|
|
router_logits = self.gate(flat_hidden) |
|
|
|
router_logits = router_logits.to(dtype=dtype) |
|
routing_weights = F.softmax(router_logits, dim=1, dtype=dtype) |
|
|
|
|
|
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(dtype=dtype) |
|
|
|
|
|
all_expert_outputs = torch.zeros((N_tokens, self.num_experts, hidden_dim), |
|
dtype=dtype, device=device) |
|
|
|
for expert_idx in range(self.num_experts): |
|
expert_layer = self.experts[expert_idx] |
|
|
|
expert_output = expert_layer(flat_hidden) |
|
|
|
expert_output = expert_output.to(dtype=dtype) |
|
all_expert_outputs[:, expert_idx, :] = expert_output |
|
|
|
|
|
|
|
token_indices = torch.arange(N_tokens, device=device).unsqueeze(1).expand(-1, self.top_k) |
|
batch_indices = token_indices.reshape(-1) |
|
expert_indices = selected_experts.reshape(-1) |
|
|
|
|
|
selected_outputs = all_expert_outputs[batch_indices, expert_indices].view(N_tokens, self.top_k, hidden_dim) |
|
|
|
|
|
expanded_weights = routing_weights_topk.unsqueeze(-1) |
|
expanded_weights = expanded_weights.to(dtype=dtype) |
|
|
|
|
|
sparse_output = (selected_outputs * expanded_weights).sum(dim=1) |
|
|
|
|
|
|
|
routing_weights_expanded = routing_weights.unsqueeze(-1) |
|
routing_weights_expanded = routing_weights_expanded.to(dtype=dtype) |
|
print(expanded_weights.shape) |
|
print("sparse",expanded_weights) |
|
print(routing_weights_expanded.shape) |
|
print("dense",routing_weights_expanded) |
|
dense_outputs = (all_expert_outputs * routing_weights_expanded).sum(dim=1) |
|
|
|
|
|
|
|
|
|
final_flat = sparse_output.detach() + (dense_outputs - dense_outputs.detach()) |
|
final_flat = final_flat.to(dtype=dtype) |
|
final_output = final_flat.view(batch_size, seq_length, hidden_dim) |
|
|
|
return final_output, router_logits |
|
|
|
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)) |
|
|
|
del pretrained_model |
|
import gc |
|
gc.collect() |
|
torch.cuda.empty_cache() |
|
print("原始预训练模型已释放") |
|
|
|
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() |