-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
136 lines (110 loc) · 4.59 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
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
import torch
import torch.nn as nn
from torch.nn import functional as F
import math
from common import *
class CausalSelfAttention(nn.Module):
def __init__(self):
super().__init__()
# key, query, value projections for all heads, but in a batch
self.c_attn = nn.Linear(n_embd, 3 * n_embd, bias=False)
# output projection
self.c_proj = nn.Linear(n_embd, n_embd, bias=False)
# regularization
self.attn_dropout = nn.Dropout(dropout)
self.resid_dropout = nn.Dropout(dropout)
# causal mask
self.register_buffer(
"tril",
torch.tril(torch.ones(block_size, block_size)).view(
1, 1, block_size, block_size
),
)
def forward(self, x):
# batch size, sequence length, embedding dimensionality (n_embd)
B, T, C = x.size()
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
q, k, v = self.c_attn(x).split(n_embd, dim=2)
k = k.view(B, T, n_head, C // n_head).transpose(1, 2) # (B, nh, T, hs)
q = q.view(B, T, n_head, C // n_head).transpose(1, 2) # (B, nh, T, hs)
v = v.view(B, T, n_head, C // n_head).transpose(1, 2) # (B, nh, T, hs)
# causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
att = att.masked_fill(self.tril[:, :, :T, :T] == 0, float("-inf"))
att = F.softmax(att, dim=-1)
att = self.attn_dropout(att)
# (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
y = att @ v
# re-assemble all head outputs side by side
y = y.transpose(1, 2).contiguous().view(B, T, C)
# output projection
y = self.resid_dropout(self.c_proj(y))
return y
class FeedForward(nn.Module):
"""a simple linear layer followed by a non-linearity"""
def __init__(self, n_embd):
super().__init__()
self.net = nn.Sequential(
nn.Linear(n_embd, 4 * n_embd),
nn.ReLU(),
nn.Linear(4 * n_embd, n_embd),
nn.Dropout(dropout),
)
def forward(self, x):
return self.net(x)
class Block(nn.Module):
"""Transformer block: communication followed by computation"""
def __init__(self, n_embd):
super().__init__()
self.ln1 = nn.LayerNorm(n_embd, bias=False)
self.attn = CausalSelfAttention()
self.ln2 = nn.LayerNorm(n_embd, bias=False)
self.ffwd = FeedForward(n_embd)
def forward(self, x):
x = x + self.attn(self.ln1(x))
x = x + self.ffwd(self.ln2(x))
return x
class GPT(nn.Module):
def __init__(self):
super().__init__()
self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
self.position_embedding_table = nn.Embedding(block_size, n_embd)
self.blocks = nn.Sequential(*[Block(n_embd) for _ in range(n_layer)])
self.ln_f = nn.LayerNorm(n_embd)
self.lm_head = nn.Linear(n_embd, vocab_size)
def forward(self, context, targets=None):
device = context.device
B, T = context.shape
tok_emb = self.token_embedding_table(context) # (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)
x = self.ln_f(x)
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
@torch.no_grad()
def generate(self, context, max_new_tokens, temperature=1.0):
# context is a (B, T) array of indices in the current context
for _ in range(max_new_tokens):
# crop context to the last block_size tokens
context_cropped = context[:, -block_size:]
# get the predictions
logits, _ = self(context_cropped)
# pluck the logits at the last time step and scale by desired temperature
logits = logits[:, -1, :] / temperature
# apply softmax to get probabilites
probs = F.softmax(logits, dim=-1)
# sample from the distribution
next_char = torch.multinomial(probs, num_samples=1)
# append sampled index to the running sequence
context = torch.cat((context, next_char), dim=1)
return context