imdatta0 commited on
Commit
1302eb0
·
verified ·
1 Parent(s): a729524

Upload convert_to_linear.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. convert_to_linear.py +96 -0
convert_to_linear.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch.nn as nn
3
+ import torch
4
+ import torch.nn.functional as F
5
+
6
+
7
+ def convert_to_linear_experts(old_module: GptOssExperts, config) -> NewGptOssExperts:
8
+ new_mod = NewGptOssExperts(config).to(old_module.gate_up_proj.device)
9
+ new_mod.alpha = old_module.alpha
10
+ new_mod.limit = old_module.limit
11
+
12
+ E, D, two_dexp = old_module.gate_up_proj.shape
13
+
14
+ for e in range(E):
15
+ # up proj
16
+ W_old = old_module.gate_up_proj[e].detach().to(config.torch_dtype)
17
+ b_old = old_module.gate_up_proj_bias[e].detach().to(config.torch_dtype)
18
+ new_mod.gate_up_projs[e].weight.data.copy_(W_old.transpose(0, 1))
19
+ new_mod.gate_up_projs[e].bias.data.copy_(b_old)
20
+
21
+ # down proj
22
+ Wd_old = old_module.down_proj[e].detach().to(config.torch_dtype)
23
+ bd_old = old_module.down_proj_bias[e].detach().to(config.torch_dtype)
24
+ new_mod.down_projs[e].weight.data.copy_(Wd_old.transpose(0, 1))
25
+ new_mod.down_projs[e].bias.data.copy_(bd_old)
26
+
27
+ return new_mod
28
+
29
+ class NewGptOssExperts(nn.Module):
30
+ def __init__(self, config):
31
+ super().__init__()
32
+
33
+ self.num_experts = config.num_local_experts
34
+ self.hidden_size = config.hidden_size
35
+ self.expert_dim = config.intermediate_size
36
+ self.alpha = 1.702
37
+ self.limit = 7.0
38
+ self.dtype = config.torch_dtype
39
+
40
+ self.gate_up_projs = nn.ModuleList([
41
+ nn.Linear(self.hidden_size, 2 * self.expert_dim, dtype=self.dtype)
42
+ for _ in range(self.num_experts)
43
+ ])
44
+ self.down_projs = nn.ModuleList([
45
+ nn.Linear(self.expert_dim, self.hidden_size, dtype=self.dtype)
46
+ for _ in range(self.num_experts)
47
+ ])
48
+
49
+ def forward(self,
50
+ hidden_states: torch.Tensor,
51
+ router_indices = None,
52
+ routing_weights = None
53
+ ) -> torch.Tensor:
54
+
55
+ batch_size = hidden_states.shape[0]
56
+ hidden_states = hidden_states.reshape(-1, self.hidden_size)
57
+ num_experts = routing_weights.shape[1]
58
+
59
+ if self.training:
60
+ next_states = torch.zeros_like(hidden_states, dtype=hidden_states.dtype, device=hidden_states.device)
61
+ with torch.no_grad():
62
+ expert_mask = torch.nn.functional.one_hot(router_indices, num_classes=num_experts)
63
+ expert_mask = expert_mask.permute(2, 1, 0)
64
+ expert_hitted = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
65
+ for expert_idx in expert_hitted[:]:
66
+ with torch.no_grad():
67
+ _, token_idx = torch.where(expert_mask[expert_idx[0]])
68
+ current_state = hidden_states[token_idx]
69
+ gate_up = self.gate_up_projs[expert_idx](current_state)
70
+ gate, up = gate_up[..., ::2], gate_up[..., 1::2]
71
+ gate = gate.clamp(min=None, max=self.limit)
72
+ up = up.clamp(min=-self.limit, max=self.limit)
73
+ glu = gate * torch.sigmoid(gate * self.alpha)
74
+ gated_output = (up + 1) * glu
75
+ out = self.down_projs[expert_idx](gated_output)
76
+ weighted_output = out * routing_weights[token_idx, expert_idx, None]
77
+ next_states.index_add_(0, token_idx, weighted_output.to(hidden_states.dtype))
78
+ next_states = next_states.view(batch_size, -1, self.hidden_size)
79
+ return next_states
80
+
81
+ else:
82
+ X_rep = hidden_states.unsqueeze(0).expand(num_experts, -1, -1)
83
+ gate_up_list = [up_l(X_rep[e]) for e, up_l in enumerate(self.gate_up_projs)]
84
+ gate_up = torch.stack(gate_up_list, dim=0)
85
+ gate = gate_up[..., ::2]
86
+ up_h = gate_up[..., 1::2]
87
+ gate = gate.clamp(max=self.limit)
88
+ up_h = up_h.clamp(min=-self.limit, max=self.limit)
89
+ glu = gate * torch.sigmoid(gate * self.alpha)
90
+ fused = (up_h + 1) * glu
91
+ out_list = [down_l(fused[e]) for e, down_l in enumerate(self.down_projs)]
92
+ outs = torch.stack(out_list, dim=0)
93
+ rw = routing_weights.transpose(0, 1).unsqueeze(-1)
94
+ mixed = (outs * rw).sum(dim=0)
95
+ return mixed.view(batch_size, -1, self.hidden_size)
96
+