File size: 8,379 Bytes
34e468d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | """
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
|