""" A standalone, selectable GRU baseline, written to match the same interface as the Transformer / Mamba models in this repo so it can be picked with `--model gru`. Design notes (parity with model/mamba.py so the rest of the pipeline works unchanged): * `self.layers` is a ModuleList of per-layer residual GRU blocks. The shared helper `get_block_list(model) = model.transformer.h if hasattr(model, 'transformer') else model.layers` therefore returns an indexable list whose last element produces a (B, L, D) hidden state (so attention/activation hooks in the analysis scripts behave like they do for Mamba). * embedding weight is tied to lm_head (weight sharing), padding_idx=0. * `forward(idx, targets=None)` returns `(logits, loss)`; the loss uses `ignore_index=pad_id` and, at inference time (targets is None), only the last position is projected through lm_head. * `configure_optimizers`, `estimate_mfu`, `get_num_params` mirror Mamba. """ import math import inspect from dataclasses import dataclass from typing import Optional import torch import torch.nn as nn import torch.nn.functional as F @dataclass class GRUConfig: n_embd: int # D (hidden size of each GRU layer) n_layer: int vocab_size: int = 64 dropout: float = 0.0 bias: bool = True # bias inside the GRU cells rms_norm_eps: float = 1e-5 pad_id: int = -1 model_type: str = "gru" # taken straight from model/mamba.py (mamba-minimal) so normalization matches class RMSNorm(nn.Module): def __init__(self, n_embd: int, eps: float = 1e-5): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(n_embd)) def forward(self, x): return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight class GRUBlock(nn.Module): """Pre-norm residual GRU layer: out = x + dropout(GRU(RMSNorm(x))).""" def __init__(self, config: GRUConfig): super().__init__() self.norm = RMSNorm(config.n_embd, config.rms_norm_eps) self.gru = nn.GRU( input_size=config.n_embd, hidden_size=config.n_embd, num_layers=1, batch_first=True, bias=config.bias, ) self.dropout = nn.Dropout(config.dropout) def forward(self, x): # x : (B, L, D) -> (B, L, D) y, _ = self.gru(self.norm(x)) return x + self.dropout(y) class GRU(nn.Module): def __init__(self, config: GRUConfig): super().__init__() self.config = config self.embedding = nn.Embedding(config.vocab_size, config.n_embd, padding_idx=0) self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) self.lm_head.weight = self.embedding.weight # weight tying self.drop = nn.Dropout(config.dropout) self.layers = nn.ModuleList([GRUBlock(config) for _ in range(config.n_layer)]) self.out_norm = RMSNorm(config.n_embd, config.rms_norm_eps) self.apply(self._init_weights) print(f"number of parameters: {self.get_num_params() / 1e6:.2f}M") def forward(self, idx, targets=None): # idx : (B, L) x = self.drop(self.embedding(idx)) # (B, L, D) for layer in self.layers: x = layer(x) x = self.out_norm(x) if targets is not None: logits = self.lm_head(x) loss = F.cross_entropy( logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=self.config.pad_id, ) else: # inference-time mini-optimization: only project the last position logits = self.lm_head(x[:, [-1], :]) loss = None return logits, loss @torch.no_grad() def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None, return_confidence=False): """Autoregressively complete idx (B, T) by re-forwarding the full sequence each step. The GRU is recurrent and has no fixed context window, so no cropping is needed. Matches the return contract of model.transformer.GPT.generate: return_confidence=False -> idx return_confidence=True -> (idx, confidences, top3_tokens, top3_probs) For B == 1 the confidence outputs are flat lists indexed by time step; for B > 1 they are per-sample lists of shape (B, T[, 3]). """ confidences = [] if return_confidence else None top3_tokens = [] if return_confidence else None top3_probs = [] if return_confidence else None B = idx.size(0) for _ in range(max_new_tokens): logits, _ = self(idx) # targets=None -> logits is (B, 1, V) for last position if temperature <= 0: # Greedy decoding (argmax); probs are the raw softmax for confidence reporting. probs = F.softmax(logits[:, -1, :], dim=-1) idx_next = probs.argmax(dim=-1, keepdim=True) # (B, 1) else: logits = logits[:, -1, :] / temperature if top_k is not None: v, _ = torch.topk(logits, min(top_k, logits.size(-1))) logits[logits < v[:, [-1]]] = -float('Inf') probs = F.softmax(logits, dim=-1) idx_next = torch.multinomial(probs, num_samples=1) # (B, 1) if return_confidence: sampled_probs = probs.gather(1, idx_next).squeeze(-1) # (B,) confidences.append(sampled_probs.cpu().tolist()) top3_prob_vals, top3_token_ids = torch.topk(probs, 3, dim=-1) # (B, 3) top3_tokens.append(top3_token_ids.cpu().tolist()) top3_probs.append(top3_prob_vals.cpu().tolist()) idx = torch.cat((idx, idx_next), dim=1) if return_confidence: if B == 1: return (idx, [c[0] for c in confidences], [t[0] for t in top3_tokens], [p[0] for p in top3_probs]) T = len(confidences) conf_bs = [[confidences[t][b] for t in range(T)] for b in range(B)] tok_bs = [[top3_tokens[t][b] for t in range(T)] for b in range(B)] prob_bs = [[top3_probs[t][b] for t in range(T)] for b in range(B)] return idx, conf_bs, tok_bs, prob_bs return idx def _init_weights(self, module): if isinstance(module, nn.Linear): torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) if module.bias is not None: torch.nn.init.zeros_(module.bias) elif isinstance(module, nn.Embedding): torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) def configure_optimizers(self, weight_decay, learning_rate, betas, device_type): # all params that require grad; 2D+ tensors get weight decay, others don't. param_dict = {pn: p for pn, p in self.named_parameters() if p.requires_grad} decay_params = [p for p in param_dict.values() if p.dim() >= 2] nodecay_params = [p for p in param_dict.values() if p.dim() < 2] optim_groups = [ {"params": decay_params, "weight_decay": weight_decay}, {"params": nodecay_params, "weight_decay": 0.0}, ] num_decay_params = sum(p.numel() for p in decay_params) num_nodecay_params = sum(p.numel() for p in nodecay_params) print(f"num decayed parameter tensors: {len(decay_params)}, with {num_decay_params:,} parameters") print(f"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay_params:,} parameters") fused_available = "fused" in inspect.signature(torch.optim.AdamW).parameters use_fused = fused_available and device_type == "cuda" extra_args = dict(fused=True) if use_fused else {} optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, **extra_args) print(f"using fused AdamW: {use_fused}") return optimizer def estimate_mfu(self, fwdbwd_per_iter, dt): return -1 def get_num_params(self, non_embedding=True): n_params = sum(p.numel() for p in self.parameters()) if non_embedding: n_params -= self.embedding.weight.numel() return n_params