walke007's picture
Upload Part 2 checkpoints and recorded results
a3baf17 verified
Raw History Blame Contribute Delete
2.94 kB
import math
import torch
from torch import nn
class MOE(nn.Module):
def __init__(self, config, experts, active, shared, hidden_dim=None):
super().__init__()
if not 0 <= shared < experts:
raise ValueError("shared must be between 0 and experts - 1")
if not 1 <= active <= experts - shared:
raise ValueError("active counts routed experts and must fit the routed expert count")
self.d = config.dimension_model
self.numexperts = experts
self.numactive = active
self.numshared = shared
self.hidden_dim = self.d if hidden_dim is None else hidden_dim
if self.hidden_dim <= 0:
raise ValueError("hidden_dim must be positive")
# For four width-d experts: expert weights = 8*d^2; routed gate
# weights + shared hidden biases = 4*d; output bias = d.
# Total = 8*d^2 + 5*d, exactly the original dense FFN's count.
self.router = nn.Linear(self.d, self.numexperts - self.numshared, bias=False)
# A single output bias replaces the individual expert output biases.
self.output_bias = nn.Parameter(torch.zeros(self.d))
self.experts = nn.ModuleList([
nn.Sequential(
nn.Linear(self.d, self.hidden_dim, bias=False),
nn.ReLU(),
nn.Linear(self.hidden_dim, self.d, bias=False),
)
for _ in range(self.numexperts - self.numshared)
])
self.shared = nn.ModuleList([
nn.Sequential(
nn.Linear(self.d, self.hidden_dim),
nn.ReLU(),
nn.Linear(self.hidden_dim, self.d, bias=False),
)
for _ in range(self.numshared)
])
def forward(self, x):
original_shape = x.shape
tokens = x.reshape(-1, x.size(-1))
probabilities = torch.softmax(self.router(tokens), dim=-1)
selected_weights, selected_experts = probabilities.topk(
self.numactive, dim=-1
)
# Used by evaluation to count expert activations for actual source tokens.
self.last_selected_experts = selected_experts.detach().reshape(
*original_shape[:2], self.numactive
)
output = torch.zeros_like(tokens)
for expert in self.shared:
output = output + expert(tokens)
for expert_id, expert in enumerate(self.experts):
token_ids, slots = torch.where(selected_experts == expert_id)
if token_ids.numel() == 0:
continue
# Run this expert once on all tokens assigned to it.
expert_output = expert(tokens[token_ids])
weights = selected_weights[token_ids, slots].unsqueeze(-1)
output = output.index_add(
0, token_ids, expert_output * weights
)
return (output + self.output_bias).reshape(original_shape)