Upload MoE Transformer model
Browse files- config.json +23 -0
- moe_transformer.py +252 -0
- pytorch_model.bin +3 -0
config.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"d_model": 256,
|
| 3 |
+
"num_heads": 8,
|
| 4 |
+
"num_encoder_layers": 6,
|
| 5 |
+
"num_decoder_layers": 6,
|
| 6 |
+
"d_ff": 1024,
|
| 7 |
+
"num_experts": 8,
|
| 8 |
+
"top_k": 2,
|
| 9 |
+
"dropout": 0.1,
|
| 10 |
+
"max_input_length": 512,
|
| 11 |
+
"max_target_length": 64,
|
| 12 |
+
"batch_size": 64,
|
| 13 |
+
"learning_rate": 0.0001,
|
| 14 |
+
"early_stopping_patience": 3,
|
| 15 |
+
"architectures": [
|
| 16 |
+
"MoETransformer"
|
| 17 |
+
],
|
| 18 |
+
"model_type": "moe_transformer",
|
| 19 |
+
"vocab_size": 32100,
|
| 20 |
+
"auto_map": {
|
| 21 |
+
"AutoModel": "moe_transformer.MoETransformer"
|
| 22 |
+
}
|
| 23 |
+
}
|
moe_transformer.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# moe_transformer.py
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import math
|
| 6 |
+
|
| 7 |
+
class SparseMoE(nn.Module):
|
| 8 |
+
"""Sparse Mixture-of-Experts layer."""
|
| 9 |
+
def __init__(self, d_model, num_experts, top_k, routing_algorithm, d_ff):
|
| 10 |
+
super().__init__()
|
| 11 |
+
self.d_model = d_model
|
| 12 |
+
self.num_experts = num_experts
|
| 13 |
+
self.top_k = top_k
|
| 14 |
+
self.routing_algorithm = routing_algorithm
|
| 15 |
+
|
| 16 |
+
self.experts = nn.ModuleList([
|
| 17 |
+
nn.Sequential(
|
| 18 |
+
nn.Linear(d_model, d_ff),
|
| 19 |
+
nn.ReLU(),
|
| 20 |
+
nn.Linear(d_ff, d_model)
|
| 21 |
+
) for _ in range(num_experts)
|
| 22 |
+
])
|
| 23 |
+
|
| 24 |
+
if self.routing_algorithm == 'top_k':
|
| 25 |
+
self.gate = nn.Linear(d_model, num_experts)
|
| 26 |
+
|
| 27 |
+
self.load_balancing_loss = 0.0
|
| 28 |
+
|
| 29 |
+
def hash_routing(self, x):
|
| 30 |
+
token_hashes = x.sum(dim=-1).long().abs()
|
| 31 |
+
expert_indices = token_hashes % self.num_experts
|
| 32 |
+
return F.one_hot(expert_indices, num_classes=self.num_experts).float()
|
| 33 |
+
|
| 34 |
+
def top_k_routing(self, x):
|
| 35 |
+
gate_logits = self.gate(x)
|
| 36 |
+
top_k_logits, top_k_indices = torch.topk(gate_logits, self.top_k, dim=-1)
|
| 37 |
+
gate_scores = F.softmax(top_k_logits, dim=-1)
|
| 38 |
+
|
| 39 |
+
router_mask = torch.zeros_like(gate_logits).scatter_(-1, top_k_indices, gate_scores)
|
| 40 |
+
|
| 41 |
+
if self.training:
|
| 42 |
+
probs_per_expert = gate_logits.softmax(dim=-1)
|
| 43 |
+
tokens_per_batch_seq = router_mask.shape[0]
|
| 44 |
+
fraction_tokens_per_expert = router_mask.sum(dim=0) / tokens_per_batch_seq
|
| 45 |
+
mean_prob_per_expert = probs_per_expert.mean(dim=0)
|
| 46 |
+
self.load_balancing_loss = self.num_experts * torch.sum(fraction_tokens_per_expert * mean_prob_per_expert)
|
| 47 |
+
|
| 48 |
+
return router_mask
|
| 49 |
+
|
| 50 |
+
def forward(self, x):
|
| 51 |
+
batch_size, seq_len, _ = x.shape
|
| 52 |
+
x_flat = x.view(-1, self.d_model)
|
| 53 |
+
|
| 54 |
+
if self.routing_algorithm == 'top_k':
|
| 55 |
+
router_output = self.top_k_routing(x_flat)
|
| 56 |
+
elif self.routing_algorithm == 'hash':
|
| 57 |
+
router_output = self.hash_routing(x_flat)
|
| 58 |
+
else:
|
| 59 |
+
raise ValueError(f"Unknown routing algorithm: {self.routing_algorithm}")
|
| 60 |
+
|
| 61 |
+
final_output = torch.zeros_like(x_flat)
|
| 62 |
+
for i, expert in enumerate(self.experts):
|
| 63 |
+
expert_mask = router_output[:, i].unsqueeze(1)
|
| 64 |
+
active_tokens_indices = torch.where(expert_mask.squeeze() > 0)[0]
|
| 65 |
+
if active_tokens_indices.numel() > 0:
|
| 66 |
+
active_tokens = x_flat[active_tokens_indices]
|
| 67 |
+
expert_out = expert(active_tokens)
|
| 68 |
+
weighted_out = expert_out * expert_mask[active_tokens_indices]
|
| 69 |
+
final_output.index_add_(0, active_tokens_indices, weighted_out)
|
| 70 |
+
|
| 71 |
+
return final_output.view(batch_size, seq_len, self.d_model)
|
| 72 |
+
|
| 73 |
+
class GroupedQueryAttention(nn.Module):
|
| 74 |
+
"""
|
| 75 |
+
Implements Grouped-Query Attention (GQA).
|
| 76 |
+
- MHA is a special case of GQA where num_kv_heads == num_heads.
|
| 77 |
+
- MQA is a special case of GQA where num_kv_heads == 1.
|
| 78 |
+
"""
|
| 79 |
+
def __init__(self, d_model, num_heads, num_kv_heads):
|
| 80 |
+
super().__init__()
|
| 81 |
+
assert d_model % num_heads == 0, "d_model must be divisible by num_heads"
|
| 82 |
+
assert num_heads % num_kv_heads == 0, "num_heads must be divisible by num_kv_heads"
|
| 83 |
+
|
| 84 |
+
self.d_model = d_model
|
| 85 |
+
self.num_heads = num_heads
|
| 86 |
+
self.num_kv_heads = num_kv_heads
|
| 87 |
+
self.num_key_value_groups = num_heads // num_kv_heads
|
| 88 |
+
self.d_k = d_model // num_heads
|
| 89 |
+
|
| 90 |
+
self.W_q = nn.Linear(d_model, d_model)
|
| 91 |
+
self.W_k = nn.Linear(d_model, self.num_kv_heads * self.d_k)
|
| 92 |
+
self.W_v = nn.Linear(d_model, self.num_kv_heads * self.d_k)
|
| 93 |
+
self.W_o = nn.Linear(d_model, d_model)
|
| 94 |
+
|
| 95 |
+
def scaled_dot_product_attention(self, Q, K, V, mask=None):
|
| 96 |
+
attn_scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)
|
| 97 |
+
if mask is not None:
|
| 98 |
+
attn_scores = attn_scores.masked_fill(mask == 0, -1e9)
|
| 99 |
+
attn_probs = F.softmax(attn_scores, dim=-1)
|
| 100 |
+
output = torch.matmul(attn_probs, V)
|
| 101 |
+
return output
|
| 102 |
+
|
| 103 |
+
def forward(self, q, k, v, mask=None):
|
| 104 |
+
batch_size = q.size(0)
|
| 105 |
+
|
| 106 |
+
Q = self.W_q(q).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
|
| 107 |
+
K = self.W_k(k).view(batch_size, -1, self.num_kv_heads, self.d_k).transpose(1, 2)
|
| 108 |
+
V = self.W_v(v).view(batch_size, -1, self.num_kv_heads, self.d_k).transpose(1, 2)
|
| 109 |
+
|
| 110 |
+
if self.num_key_value_groups > 1:
|
| 111 |
+
K = K.repeat_interleave(self.num_key_value_groups, dim=1)
|
| 112 |
+
V = V.repeat_interleave(self.num_key_value_groups, dim=1)
|
| 113 |
+
|
| 114 |
+
context = self.scaled_dot_product_attention(Q, K, V, mask)
|
| 115 |
+
context = context.transpose(1, 2).contiguous().view(batch_size, -1, self.d_model)
|
| 116 |
+
|
| 117 |
+
output = self.W_o(context)
|
| 118 |
+
return output
|
| 119 |
+
|
| 120 |
+
class PositionalEncoding(nn.Module):
|
| 121 |
+
def __init__(self, d_model, dropout=0.1, max_len=5000):
|
| 122 |
+
super().__init__()
|
| 123 |
+
self.dropout = nn.Dropout(p=dropout)
|
| 124 |
+
pe = torch.zeros(max_len, d_model)
|
| 125 |
+
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
|
| 126 |
+
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
|
| 127 |
+
pe[:, 0::2] = torch.sin(position * div_term)
|
| 128 |
+
pe[:, 1::2] = torch.cos(position * div_term)
|
| 129 |
+
self.register_buffer('pe', pe.unsqueeze(0))
|
| 130 |
+
|
| 131 |
+
def forward(self, x):
|
| 132 |
+
x = x + self.pe[:, :x.size(1)]
|
| 133 |
+
return self.dropout(x)
|
| 134 |
+
|
| 135 |
+
class EncoderLayer(nn.Module):
|
| 136 |
+
def __init__(self, d_model, num_heads, num_kv_heads, d_ff, num_experts, top_k, routing_algorithm, dropout):
|
| 137 |
+
super().__init__()
|
| 138 |
+
self.self_attn = GroupedQueryAttention(d_model, num_heads, num_kv_heads)
|
| 139 |
+
self.moe_ffn = SparseMoE(d_model, num_experts, top_k, routing_algorithm, d_ff)
|
| 140 |
+
self.norm1 = nn.LayerNorm(d_model)
|
| 141 |
+
self.norm2 = nn.LayerNorm(d_model)
|
| 142 |
+
self.dropout = nn.Dropout(dropout)
|
| 143 |
+
|
| 144 |
+
def forward(self, x, mask):
|
| 145 |
+
attn_output = self.self_attn(x, x, x, mask)
|
| 146 |
+
x = self.norm1(x + self.dropout(attn_output))
|
| 147 |
+
|
| 148 |
+
moe_output = self.moe_ffn(x)
|
| 149 |
+
x = self.norm2(x + self.dropout(moe_output))
|
| 150 |
+
return x
|
| 151 |
+
|
| 152 |
+
class DecoderLayer(nn.Module):
|
| 153 |
+
def __init__(self, d_model, num_heads, num_kv_heads, d_ff, num_experts, top_k, routing_algorithm, dropout):
|
| 154 |
+
super().__init__()
|
| 155 |
+
self.self_attn = GroupedQueryAttention(d_model, num_heads, num_kv_heads)
|
| 156 |
+
self.cross_attn = GroupedQueryAttention(d_model, num_heads, num_kv_heads)
|
| 157 |
+
self.moe_ffn = SparseMoE(d_model, num_experts, top_k, routing_algorithm, d_ff)
|
| 158 |
+
self.norm1 = nn.LayerNorm(d_model)
|
| 159 |
+
self.norm2 = nn.LayerNorm(d_model)
|
| 160 |
+
self.norm3 = nn.LayerNorm(d_model)
|
| 161 |
+
self.dropout = nn.Dropout(dropout)
|
| 162 |
+
|
| 163 |
+
def forward(self, x, enc_output, src_mask, tgt_mask):
|
| 164 |
+
attn_output = self.self_attn(x, x, x, tgt_mask)
|
| 165 |
+
x = self.norm1(x + self.dropout(attn_output))
|
| 166 |
+
|
| 167 |
+
cross_attn_output = self.cross_attn(x, enc_output, enc_output, src_mask)
|
| 168 |
+
x = self.norm2(x + self.dropout(cross_attn_output))
|
| 169 |
+
|
| 170 |
+
moe_output = self.moe_ffn(x)
|
| 171 |
+
x = self.norm3(x + self.dropout(moe_output))
|
| 172 |
+
return x
|
| 173 |
+
|
| 174 |
+
class MoETransformer(nn.Module):
|
| 175 |
+
def __init__(self, config, vocab_size):
|
| 176 |
+
super().__init__()
|
| 177 |
+
self.config = config
|
| 178 |
+
self.encoder_embedding = nn.Embedding(vocab_size, config['d_model'])
|
| 179 |
+
self.decoder_embedding = nn.Embedding(vocab_size, config['d_model'])
|
| 180 |
+
self.positional_encoding = PositionalEncoding(config['d_model'], config['dropout'])
|
| 181 |
+
|
| 182 |
+
self.encoder_layers = nn.ModuleList([
|
| 183 |
+
EncoderLayer(config['d_model'], config['num_heads'], config['num_kv_heads'], config['d_ff'], config['num_experts'], config['top_k'], config['routing_algorithm'], config['dropout'])
|
| 184 |
+
for _ in range(config['num_encoder_layers'])
|
| 185 |
+
])
|
| 186 |
+
self.decoder_layers = nn.ModuleList([
|
| 187 |
+
DecoderLayer(config['d_model'], config['num_heads'], config['num_kv_heads'], config['d_ff'], config['num_experts'], config['top_k'], config['routing_algorithm'], config['dropout'])
|
| 188 |
+
for _ in range(config['num_decoder_layers'])
|
| 189 |
+
])
|
| 190 |
+
|
| 191 |
+
self.fc_out = nn.Linear(config['d_model'], vocab_size)
|
| 192 |
+
|
| 193 |
+
def generate_mask(self, src, tgt, pad_idx):
|
| 194 |
+
src_mask = (src != pad_idx).unsqueeze(1).unsqueeze(2)
|
| 195 |
+
tgt_pad_mask = (tgt != pad_idx).unsqueeze(1).unsqueeze(2)
|
| 196 |
+
seq_len = tgt.size(1)
|
| 197 |
+
tgt_sub_mask = torch.tril(torch.ones((seq_len, seq_len), device=tgt.device)).bool()
|
| 198 |
+
tgt_mask = tgt_pad_mask & tgt_sub_mask
|
| 199 |
+
return src_mask, tgt_mask
|
| 200 |
+
|
| 201 |
+
def forward(self, src, tgt, pad_idx=0):
|
| 202 |
+
src_mask, tgt_mask = self.generate_mask(src, tgt, pad_idx)
|
| 203 |
+
|
| 204 |
+
src_emb = self.positional_encoding(self.encoder_embedding(src) * math.sqrt(self.config['d_model']))
|
| 205 |
+
tgt_emb = self.positional_encoding(self.decoder_embedding(tgt) * math.sqrt(self.config['d_model']))
|
| 206 |
+
|
| 207 |
+
enc_output = src_emb
|
| 208 |
+
for layer in self.encoder_layers:
|
| 209 |
+
enc_output = layer(enc_output, src_mask)
|
| 210 |
+
|
| 211 |
+
dec_output = tgt_emb
|
| 212 |
+
for layer in self.decoder_layers:
|
| 213 |
+
dec_output = layer(dec_output, enc_output, src_mask, tgt_mask)
|
| 214 |
+
|
| 215 |
+
return self.fc_out(dec_output)
|
| 216 |
+
|
| 217 |
+
def get_total_load_balancing_loss(self):
|
| 218 |
+
total_loss = 0
|
| 219 |
+
for layer in self.encoder_layers + self.decoder_layers:
|
| 220 |
+
total_loss += layer.moe_ffn.load_balancing_loss
|
| 221 |
+
return total_loss
|
| 222 |
+
|
| 223 |
+
@torch.no_grad()
|
| 224 |
+
def generate(self, src, max_length, start_symbol, pad_idx=0):
|
| 225 |
+
self.eval()
|
| 226 |
+
device = next(self.parameters()).device
|
| 227 |
+
src = src.to(device)
|
| 228 |
+
batch_size = src.shape[0]
|
| 229 |
+
|
| 230 |
+
src_mask = (src != pad_idx).unsqueeze(1).unsqueeze(2)
|
| 231 |
+
src_emb = self.positional_encoding(self.encoder_embedding(src) * math.sqrt(self.config['d_model']))
|
| 232 |
+
enc_output = src_emb
|
| 233 |
+
for layer in self.encoder_layers:
|
| 234 |
+
enc_output = layer(enc_output, src_mask)
|
| 235 |
+
|
| 236 |
+
tgt = torch.full((batch_size, 1), start_symbol, dtype=torch.long, device=device)
|
| 237 |
+
|
| 238 |
+
for _ in range(max_length - 1):
|
| 239 |
+
_, tgt_mask = self.generate_mask(src, tgt, pad_idx)
|
| 240 |
+
tgt_emb = self.positional_encoding(self.decoder_embedding(tgt) * math.sqrt(self.config['d_model']))
|
| 241 |
+
dec_output = tgt_emb
|
| 242 |
+
for layer in self.decoder_layers:
|
| 243 |
+
dec_output = layer(dec_output, enc_output, src_mask, tgt_mask)
|
| 244 |
+
|
| 245 |
+
logits = self.fc_out(dec_output[:, -1])
|
| 246 |
+
next_token = torch.argmax(logits, dim=-1).unsqueeze(1)
|
| 247 |
+
tgt = torch.cat([tgt, next_token], dim=1)
|
| 248 |
+
|
| 249 |
+
if (tgt == 1).any(dim=-1).all():
|
| 250 |
+
break
|
| 251 |
+
|
| 252 |
+
return tgt
|
pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dd007dfb2d5664ab7f18d3699ddf237353cb72675976c48e10d00a24b5f0aab5
|
| 3 |
+
size 325023994
|