Download moe.py from vanshnawander/assignment2-optimizer-lion: direct link, hf CLI and curl.
- Browser
- Download file 5.99 kB
-
https://huggingface.co/vanshnawander/assignment2-optimizer-lion/resolve/main/moe.py
- Command line
-
hf download hf://vanshnawander/assignment2-optimizer-lion/moe.py
-
curl -L -o moe.py https://huggingface.co/vanshnawander/assignment2-optimizer-lion/resolve/main/moe.py
5.99 kB
| """Five FFN ablations with exact router-inclusive parameter budgets.""" | |
| from dataclasses import dataclass | |
| import torch | |
| from torch import Tensor, nn | |
| import torch.nn.functional as F | |
| class TransformerConfig: | |
| """Describe decoder dimensions and the selected feedforward routing variant.""" | |
| d_model: int | |
| d_ff: int | |
| vocab_size: int | |
| context_length: int | |
| num_experts: int = 1 | |
| top_k: int = 1 | |
| shared_expert: bool = False | |
| match_active_parameters: bool = False | |
| n_layers: int = 6 | |
| n_heads: int = 8 | |
| dropout: float = 0.1 | |
| class MLP(nn.Module): | |
| """Implement a bias-free two-layer GELU feedforward network.""" | |
| def __init__(self, config: TransformerConfig, width: int | None = None): | |
| """Create the two projections using the given or configured hidden width.""" | |
| super().__init__() | |
| self.width = config.d_ff if width is None else width | |
| self.up = nn.Linear(config.d_model, self.width, bias=False) | |
| self.down = nn.Linear(self.width, config.d_model, bias=False) | |
| def forward(self, x: Tensor) -> Tensor: | |
| """Apply the feedforward network while preserving the input shape.""" | |
| return self.down(F.gelu(self.up(x))) | |
| class MoE(nn.Module): | |
| """Route tokens to four experts while matching the requested parameter budget.""" | |
| def __init__(self, config: TransformerConfig): | |
| """Create router, expert widths and counters for the selected variant.""" | |
| super().__init__() | |
| if config.num_experts != 4 or config.top_k not in (1, 2): | |
| raise ValueError( | |
| "This assignment uses four experts and top-k of one or two" | |
| ) | |
| if config.shared_expert and config.top_k != 1: | |
| raise ValueError("Shared variant selects one of three routed experts") | |
| budget = config.d_ff - 2 # 4*d router weights cost two FFN hidden units. | |
| if budget < 4: | |
| raise ValueError("d_ff must be at least six") | |
| if config.match_active_parameters: | |
| if config.top_k != 2 or config.shared_expert or budget % 2: | |
| raise ValueError( | |
| "Active matching requires even d_ff and two routed experts" | |
| ) | |
| widths = [budget // 2] * 4 | |
| else: | |
| widths = [budget // 4 + (i < budget % 4) for i in range(4)] | |
| self.experts = nn.ModuleList([MLP(config, width) for width in widths]) | |
| self.router = nn.Linear(config.d_model, 4, bias=False) | |
| self.config = config | |
| self.register_buffer( | |
| "usage", torch.zeros(4, dtype=torch.long), persistent=False | |
| ) | |
| self.aux_loss = torch.tensor(0.0) | |
| self.tracking_mask: Tensor | None = None | |
| self.track_usage = False | |
| def forward(self, x: Tensor) -> Tensor: | |
| """Dispatch token states to selected experts and combine their gated outputs. | |
| Preserve the input shape and update the balancing loss. When enabled, | |
| usage tracking counts only positions allowed by the tracking mask. | |
| """ | |
| flat = x.reshape(-1, x.shape[-1]) | |
| logits = self.router(flat).float() | |
| offset = 1 if self.config.shared_expert else 0 | |
| probs = logits[:, offset:].softmax(-1) | |
| weights, selected = probs.topk(self.config.top_k, dim=-1) | |
| # Keep the top-1 probability, preserving a task-loss gradient to its gate. | |
| if self.config.top_k > 1: | |
| weights = weights / weights.sum(-1, keepdim=True) | |
| output = torch.zeros_like(flat) | |
| valid = torch.ones(flat.shape[0], dtype=torch.bool, device=x.device) | |
| if self.tracking_mask is not None: | |
| valid = self.tracking_mask.reshape(-1).bool() | |
| assignments = F.one_hot(selected, probs.shape[-1]).float().sum(1) | |
| if valid.any(): | |
| self.aux_loss = ( | |
| probs.shape[-1] | |
| * ( | |
| probs[valid].mean(0) | |
| * assignments[valid].mean(0) | |
| / self.config.top_k | |
| ).sum() | |
| ) | |
| else: | |
| self.aux_loss = probs.sum() * 0 | |
| if offset: | |
| output = self.experts[0](flat) * logits[:, :1].sigmoid().to(flat.dtype) | |
| if self.track_usage: | |
| self.usage[0].add_(valid.sum()) | |
| for expert_id in range(offset, 4): | |
| token, slot = (selected == expert_id - offset).nonzero(as_tuple=True) | |
| if token.numel(): | |
| values = self.experts[expert_id](flat[token]) | |
| output.index_add_( | |
| 0, | |
| token, | |
| (values * weights[token, slot, None].to(values.dtype)).to( | |
| output.dtype | |
| ), | |
| ) | |
| if self.track_usage: | |
| self.usage[expert_id].add_(valid[token].sum()) | |
| return output.reshape_as(x) | |
| def reset_usage(self): | |
| """Clear the expert assignment counters before a tracking pass.""" | |
| self.usage.zero_() | |
| def active_parameter_count(self) -> int: | |
| """Count router weights and the largest expert subset active for one token.""" | |
| router = self.router.weight.numel() | |
| counts = [sum(p.numel() for p in e.parameters()) for e in self.experts] | |
| if self.config.shared_expert: | |
| return router + counts[0] + max(counts[1:]) | |
| return router + sum(sorted(counts, reverse=True)[: self.config.top_k]) | |
| class Transformer(nn.Module): | |
| """Compatibility wrapper using the complete causal transformer.""" | |
| def __init__(self, config: TransformerConfig): | |
| """Wrap the causal decoder using the supplied configuration.""" | |
| super().__init__() | |
| from model import CausalLM | |
| self.model = CausalLM(config) | |
| def forward(self, input_ids: Tensor, attention_mask: Tensor | None = None): | |
| """Pass token IDs and an optional attention mask to the wrapped decoder.""" | |
| return self.model(input_ids, attention_mask) | |