-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
63 lines (55 loc) · 2.48 KB
/
model.py
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
import torch
from torch import nn
from torch.nn import functional as F
from model_utils import Block
device = "cuda" if torch.cuda.is_available() else "cpu"
class Gpt(nn.Module):
def __init__(self, vocab_size, n_embd, n_layer, n_head, block_size, dropout=None):
super().__init__()
self.vocab_size = vocab_size
self.n_embd = n_embd
self.n_layer = n_layer
self.n_head = n_head
self.block_size = block_size
self.dropout = dropout
# each token directly reads off the logits for the next token from a lookup table
self.token_embedding_table = nn.Embedding(self.vocab_size, self.n_embd)
self.position_embedding_table = nn.Embedding(self.block_size, self.n_embd)
self.blocks = nn.Sequential(
*[Block(self.n_embd, self.n_head, self.block_size, self.dropout) for _ in range(self.n_layer)]
)
self.ln_f = nn.LayerNorm(self.n_embd) # final layer norm
self.lm_head = nn.Linear(self.n_embd, self.vocab_size)
def forward(self, idx, targets=None):
B, T = idx.shape
# idx and targets are both (B,T) tensor of integers
tok_emb = self.token_embedding_table(idx) # (B,T,C)
pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)
x = tok_emb + pos_emb # (B,T,C)
x = self.blocks(x) # (B,T,C)
x = self.ln_f(x) # (B,T,C)
logits = self.lm_head(x) # (B,T,vocab_size)
if targets is None:
loss = None
else:
B, T, C = logits.shape
logits = logits.view(B * T, C)
targets = targets.view(B * T)
loss = F.cross_entropy(logits, targets)
return logits, loss
def generate(self, idx, max_new_tokens, block_size):
# idx is (B, T) array of indices in the current context
for _ in range(max_new_tokens):
# crop idx to the last block_size tokens
idx_cond = idx[:, -block_size:]
# get the predictions
logits, loss = self(idx_cond)
# focus only on the last time step
logits = logits[:, -1, :] # becomes (B, C)
# apply softmax to get probabilities
probs = F.softmax(logits, dim=-1) # (B, C)
# sample from the distribution
idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
# append sampled index to the running sequence
idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
return idx