Update model.py
Browse files
model.py
CHANGED
@@ -47,78 +47,78 @@ n = int(0.9*len(data)) # first 90% will be train, rest val
|
|
47 |
train_data = data[:n]
|
48 |
val_data = data[n:]
|
49 |
|
50 |
-
|
51 |
-
|
52 |
-
# generate a small batch of data of inputs x and targets y
|
53 |
-
data = train_data if split == 'train' else val_data
|
54 |
-
ix = torch.randint(len(data) - block_size, (batch_size,))
|
55 |
-
x = torch.stack([data[i:i+block_size] for i in ix])
|
56 |
-
y = torch.stack([data[i+1:i+block_size+1] for i in ix])
|
57 |
-
x, y = x.to(device), y.to(device)
|
58 |
-
return x, y
|
59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
def __init__(self, ndim, bias):
|
65 |
-
super().__init__()
|
66 |
-
self.weight = nn.Parameter(torch.ones(ndim))
|
67 |
-
self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None
|
68 |
-
|
69 |
-
def forward(self, input):
|
70 |
-
return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5)
|
71 |
-
|
72 |
-
class CausalSelfAttention(nn.Module):
|
73 |
-
|
74 |
-
def __init__(self, config):
|
75 |
-
super().__init__()
|
76 |
-
assert config.n_embd % config.n_head == 0
|
77 |
-
# key, query, value projections for all heads, but in a batch
|
78 |
-
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
|
79 |
-
# output projection
|
80 |
-
self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
|
81 |
-
# regularization
|
82 |
-
self.attn_dropout = nn.Dropout(config.dropout)
|
83 |
-
self.resid_dropout = nn.Dropout(config.dropout)
|
84 |
-
self.n_head = config.n_head
|
85 |
-
self.n_embd = config.n_embd
|
86 |
-
self.dropout = config.dropout
|
87 |
-
# flash attention make GPU go brrrrr but support is only in PyTorch >= 2.0
|
88 |
-
self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention')
|
89 |
-
if not self.flash:
|
90 |
-
print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
|
91 |
-
# causal mask to ensure that attention is only applied to the left in the input sequence
|
92 |
-
self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
|
93 |
-
.view(1, 1, config.block_size, config.block_size))
|
94 |
-
|
95 |
-
def forward(self, x):
|
96 |
-
B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
|
97 |
-
|
98 |
-
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
|
99 |
-
q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
|
100 |
-
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
101 |
-
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
102 |
-
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
103 |
-
|
104 |
-
# causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
|
105 |
-
if self.flash:
|
106 |
-
# efficient attention using Flash Attention CUDA kernels
|
107 |
-
y = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=self.dropout if self.training else 0, is_causal=True)
|
108 |
-
else:
|
109 |
-
# manual implementation of attention
|
110 |
-
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
|
111 |
-
att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float('-inf'))
|
112 |
-
att = F.softmax(att, dim=-1)
|
113 |
-
att = self.attn_dropout(att)
|
114 |
-
y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
|
115 |
-
y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
|
116 |
|
117 |
-
|
118 |
-
|
119 |
-
return y
|
120 |
|
121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
122 |
class BigramLanguageModel(nn.Module):
|
123 |
|
124 |
def __init__(self):
|
@@ -151,257 +151,19 @@ class BigramLanguageModel(nn.Module):
|
|
151 |
|
152 |
return logits, loss
|
153 |
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
class Block(nn.Module):
|
172 |
-
|
173 |
-
def __init__(self, config):
|
174 |
-
super().__init__()
|
175 |
-
self.ln_1 = LayerNorm(config.n_embd, bias=config.bias)
|
176 |
-
self.attn = CausalSelfAttention(config)
|
177 |
-
self.ln_2 = LayerNorm(config.n_embd, bias=config.bias)
|
178 |
-
self.mlp = MLP(config)
|
179 |
-
|
180 |
-
def forward(self, x):
|
181 |
-
x = x + self.attn(self.ln_1(x))
|
182 |
-
x = x + self.mlp(self.ln_2(x))
|
183 |
-
return x
|
184 |
-
|
185 |
-
@dataclass
|
186 |
-
class GPTConfig:
|
187 |
-
block_size: int = 1024
|
188 |
-
vocab_size: int = 50304 # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency
|
189 |
-
n_layer: int = 12
|
190 |
-
n_head: int = 12
|
191 |
-
n_embd: int = 768
|
192 |
-
dropout: float = 0.0
|
193 |
-
bias: bool = True # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster
|
194 |
-
|
195 |
-
class GPT(nn.Module):
|
196 |
-
|
197 |
-
def __init__(self, config):
|
198 |
-
super().__init__()
|
199 |
-
assert config.vocab_size is not None
|
200 |
-
assert config.block_size is not None
|
201 |
-
self.config = config
|
202 |
-
|
203 |
-
self.transformer = nn.ModuleDict(dict(
|
204 |
-
wte = nn.Embedding(config.vocab_size, config.n_embd),
|
205 |
-
wpe = nn.Embedding(config.block_size, config.n_embd),
|
206 |
-
drop = nn.Dropout(config.dropout),
|
207 |
-
h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
|
208 |
-
ln_f = LayerNorm(config.n_embd, bias=config.bias),
|
209 |
-
))
|
210 |
-
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
211 |
-
# with weight tying when using torch.compile() some warnings get generated:
|
212 |
-
# "UserWarning: functional_call was passed multiple values for tied weights.
|
213 |
-
# This behavior is deprecated and will be an error in future versions"
|
214 |
-
# not 100% sure what this is, so far seems to be harmless. TODO investigate
|
215 |
-
self.transformer.wte.weight = self.lm_head.weight # https://paperswithcode.com/method/weight-tying
|
216 |
-
|
217 |
-
# init all weights
|
218 |
-
self.apply(self._init_weights)
|
219 |
-
# apply special scaled init to the residual projections, per GPT-2 paper
|
220 |
-
for pn, p in self.named_parameters():
|
221 |
-
if pn.endswith('c_proj.weight'):
|
222 |
-
torch.nn.init.normal_(p, mean=0.0, std=0.02/math.sqrt(2 * config.n_layer))
|
223 |
-
|
224 |
-
# report number of parameters
|
225 |
-
print("number of parameters: %.2fM" % (self.get_num_params()/1e6,))
|
226 |
-
|
227 |
-
def get_num_params(self, non_embedding=True):
|
228 |
-
"""
|
229 |
-
Return the number of parameters in the model.
|
230 |
-
For non-embedding count (default), the position embeddings get subtracted.
|
231 |
-
The token embeddings would too, except due to the parameter sharing these
|
232 |
-
params are actually used as weights in the final layer, so we include them.
|
233 |
-
"""
|
234 |
-
n_params = sum(p.numel() for p in self.parameters())
|
235 |
-
if non_embedding:
|
236 |
-
n_params -= self.transformer.wpe.weight.numel()
|
237 |
-
return n_params
|
238 |
-
|
239 |
-
def _init_weights(self, module):
|
240 |
-
if isinstance(module, nn.Linear):
|
241 |
-
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
242 |
-
if module.bias is not None:
|
243 |
-
torch.nn.init.zeros_(module.bias)
|
244 |
-
elif isinstance(module, nn.Embedding):
|
245 |
-
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
246 |
-
|
247 |
-
def forward(self, idx, targets=None):
|
248 |
-
device = idx.device
|
249 |
-
b, t = idx.size()
|
250 |
-
assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
|
251 |
-
pos = torch.arange(0, t, dtype=torch.long, device=device) # shape (t)
|
252 |
-
|
253 |
-
# forward the GPT model itself
|
254 |
-
tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
|
255 |
-
pos_emb = self.transformer.wpe(pos) # position embeddings of shape (t, n_embd)
|
256 |
-
x = self.transformer.drop(tok_emb + pos_emb)
|
257 |
-
for block in self.transformer.h:
|
258 |
-
x = block(x)
|
259 |
-
x = self.transformer.ln_f(x)
|
260 |
-
|
261 |
-
if targets is not None:
|
262 |
-
# if we are given some desired targets also calculate the loss
|
263 |
-
logits = self.lm_head(x)
|
264 |
-
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
|
265 |
-
else:
|
266 |
-
# inference-time mini-optimization: only forward the lm_head on the very last position
|
267 |
-
logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim
|
268 |
-
loss = None
|
269 |
-
|
270 |
-
return logits, loss
|
271 |
-
|
272 |
-
def crop_block_size(self, block_size):
|
273 |
-
# model surgery to decrease the block size if necessary
|
274 |
-
# e.g. we may load the GPT2 pretrained model checkpoint (block size 1024)
|
275 |
-
# but want to use a smaller block size for some smaller, simpler model
|
276 |
-
assert block_size <= self.config.block_size
|
277 |
-
self.config.block_size = block_size
|
278 |
-
self.transformer.wpe.weight = nn.Parameter(self.transformer.wpe.weight[:block_size])
|
279 |
-
for block in self.transformer.h:
|
280 |
-
if hasattr(block.attn, 'bias'):
|
281 |
-
block.attn.bias = block.attn.bias[:,:,:block_size,:block_size]
|
282 |
-
|
283 |
-
@classmethod
|
284 |
-
def from_pretrained(cls, model_type, override_args=None):
|
285 |
-
assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
|
286 |
-
override_args = override_args or {} # default to empty dict
|
287 |
-
# only dropout can be overridden see more notes below
|
288 |
-
assert all(k == 'dropout' for k in override_args)
|
289 |
-
from transformers import GPT2LMHeadModel
|
290 |
-
print("loading weights from pretrained gpt: %s" % model_type)
|
291 |
-
|
292 |
-
# n_layer, n_head and n_embd are determined from model_type
|
293 |
-
config_args = {
|
294 |
-
'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
|
295 |
-
'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
|
296 |
-
'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
|
297 |
-
'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
|
298 |
-
}[model_type]
|
299 |
-
print("forcing vocab_size=50257, block_size=1024, bias=True")
|
300 |
-
config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
|
301 |
-
config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
|
302 |
-
config_args['bias'] = True # always True for GPT model checkpoints
|
303 |
-
# we can override the dropout rate, if desired
|
304 |
-
if 'dropout' in override_args:
|
305 |
-
print(f"overriding dropout rate to {override_args['dropout']}")
|
306 |
-
config_args['dropout'] = override_args['dropout']
|
307 |
-
# create a from-scratch initialized minGPT model
|
308 |
-
config = GPTConfig(**config_args)
|
309 |
-
model = GPT(config)
|
310 |
-
sd = model.state_dict()
|
311 |
-
sd_keys = sd.keys()
|
312 |
-
sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param
|
313 |
-
|
314 |
-
# init a huggingface/transformers model
|
315 |
-
model_hf = GPT2LMHeadModel.from_pretrained(model_type)
|
316 |
-
sd_hf = model_hf.state_dict()
|
317 |
-
|
318 |
-
# copy while ensuring all of the parameters are aligned and match in names and shapes
|
319 |
-
sd_keys_hf = sd_hf.keys()
|
320 |
-
sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
|
321 |
-
sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
|
322 |
-
transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
|
323 |
-
# basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
|
324 |
-
# this means that we have to transpose these weights when we import them
|
325 |
-
assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
|
326 |
-
for k in sd_keys_hf:
|
327 |
-
if any(k.endswith(w) for w in transposed):
|
328 |
-
# special treatment for the Conv1D weights we need to transpose
|
329 |
-
assert sd_hf[k].shape[::-1] == sd[k].shape
|
330 |
-
with torch.no_grad():
|
331 |
-
sd[k].copy_(sd_hf[k].t())
|
332 |
-
else:
|
333 |
-
# vanilla copy over the other parameters
|
334 |
-
assert sd_hf[k].shape == sd[k].shape
|
335 |
-
with torch.no_grad():
|
336 |
-
sd[k].copy_(sd_hf[k])
|
337 |
-
|
338 |
-
return model
|
339 |
-
|
340 |
-
def configure_optimizers(self, weight_decay, learning_rate, betas, device_type):
|
341 |
-
# start with all of the candidate parameters
|
342 |
-
param_dict = {pn: p for pn, p in self.named_parameters()}
|
343 |
-
# filter out those that do not require grad
|
344 |
-
param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
|
345 |
-
# create optim groups. Any parameters that is 2D will be weight decayed, otherwise no.
|
346 |
-
# i.e. all weight tensors in matmuls + embeddings decay, all biases and layernorms don't.
|
347 |
-
decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]
|
348 |
-
nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2]
|
349 |
-
optim_groups = [
|
350 |
-
{'params': decay_params, 'weight_decay': weight_decay},
|
351 |
-
{'params': nodecay_params, 'weight_decay': 0.0}
|
352 |
-
]
|
353 |
-
num_decay_params = sum(p.numel() for p in decay_params)
|
354 |
-
num_nodecay_params = sum(p.numel() for p in nodecay_params)
|
355 |
-
print(f"num decayed parameter tensors: {len(decay_params)}, with {num_decay_params:,} parameters")
|
356 |
-
print(f"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay_params:,} parameters")
|
357 |
-
# Create AdamW optimizer and use the fused version if it is available
|
358 |
-
fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
|
359 |
-
use_fused = fused_available and device_type == 'cuda'
|
360 |
-
extra_args = dict(fused=True) if use_fused else dict()
|
361 |
-
optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, **extra_args)
|
362 |
-
print(f"using fused AdamW: {use_fused}")
|
363 |
-
|
364 |
-
return optimizer
|
365 |
-
|
366 |
-
def estimate_mfu(self, fwdbwd_per_iter, dt):
|
367 |
-
""" estimate model flops utilization (MFU) in units of A100 bfloat16 peak FLOPS """
|
368 |
-
# first estimate the number of flops we do per iteration.
|
369 |
-
# see PaLM paper Appendix B as ref: https://arxiv.org/abs/2204.02311
|
370 |
-
N = self.get_num_params()
|
371 |
-
cfg = self.config
|
372 |
-
L, H, Q, T = cfg.n_layer, cfg.n_head, cfg.n_embd//cfg.n_head, cfg.block_size
|
373 |
-
flops_per_token = 6*N + 12*L*H*Q*T
|
374 |
-
flops_per_fwdbwd = flops_per_token * T
|
375 |
-
flops_per_iter = flops_per_fwdbwd * fwdbwd_per_iter
|
376 |
-
# express our flops throughput as ratio of A100 bfloat16 peak flops
|
377 |
-
flops_achieved = flops_per_iter * (1.0/dt) # per second
|
378 |
-
flops_promised = 312e12 # A100 GPU bfloat16 peak flops is 312 TFLOPS
|
379 |
-
mfu = flops_achieved / flops_promised
|
380 |
-
return mfu
|
381 |
-
|
382 |
-
@torch.no_grad()
|
383 |
-
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
|
384 |
-
"""
|
385 |
-
Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete
|
386 |
-
the sequence max_new_tokens times, feeding the predictions back into the model each time.
|
387 |
-
Most likely you'll want to make sure to be in model.eval() mode of operation for this.
|
388 |
-
"""
|
389 |
-
for _ in range(max_new_tokens):
|
390 |
-
# if the sequence context is growing too long we must crop it at block_size
|
391 |
-
idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
|
392 |
-
# forward the model to get the logits for the index in the sequence
|
393 |
-
logits, _ = self(idx_cond)
|
394 |
-
# pluck the logits at the final step and scale by desired temperature
|
395 |
-
logits = logits[:, -1, :] / temperature
|
396 |
-
# optionally crop the logits to only the top k options
|
397 |
-
if top_k is not None:
|
398 |
-
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
399 |
-
logits[logits < v[:, [-1]]] = -float('Inf')
|
400 |
-
# apply softmax to convert logits to (normalized) probabilities
|
401 |
-
probs = F.softmax(logits, dim=-1)
|
402 |
-
# sample from the distribution
|
403 |
-
idx_next = torch.multinomial(probs, num_samples=1)
|
404 |
-
# append sampled index to the running sequence and continue
|
405 |
-
idx = torch.cat((idx, idx_next), dim=1)
|
406 |
-
|
407 |
-
return idx
|
|
|
47 |
train_data = data[:n]
|
48 |
val_data = data[n:]
|
49 |
|
50 |
+
class Head(nn.Module):
|
51 |
+
""" one head of self-attention """
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
52 |
|
53 |
+
def __init__(self, head_size):
|
54 |
+
super().__init__()
|
55 |
+
self.key = nn.Linear(n_embd, head_size, bias=False)
|
56 |
+
self.query = nn.Linear(n_embd, head_size, bias=False)
|
57 |
+
self.value = nn.Linear(n_embd, head_size, bias=False)
|
58 |
+
self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
|
59 |
+
|
60 |
+
self.dropout = nn.Dropout(dropout)
|
61 |
+
|
62 |
+
def forward(self, x):
|
63 |
+
B,T,C = x.shape
|
64 |
+
k = self.key(x) # (B,T,C)
|
65 |
+
q = self.query(x) # (B,T,C)
|
66 |
+
# compute attention scores ("affinities")
|
67 |
+
wei = q @ k.transpose(-2,-1) * C**-0.5 # (B, T, C) @ (B, C, T) -> (B, T, T)
|
68 |
+
wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
|
69 |
+
wei = F.softmax(wei, dim=-1) # (B, T, T)
|
70 |
+
wei = self.dropout(wei)
|
71 |
+
# perform the weighted aggregation of the values
|
72 |
+
v = self.value(x) # (B,T,C)
|
73 |
+
out = wei @ v # (B, T, T) @ (B, T, C) -> (B, T, C)
|
74 |
+
return out
|
75 |
+
|
76 |
+
class MultiHeadAttention(nn.Module):
|
77 |
+
""" multiple heads of self-attention in parallel """
|
78 |
+
|
79 |
+
def __init__(self, num_heads, head_size):
|
80 |
+
super().__init__()
|
81 |
+
self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
|
82 |
+
self.proj = nn.Linear(n_embd, n_embd)
|
83 |
+
self.dropout = nn.Dropout(dropout)
|
84 |
+
|
85 |
+
def forward(self, x):
|
86 |
+
out = torch.cat([h(x) for h in self.heads], dim=-1)
|
87 |
+
out = self.dropout(self.proj(out))
|
88 |
+
return out
|
89 |
+
class FeedFoward(nn.Module):
|
90 |
+
""" a simple linear layer followed by a non-linearity """
|
91 |
+
|
92 |
+
def __init__(self, n_embd):
|
93 |
+
super().__init__()
|
94 |
+
self.net = nn.Sequential(
|
95 |
+
nn.Linear(n_embd, 4 * n_embd),
|
96 |
+
nn.ReLU(),
|
97 |
+
nn.Linear(4 * n_embd, n_embd),
|
98 |
+
nn.Dropout(dropout),
|
99 |
+
)
|
100 |
|
101 |
+
def forward(self, x):
|
102 |
+
return self.net(x)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
|
104 |
+
class Block(nn.Module):
|
105 |
+
""" Transformer block: communication followed by computation """
|
|
|
106 |
|
107 |
+
def __init__(self, n_embd, n_head):
|
108 |
+
# n_embd: embedding dimension, n_head: the number of heads we'd like
|
109 |
+
super().__init__()
|
110 |
+
head_size = n_embd // n_head
|
111 |
+
self.sa = MultiHeadAttention(n_head, head_size)
|
112 |
+
self.ffwd = FeedFoward(n_embd)
|
113 |
+
self.ln1 = nn.LayerNorm(n_embd)
|
114 |
+
self.ln2 = nn.LayerNorm(n_embd)
|
115 |
+
|
116 |
+
def forward(self, x):
|
117 |
+
x = x + self.sa(self.ln1(x))
|
118 |
+
x = x + self.ffwd(self.ln2(x))
|
119 |
+
return x
|
120 |
+
|
121 |
+
# super simple bigram model
|
122 |
class BigramLanguageModel(nn.Module):
|
123 |
|
124 |
def __init__(self):
|
|
|
151 |
|
152 |
return logits, loss
|
153 |
|
154 |
+
def generate(self, idx, max_new_tokens):
|
155 |
+
# idx is (B, T) array of indices in the current context
|
156 |
+
for _ in range(max_new_tokens):
|
157 |
+
# crop idx to the last block_size tokens
|
158 |
+
idx_cond = idx[:, -block_size:]
|
159 |
+
# get the predictions
|
160 |
+
logits, loss = self(idx_cond)
|
161 |
+
# focus only on the last time step
|
162 |
+
logits = logits[:, -1, :] # becomes (B, C)
|
163 |
+
# apply softmax to get probabilities
|
164 |
+
probs = F.softmax(logits, dim=-1) # (B, C)
|
165 |
+
# sample from the distribution
|
166 |
+
idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
|
167 |
+
# append sampled index to the running sequence
|
168 |
+
idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
|
169 |
+
return idx
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|