Eeppa commited on
Commit
83154d1
·
verified ·
1 Parent(s): 261ebf5

Create Model.py

Browse files
Files changed (1) hide show
  1. Model.py +169 -0
Model.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tiny GPT-style transformer (~30M params target).
3
+
4
+ Config:
5
+ - 6 layers
6
+ - 8 heads
7
+ - d_model = 256
8
+ - vocab_size = 32000 (chosen to push param count up to ~30M, since the
9
+ transformer blocks themselves only have ~5M params at d_model=256/L=6;
10
+ the embedding + tied LM head dominates the parameter budget.)
11
+
12
+ Parameter accounting (approx):
13
+ Token embedding : 32000 * 256 = 8,192,000
14
+ LM head (untied) : 256 * 32000 + 32000 = 8,224,000
15
+ Positional emb : 512 * 256 = 131,072
16
+ Per block (x6):
17
+ attn (qkv+out) : 4 * 256 * 256 + 4*256 = 263,168
18
+ mlp (2 linear): 256*1024 + 1024 + 1024*256+256 = 525,568
19
+ 2x LayerNorm : 4 * 256 = 1,024
20
+ block total = 789,760
21
+ Blocks total : 6 * 789,760 = 4,738,560
22
+ Final LN : 512
23
+ ---------------------------------------------------------
24
+ TOTAL ~ 21.3M (tied) or ~29.5M (untied lm head) -> ~30M ✓
25
+ """
26
+
27
+ import math
28
+ import torch
29
+ import torch.nn as nn
30
+ import torch.nn.functional as F
31
+ from dataclasses import dataclass
32
+
33
+
34
+ @dataclass
35
+ class GPTConfig:
36
+ vocab_size: int = 32000
37
+ block_size: int = 512 # max context length
38
+ n_layer: int = 6
39
+ n_head: int = 8
40
+ n_embd: int = 256
41
+ mlp_ratio: int = 4 # hidden = 4 * n_embd
42
+ dropout: float = 0.0
43
+ tie_weights: bool = False # False -> ~30M params; True -> ~21M
44
+
45
+
46
+ class CausalSelfAttention(nn.Module):
47
+ def __init__(self, cfg: GPTConfig):
48
+ super().__init__()
49
+ assert cfg.n_embd % cfg.n_head == 0
50
+ self.n_head = cfg.n_head
51
+ self.n_embd = cfg.n_embd
52
+ self.head_dim = cfg.n_embd // cfg.n_head
53
+ self.qkv = nn.Linear(cfg.n_embd, 3 * cfg.n_embd, bias=True)
54
+ self.proj = nn.Linear(cfg.n_embd, cfg.n_embd, bias=True)
55
+ self.drop = nn.Dropout(cfg.dropout)
56
+ # causal mask
57
+ mask = torch.tril(torch.ones(cfg.block_size, cfg.block_size)).bool()
58
+ self.register_buffer("mask", mask, persistent=False)
59
+
60
+ def forward(self, x):
61
+ B, T, C = x.shape
62
+ qkv = self.qkv(x)
63
+ q, k, v = qkv.split(self.n_embd, dim=2)
64
+ q = q.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
65
+ k = k.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
66
+ v = v.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
67
+ # use PyTorch's fused SDPA (faster on CPU than manual)
68
+ y = F.scaled_dot_product_attention(q, k, v, is_causal=True,
69
+ dropout_p=self.drop.p if self.training else 0.0)
70
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
71
+ return self.proj(y)
72
+
73
+
74
+ class MLP(nn.Module):
75
+ def __init__(self, cfg: GPTConfig):
76
+ super().__init__()
77
+ hidden = cfg.mlp_ratio * cfg.n_embd
78
+ self.fc1 = nn.Linear(cfg.n_embd, hidden, bias=True)
79
+ self.fc2 = nn.Linear(hidden, cfg.n_embd, bias=True)
80
+ self.drop = nn.Dropout(cfg.dropout)
81
+
82
+ def forward(self, x):
83
+ return self.drop(self.fc2(F.gelu(self.fc1(x))))
84
+
85
+
86
+ class Block(nn.Module):
87
+ def __init__(self, cfg: GPTConfig):
88
+ super().__init__()
89
+ self.ln1 = nn.LayerNorm(cfg.n_embd)
90
+ self.attn = CausalSelfAttention(cfg)
91
+ self.ln2 = nn.LayerNorm(cfg.n_embd)
92
+ self.mlp = MLP(cfg)
93
+
94
+ def forward(self, x):
95
+ x = x + self.attn(self.ln1(x))
96
+ x = x + self.mlp(self.ln2(x))
97
+ return x
98
+
99
+
100
+ class TinyGPT(nn.Module):
101
+ def __init__(self, cfg: GPTConfig):
102
+ super().__init__()
103
+ self.cfg = cfg
104
+ self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.n_embd)
105
+ self.pos_emb = nn.Embedding(cfg.block_size, cfg.n_embd)
106
+ self.drop = nn.Dropout(cfg.dropout)
107
+ self.blocks = nn.ModuleList([Block(cfg) for _ in range(cfg.n_layer)])
108
+ self.ln_f = nn.LayerNorm(cfg.n_embd)
109
+ self.lm_head = nn.Linear(cfg.n_embd, cfg.vocab_size, bias=False)
110
+ if cfg.tie_weights:
111
+ self.lm_head.weight = self.tok_emb.weight
112
+ self.apply(self._init_weights)
113
+
114
+ @staticmethod
115
+ def _init_weights(m):
116
+ if isinstance(m, nn.Linear):
117
+ nn.init.normal_(m.weight, mean=0.0, std=0.02)
118
+ if m.bias is not None:
119
+ nn.init.zeros_(m.bias)
120
+ elif isinstance(m, nn.Embedding):
121
+ nn.init.normal_(m.weight, mean=0.0, std=0.02)
122
+
123
+ def num_params(self, non_embedding=False):
124
+ n = sum(p.numel() for p in self.parameters())
125
+ if non_embedding:
126
+ n -= self.tok_emb.weight.numel() + self.pos_emb.weight.numel()
127
+ if not self.cfg.tie_weights:
128
+ n -= self.lm_head.weight.numel()
129
+ return n
130
+
131
+ def forward(self, idx, targets=None):
132
+ B, T = idx.shape
133
+ assert T <= self.cfg.block_size, f"sequence length {T} > block_size {self.cfg.block_size}"
134
+ pos = torch.arange(T, device=idx.device)
135
+ x = self.tok_emb(idx) + self.pos_emb(pos)[None, :, :]
136
+ x = self.drop(x)
137
+ for blk in self.blocks:
138
+ x = blk(x)
139
+ x = self.ln_f(x)
140
+ logits = self.lm_head(x)
141
+ loss = None
142
+ if targets is not None:
143
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)),
144
+ targets.view(-1), ignore_index=-100)
145
+ return logits, loss
146
+
147
+ @torch.no_grad()
148
+ def generate(self, idx, max_new_tokens=100, temperature=1.0, top_k=None):
149
+ self.eval()
150
+ for _ in range(max_new_tokens):
151
+ idx_cond = idx if idx.size(1) <= self.cfg.block_size else idx[:, -self.cfg.block_size:]
152
+ logits, _ = self(idx_cond)
153
+ logits = logits[:, -1, :] / max(temperature, 1e-6)
154
+ if top_k is not None:
155
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
156
+ logits[logits < v[:, [-1]]] = -float("inf")
157
+ probs = F.softmax(logits, dim=-1)
158
+ next_id = torch.multinomial(probs, num_samples=1)
159
+ idx = torch.cat([idx, next_id], dim=1)
160
+ return idx
161
+
162
+
163
+ if __name__ == "__main__":
164
+ cfg = GPTConfig()
165
+ m = TinyGPT(cfg)
166
+ total = m.num_params()
167
+ nonemb = m.num_params(non_embedding=True)
168
+ print(f"Total params : {total:,} (~{total/1e6:.2f}M)")
169
+ print(f"Non-embedding params: {nonemb:,} (~{nonemb/1e6:.2f}M)")