File size: 7,082 Bytes
673d750 | 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 199 200 201 202 203 204 205 206 207 208 209 210 | """A small decoder-only GPT with RoPE, RMSNorm, and SwiGLU."""
from __future__ import annotations
from dataclasses import asdict, dataclass
import torch
from torch import nn
from torch.nn import functional as F
@dataclass(frozen=True)
class GPTConfig:
"""Shape and numerical settings for the 20M-parameter model."""
vocab_size: int = 8192
context_length: int = 512
d_model: int = 384
n_layers: int = 6
n_heads: int = 6
ffn_dim: int = 1920
rope_base: float = 10_000.0
norm_eps: float = 1e-5
def to_dict(self) -> dict[str, int | float]:
return asdict(self)
class RMSNorm(nn.Module):
def __init__(self, width: int, eps: float = 1e-5) -> None:
super().__init__()
self.weight = nn.Parameter(torch.ones(width))
self.eps = eps
def forward(self, x: torch.Tensor) -> torch.Tensor:
normalized = x.float() * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps)
return (normalized * self.weight.float()).to(dtype=x.dtype)
def apply_rope(
query: torch.Tensor,
key: torch.Tensor,
positions: torch.Tensor,
base: float,
) -> tuple[torch.Tensor, torch.Tensor]:
head_dim = query.size(-1)
frequency = 1.0 / (
base ** (torch.arange(0, head_dim, 2, device=query.device, dtype=torch.float32) / head_dim)
)
phase = positions.to(torch.float32)[:, None] * frequency[None, :]
cos = torch.cat((phase.cos(), phase.cos()), dim=-1)[None, None, :, :]
sin = torch.cat((phase.sin(), phase.sin()), dim=-1)[None, None, :, :]
def rotate(x: torch.Tensor) -> torch.Tensor:
first, second = x.chunk(2, dim=-1)
return torch.cat((-second, first), dim=-1)
return query * cos.to(query.dtype) + rotate(query) * sin.to(query.dtype), (
key * cos.to(key.dtype) + rotate(key) * sin.to(key.dtype)
)
class CausalSelfAttention(nn.Module):
def __init__(self, config: GPTConfig) -> None:
super().__init__()
if config.d_model % config.n_heads:
raise ValueError("d_model must be divisible by n_heads")
self.n_heads = config.n_heads
self.head_dim = config.d_model // config.n_heads
if self.head_dim % 2:
raise ValueError("RoPE requires an even attention head dimension")
self.rope_base = config.rope_base
self.qkv = nn.Linear(config.d_model, 3 * config.d_model, bias=False)
self.out_proj = nn.Linear(config.d_model, config.d_model, bias=False)
def forward(self, x: torch.Tensor, causal: bool = True) -> torch.Tensor:
batch_size, sequence_length, width = x.shape
qkv = self.qkv(x).view(
batch_size, sequence_length, 3, self.n_heads, self.head_dim
)
query, key, value = qkv.permute(2, 0, 3, 1, 4).unbind(0)
positions = torch.arange(sequence_length, device=x.device)
query, key = apply_rope(query, key, positions, self.rope_base)
attended = F.scaled_dot_product_attention(
query, key, value, is_causal=causal, dropout_p=0.0
)
attended = attended.transpose(1, 2).contiguous().view(
batch_size, sequence_length, width
)
return self.out_proj(attended)
class SwiGLU(nn.Module):
def __init__(self, config: GPTConfig) -> None:
super().__init__()
self.gate_proj = nn.Linear(config.d_model, config.ffn_dim, bias=False)
self.up_proj = nn.Linear(config.d_model, config.ffn_dim, bias=False)
self.down_proj = nn.Linear(config.ffn_dim, config.d_model, bias=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
class TransformerBlock(nn.Module):
def __init__(self, config: GPTConfig) -> None:
super().__init__()
self.attn_norm = RMSNorm(config.d_model, config.norm_eps)
self.attention = CausalSelfAttention(config)
self.mlp_norm = RMSNorm(config.d_model, config.norm_eps)
self.mlp = SwiGLU(config)
def forward(self, x: torch.Tensor, causal: bool = True) -> torch.Tensor:
x = x + self.attention(self.attn_norm(x), causal=causal)
return x + self.mlp(self.mlp_norm(x))
class GPT(nn.Module):
def __init__(self, config: GPTConfig = GPTConfig()) -> None:
super().__init__()
self.config = config
self.token_embedding = nn.Embedding(config.vocab_size, config.d_model)
self.blocks = nn.ModuleList(
TransformerBlock(config) for _ in range(config.n_layers)
)
self.final_norm = RMSNorm(config.d_model, config.norm_eps)
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
self.lm_head.weight = self.token_embedding.weight
self.apply(self._init_weights)
self._init_residual_projections()
@staticmethod
def _init_weights(module: nn.Module) -> None:
if isinstance(module, nn.Linear):
nn.init.normal_(module.weight, mean=0.0, std=0.02)
elif isinstance(module, nn.Embedding):
nn.init.normal_(module.weight, mean=0.0, std=0.02)
def _init_residual_projections(self) -> None:
std = 0.02 / (2 * self.config.n_layers) ** 0.5
for block in self.blocks:
nn.init.normal_(block.attention.out_proj.weight, mean=0.0, std=std)
nn.init.normal_(block.mlp.down_proj.weight, mean=0.0, std=std)
def parameter_count(self) -> int:
return sum(parameter.numel() for parameter in self.parameters())
def forward(
self,
input_ids: torch.Tensor,
targets: torch.Tensor | None = None,
causal: bool = True,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
if input_ids.ndim != 2:
raise ValueError("input_ids must have shape (batch, sequence)")
if input_ids.size(1) > self.config.context_length:
raise ValueError(
f"sequence length {input_ids.size(1)} exceeds context length "
f"{self.config.context_length}"
)
if targets is not None and targets.shape != input_ids.shape:
raise ValueError("targets must have the same shape as input_ids")
x = self.token_embedding(input_ids)
for block in self.blocks:
x = block(x, causal=causal)
logits = F.linear(self.final_norm(x), self.token_embedding.weight)
if targets is None:
return logits
loss = F.cross_entropy(
logits.float().view(-1, self.config.vocab_size),
targets.reshape(-1),
ignore_index=-100,
)
return logits, loss
@torch.no_grad()
def generate(
self,
input_ids: torch.Tensor,
max_new_tokens: int = 100,
temperature: float = 1.0,
top_k: int | None = 50,
eos_token_id: int | None = None,
) -> torch.Tensor:
if temperature <= 0:
raise ValueError("temperature must be greater than zero")
if top_k is not None and top_k < 1:
raise ValueError("top_k must be at least one")
was_training = self.training
self.eval()
try:
for _ in range(max_new_tokens):
context = input_ids[:, -self.config.context_length :]
logits = self(context)[:, -1, :] / temperature
if top_k is not None:
threshold = torch.topk(logits, min(top_k, logits.size(-1))).values[:, -1:]
logits = logits.masked_fill(logits < threshold, float("-inf"))
probabilities = F.softmax(logits, dim=-1)
next_token = torch.multinomial(probabilities, num_samples=1)
input_ids = torch.cat((input_ids, next_token), dim=1)
if eos_token_id is not None and torch.all(next_token == eos_token_id):
break
return input_ids
finally:
self.train(was_training)
if __name__ == "__main__":
model = GPT()
print(f"Parameters: {model.parameter_count():,}") |