Upload src/model.py with huggingface_hub
Browse files- src/model.py +127 -0
src/model.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Milestone 4: Full GPT model.
|
| 3 |
+
|
| 4 |
+
Architecture:
|
| 5 |
+
- Token embedding table
|
| 6 |
+
- Learned positional embedding table (will be replaced with RoPE in modernization)
|
| 7 |
+
- Stack of transformer Blocks
|
| 8 |
+
- Final LayerNorm
|
| 9 |
+
- Linear language model head (maps n_embd -> vocab_size)
|
| 10 |
+
|
| 11 |
+
~10M parameters with the default config.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
import torch.nn as nn
|
| 16 |
+
import torch.nn.functional as F
|
| 17 |
+
|
| 18 |
+
from transformer import Block
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class GPT(nn.Module):
|
| 22 |
+
|
| 23 |
+
def __init__(
|
| 24 |
+
self,
|
| 25 |
+
vocab_size: int,
|
| 26 |
+
n_embd: int = 384,
|
| 27 |
+
n_heads: int = 6,
|
| 28 |
+
n_layer: int = 6,
|
| 29 |
+
block_size: int = 256,
|
| 30 |
+
dropout: float = 0.2,
|
| 31 |
+
):
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.block_size = block_size
|
| 34 |
+
|
| 35 |
+
self.token_emb = nn.Embedding(vocab_size, n_embd)
|
| 36 |
+
self.pos_emb = nn.Embedding(block_size, n_embd) # learned positional embeddings
|
| 37 |
+
|
| 38 |
+
self.blocks = nn.Sequential(*[
|
| 39 |
+
Block(n_embd=n_embd, n_heads=n_heads, block_size=block_size, dropout=dropout)
|
| 40 |
+
for _ in range(n_layer)
|
| 41 |
+
])
|
| 42 |
+
self.ln_f = nn.LayerNorm(n_embd) # final layer norm
|
| 43 |
+
self.lm_head = nn.Linear(n_embd, vocab_size, bias=False)
|
| 44 |
+
|
| 45 |
+
# Weight tying: share token embedding and lm_head weights.
|
| 46 |
+
# Standard in GPT-2 β reduces params and improves performance.
|
| 47 |
+
self.lm_head.weight = self.token_emb.weight
|
| 48 |
+
|
| 49 |
+
self._init_weights()
|
| 50 |
+
|
| 51 |
+
def _init_weights(self):
|
| 52 |
+
"""Initialize weights following GPT-2 paper."""
|
| 53 |
+
for module in self.modules():
|
| 54 |
+
if isinstance(module, nn.Linear):
|
| 55 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 56 |
+
if module.bias is not None:
|
| 57 |
+
nn.init.zeros_(module.bias)
|
| 58 |
+
elif isinstance(module, nn.Embedding):
|
| 59 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 60 |
+
|
| 61 |
+
def forward(self, idx: torch.Tensor, targets: torch.Tensor | None = None):
|
| 62 |
+
B, T = idx.shape
|
| 63 |
+
assert T <= self.block_size, f"Sequence length {T} exceeds block_size {self.block_size}"
|
| 64 |
+
|
| 65 |
+
positions = torch.arange(T, device=idx.device) # (T,)
|
| 66 |
+
x = self.token_emb(idx) + self.pos_emb(positions) # (B, T, n_embd)
|
| 67 |
+
x = self.blocks(x) # (B, T, n_embd)
|
| 68 |
+
x = self.ln_f(x) # (B, T, n_embd)
|
| 69 |
+
logits = self.lm_head(x) # (B, T, vocab_size)
|
| 70 |
+
|
| 71 |
+
loss = None
|
| 72 |
+
if targets is not None:
|
| 73 |
+
# Reshape for cross-entropy: (B*T, vocab_size) vs (B*T,)
|
| 74 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
|
| 75 |
+
|
| 76 |
+
return logits, loss
|
| 77 |
+
|
| 78 |
+
@torch.no_grad()
|
| 79 |
+
def generate(
|
| 80 |
+
self,
|
| 81 |
+
idx: torch.Tensor,
|
| 82 |
+
max_new_tokens: int,
|
| 83 |
+
temperature: float = 1.0,
|
| 84 |
+
top_k: int | None = None,
|
| 85 |
+
) -> torch.Tensor:
|
| 86 |
+
"""Autoregressively generate new tokens.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
idx: (B, T) tensor of seed token ids
|
| 90 |
+
max_new_tokens: number of tokens to generate
|
| 91 |
+
temperature: >1 = more random, <1 = more focused
|
| 92 |
+
top_k: if set, only sample from the top-k logits
|
| 93 |
+
"""
|
| 94 |
+
for _ in range(max_new_tokens):
|
| 95 |
+
# Crop context to block_size
|
| 96 |
+
idx_cond = idx[:, -self.block_size:]
|
| 97 |
+
logits, _ = self(idx_cond)
|
| 98 |
+
logits = logits[:, -1, :] / temperature # (B, vocab_size) β last time step
|
| 99 |
+
|
| 100 |
+
if top_k is not None:
|
| 101 |
+
# Zero out all logits below the top-k
|
| 102 |
+
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
| 103 |
+
logits[logits < v[:, [-1]]] = float("-inf")
|
| 104 |
+
|
| 105 |
+
probs = F.softmax(logits, dim=-1)
|
| 106 |
+
next_id = torch.multinomial(probs, num_samples=1) # (B, 1)
|
| 107 |
+
idx = torch.cat([idx, next_id], dim=1) # (B, T+1)
|
| 108 |
+
|
| 109 |
+
return idx
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# ββ Quick model size check ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 113 |
+
if __name__ == "__main__":
|
| 114 |
+
from tokenizer import DEVICE, VOCAB_SIZE, BLOCK_SIZE
|
| 115 |
+
|
| 116 |
+
model = GPT(vocab_size=VOCAB_SIZE, block_size=BLOCK_SIZE).to(DEVICE)
|
| 117 |
+
|
| 118 |
+
n_params = sum(p.numel() for p in model.parameters())
|
| 119 |
+
print(f"Model parameters: {n_params:,} (~{n_params/1e6:.1f}M)")
|
| 120 |
+
|
| 121 |
+
# Forward pass test
|
| 122 |
+
x = torch.zeros((2, 8), dtype=torch.long, device=DEVICE)
|
| 123 |
+
logits, loss = model(x, x)
|
| 124 |
+
print(f"Logits shape : {logits.shape} (expected [2, 8, {VOCAB_SIZE}])")
|
| 125 |
+
print(f"Loss (untrained): {loss.item():.4f} (expected ~{__import__('math').log(VOCAB_SIZE):.2f})")
|
| 126 |
+
|
| 127 |
+
print("\nMilestone 4 OK: GPT model works.")
|