"""Feed-forward variants: a dense 2-layer MLP and a Mixture-of-Experts layer.""" from __future__ import annotations import torch import torch.nn as nn import torch.nn.functional as F from .config import TransformerConfig, moe_spec class MLP(nn.Module): """Standard 2-layer MLP: D -> hidden -> D with GELU.""" def __init__(self, config: TransformerConfig, hidden: int | None = None): super().__init__() hidden = hidden or config.d_ff self.up = nn.Linear(config.D_model, hidden, bias=False) self.down = nn.Linear(hidden, config.D_model, bias=False) self.drop = nn.Dropout(config.dropout) def forward(self, x, pad_mask=None): # Input shape: (B, N_ctx, D_model) # Output shape: (B, N_ctx, D_model) return self.drop(self.down(F.gelu(self.up(x)))) def active_params(self) -> int: return sum(p.numel() for p in self.parameters()) class MoE(nn.Module): """Top-k routed Mixture-of-Experts with an optional always-on shared expert. Routing: softmax over the routed experts, keep the top-k. For k > 1 the kept probabilities are renormalised to sum to 1; for k == 1 the raw softmax probability is used as the gate (renormalising would make the gate a constant 1 and starve the router of gradient). Dispatch is dropless: every token is processed by each of its selected experts. Side effects of a forward pass (read by training / analysis code): self.aux_loss scalar load-balancing loss (+ optional z-loss), weighted self.last_load (n_routed,) fraction of routing slots sent to each expert self.last_topk (B, N_ctx, k) chosen expert ids, only if record_routing """ def __init__(self, config: TransformerConfig): super().__init__() spec = moe_spec(config.ffn_variant, config.d_ff) self.n_routed, self.top_k = spec.n_routed, spec.top_k self.aux_coef, self.z_coef = config.aux_loss_coef, config.z_loss_coef self.router = nn.Linear(config.D_model, spec.n_routed, bias=False) self.experts = nn.ModuleList( MLP(config, spec.expert_hidden) for _ in range(spec.n_routed) ) self.shared = ( nn.ModuleList(MLP(config, spec.expert_hidden) for _ in range(spec.n_shared)) if spec.n_shared else None ) self.record_routing = False self.aux_loss = torch.zeros(()) self.last_load = None self.last_topk = None def forward(self, x, pad_mask=None): # Input shape: (B, N_ctx, D_model) # Output shape: (B, N_ctx, D_model) # pad_mask: optional (B, N_ctx) bool, True for real tokens. Padding is # still computed on (cheap) but excluded from the aux loss and stats. B, T, D = x.shape flat = x.reshape(-1, D) n_tok = flat.shape[0] logits = self.router(flat).float() # (N, E) router always in fp32 probs = logits.softmax(dim=-1) top_p, top_i = probs.topk(self.top_k, dim=-1) # (N, k) if self.top_k > 1: top_p = top_p / top_p.sum(dim=-1, keepdim=True) out = torch.zeros_like(flat) for e, expert in enumerate(self.experts): tok, slot = (top_i == e).nonzero(as_tuple=True) if tok.numel() == 0: continue y = expert(flat[tok]) gate = top_p[tok, slot].unsqueeze(-1) out.index_add_(0, tok, (y * gate).to(out.dtype)) if self.shared is not None: for s in self.shared: out = out + s(flat) # --- load balancing + stats (real tokens only) --- valid = ( pad_mask.reshape(-1) if pad_mask is not None else torch.ones(n_tok, dtype=torch.bool, device=x.device) ) n_valid = valid.sum().clamp(min=1) assign = F.one_hot(top_i, self.n_routed).sum(dim=1).float() # (N, E) 0/1 f = (assign * valid[:, None]).sum(0) / (n_valid * self.top_k) # sums to 1 P = (probs * valid[:, None]).sum(0) / n_valid # mean router prob aux = self.n_routed * (f * P).sum() # Switch eq. 4-6, == 1 when uniform if self.z_coef: z = (torch.logsumexp(logits, dim=-1) ** 2 * valid).sum() / n_valid aux_total = self.aux_coef * aux + self.z_coef * z else: aux_total = self.aux_coef * aux self.aux_loss = aux_total self.last_load = f.detach() if self.record_routing: self.last_topk = top_i.detach().reshape(B, T, self.top_k) return out.reshape(B, T, D) def active_params(self) -> int: per_expert = sum(p.numel() for p in self.experts[0].parameters()) shared = sum(p.numel() for p in self.shared.parameters()) if self.shared else 0 return sum(p.numel() for p in self.router.parameters()) + self.top_k * per_expert + shared def build_ffn(config: TransformerConfig) -> nn.Module: return MoE(config) if config.use_moe else MLP(config)