PrateekJ17 commited on
Commit
871f0bc
1 Parent(s): 22ebca0

Initial Files

Browse files
Files changed (3) hide show
  1. bigram.py +120 -0
  2. gpt.py +224 -0
  3. input.txt +0 -0
bigram.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.nn import functional as F
4
+
5
+ # hyperparameters
6
+ batch_size = 32 # how many independent sequences will we process in parallel?
7
+ block_size = 8 # what is the maximum context length for predictions?
8
+ max_iters = 3000
9
+ eval_interval = 300
10
+ learning_rate = 1e-2
11
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
12
+ eval_iters = 200
13
+ # ------------
14
+
15
+ torch.manual_seed(1337)
16
+ with open('input.txt', 'r', encoding='utf-8') as f:
17
+ text = f.read()
18
+
19
+ # here are all the unique characters that occur in this text
20
+ chars = sorted(list(set(text)))
21
+ vocab_size = len(chars)
22
+ # create a mapping from characters to integers
23
+ stoi = { ch:i for i,ch in enumerate(chars) }
24
+ itos = { i:ch for i,ch in enumerate(chars) }
25
+ encode = lambda s: [stoi[c] for c in s] # encoder: take a string, output a list of integers
26
+ decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string
27
+
28
+ # Train and test splits
29
+ data = torch.tensor(encode(text), dtype=torch.long)
30
+ n = int(0.9*len(data)) # first 90% will be train, rest val
31
+ train_data = data[:n]
32
+ val_data = data[n:]
33
+
34
+ # data loading
35
+ def get_batch(split):
36
+ # generate a small batch of data of inputs x and targets y
37
+ data = train_data if split == 'train' else val_data
38
+ ix = torch.randint(len(data) - block_size, (batch_size,))
39
+ x = torch.stack([data[i:i+block_size] for i in ix])
40
+ y = torch.stack([data[i+1:i+block_size+1] for i in ix])
41
+ x, y = x.to(device), y.to(device)
42
+ return x, y
43
+
44
+ @torch.no_grad()
45
+ def estimate_loss():
46
+ out = {}
47
+ model.eval()
48
+ for split in ['train', 'val']:
49
+ losses = torch.zeros(eval_iters)
50
+ for k in range(eval_iters):
51
+ X, Y = get_batch(split)
52
+ logits, loss = model(X, Y)
53
+ losses[k] = loss.item()
54
+ out[split] = losses.mean()
55
+ model.train()
56
+ return out
57
+
58
+ # super simple bigram model
59
+ class BigramLanguageModel(nn.Module):
60
+
61
+ def __init__(self, vocab_size):
62
+ super().__init__()
63
+ # each token directly reads off the logits for the next token from a lookup table
64
+ self.token_embedding_table = nn.Embedding(vocab_size, vocab_size)
65
+
66
+ def forward(self, idx, targets=None):
67
+
68
+ # idx and targets are both (B,T) tensor of integers
69
+ logits = self.token_embedding_table(idx) # (B,T,C)
70
+
71
+ if targets is None:
72
+ loss = None
73
+ else:
74
+ B, T, C = logits.shape
75
+ logits = logits.view(B*T, C)
76
+ targets = targets.view(B*T)
77
+ loss = F.cross_entropy(logits, targets)
78
+
79
+ return logits, loss
80
+
81
+ def generate(self, idx, max_new_tokens):
82
+ # idx is (B, T) array of indices in the current context
83
+ for _ in range(max_new_tokens):
84
+ # get the predictions
85
+ logits, loss = self(idx)
86
+ # focus only on the last time step
87
+ logits = logits[:, -1, :] # becomes (B, C)
88
+ # apply softmax to get probabilities
89
+ probs = F.softmax(logits, dim=-1) # (B, C)
90
+ # sample from the distribution
91
+ idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
92
+ # append sampled index to the running sequence
93
+ idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
94
+ return idx
95
+
96
+ model = BigramLanguageModel(vocab_size)
97
+ m = model.to(device)
98
+
99
+ # create a PyTorch optimizer
100
+ optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
101
+
102
+ for iter in range(max_iters):
103
+
104
+ # every once in a while evaluate the loss on train and val sets
105
+ if iter % eval_interval == 0:
106
+ losses = estimate_loss()
107
+ print(f"step {iter}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
108
+
109
+ # sample a batch of data
110
+ xb, yb = get_batch('train')
111
+
112
+ # evaluate the loss
113
+ logits, loss = model(xb, yb)
114
+ optimizer.zero_grad(set_to_none=True)
115
+ loss.backward()
116
+ optimizer.step()
117
+
118
+ # generate from the model
119
+ context = torch.zeros((1, 1), dtype=torch.long, device=device)
120
+ print(decode(m.generate(context, max_new_tokens=500)[0].tolist()))
gpt.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.nn import functional as F
4
+
5
+ # hyperparameters
6
+ batch_size = 64 # how many independent sequences will we process in parallel?
7
+ block_size = 256 # what is the maximum context length for predictions?
8
+ max_iters = 5000
9
+ eval_interval = 500
10
+ learning_rate = 3e-4
11
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
12
+ eval_iters = 200
13
+ n_embd = 384
14
+ n_head = 6
15
+ n_layer = 6
16
+ dropout = 0.2
17
+ # ------------
18
+
19
+ torch.manual_seed(1337)
20
+
21
+ with open('input.txt', 'r', encoding='utf-8') as f:
22
+ text = f.read()
23
+
24
+ # here are all the unique characters that occur in this text
25
+ chars = sorted(list(set(text)))
26
+ vocab_size = len(chars)
27
+ # create a mapping from characters to integers
28
+ stoi = { ch:i for i,ch in enumerate(chars) }
29
+ itos = { i:ch for i,ch in enumerate(chars) }
30
+ encode = lambda s: [stoi[c] for c in s] # encoder: take a string, output a list of integers
31
+ decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string
32
+
33
+ # Train and test splits
34
+ data = torch.tensor(encode(text), dtype=torch.long)
35
+ n = int(0.9*len(data)) # first 90% will be train, rest val
36
+ train_data = data[:n]
37
+ val_data = data[n:]
38
+
39
+ # data loading
40
+ def get_batch(split):
41
+ # generate a small batch of data of inputs x and targets y
42
+ data = train_data if split == 'train' else val_data
43
+ ix = torch.randint(len(data) - block_size, (batch_size,))
44
+ x = torch.stack([data[i:i+block_size] for i in ix])
45
+ y = torch.stack([data[i+1:i+block_size+1] for i in ix])
46
+ x, y = x.to(device), y.to(device)
47
+ return x, y
48
+
49
+ @torch.no_grad()
50
+ def estimate_loss():
51
+ out = {}
52
+ model.eval()
53
+ for split in ['train', 'val']:
54
+ losses = torch.zeros(eval_iters)
55
+ for k in range(eval_iters):
56
+ X, Y = get_batch(split)
57
+ logits, loss = model(X, Y)
58
+ losses[k] = loss.item()
59
+ out[split] = losses.mean()
60
+ model.train()
61
+ return out
62
+
63
+ class Head(nn.Module):
64
+ """ one head of self-attention """
65
+
66
+ def __init__(self, head_size):
67
+ super().__init__()
68
+ self.key = nn.Linear(n_embd, head_size, bias=False)
69
+ self.query = nn.Linear(n_embd, head_size, bias=False)
70
+ self.value = nn.Linear(n_embd, head_size, bias=False)
71
+ self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
72
+
73
+ self.dropout = nn.Dropout(dropout)
74
+
75
+ def forward(self, x):
76
+ # input of size (batch, time-step, channels)
77
+ # output of size (batch, time-step, head size)
78
+ B,T,C = x.shape
79
+ k = self.key(x) # (B,T,hs)
80
+ q = self.query(x) # (B,T,hs)
81
+ # compute attention scores ("affinities")
82
+ wei = q @ k.transpose(-2,-1) * k.shape[-1]**-0.5 # (B, T, hs) @ (B, hs, T) -> (B, T, T)
83
+ wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
84
+ wei = F.softmax(wei, dim=-1) # (B, T, T)
85
+ wei = self.dropout(wei)
86
+ # perform the weighted aggregation of the values
87
+ v = self.value(x) # (B,T,hs)
88
+ out = wei @ v # (B, T, T) @ (B, T, hs) -> (B, T, hs)
89
+ return out
90
+
91
+ class MultiHeadAttention(nn.Module):
92
+ """ multiple heads of self-attention in parallel """
93
+
94
+ def __init__(self, num_heads, head_size):
95
+ super().__init__()
96
+ self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
97
+ self.proj = nn.Linear(head_size * num_heads, n_embd)
98
+ self.dropout = nn.Dropout(dropout)
99
+
100
+ def forward(self, x):
101
+ out = torch.cat([h(x) for h in self.heads], dim=-1)
102
+ out = self.dropout(self.proj(out))
103
+ return out
104
+
105
+ class FeedFoward(nn.Module):
106
+ """ a simple linear layer followed by a non-linearity """
107
+
108
+ def __init__(self, n_embd):
109
+ super().__init__()
110
+ self.net = nn.Sequential(
111
+ nn.Linear(n_embd, 4 * n_embd),
112
+ nn.ReLU(),
113
+ nn.Linear(4 * n_embd, n_embd),
114
+ nn.Dropout(dropout),
115
+ )
116
+
117
+ def forward(self, x):
118
+ return self.net(x)
119
+
120
+ class Block(nn.Module):
121
+ """ Transformer block: communication followed by computation """
122
+
123
+ def __init__(self, n_embd, n_head):
124
+ # n_embd: embedding dimension, n_head: the number of heads we'd like
125
+ super().__init__()
126
+ head_size = n_embd // n_head
127
+ self.sa = MultiHeadAttention(n_head, head_size)
128
+ self.ffwd = FeedFoward(n_embd)
129
+ self.ln1 = nn.LayerNorm(n_embd)
130
+ self.ln2 = nn.LayerNorm(n_embd)
131
+
132
+ def forward(self, x):
133
+ x = x + self.sa(self.ln1(x))
134
+ x = x + self.ffwd(self.ln2(x))
135
+ return x
136
+
137
+ class GPTLanguageModel(nn.Module):
138
+
139
+ def __init__(self):
140
+ super().__init__()
141
+ # each token directly reads off the logits for the next token from a lookup table
142
+ self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
143
+ self.position_embedding_table = nn.Embedding(block_size, n_embd)
144
+ self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])
145
+ self.ln_f = nn.LayerNorm(n_embd) # final layer norm
146
+ self.lm_head = nn.Linear(n_embd, vocab_size)
147
+
148
+ # better init, not covered in the original GPT video, but important, will cover in followup video
149
+ self.apply(self._init_weights)
150
+
151
+ def _init_weights(self, module):
152
+ if isinstance(module, nn.Linear):
153
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
154
+ if module.bias is not None:
155
+ torch.nn.init.zeros_(module.bias)
156
+ elif isinstance(module, nn.Embedding):
157
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
158
+
159
+ def forward(self, idx, targets=None):
160
+ B, T = idx.shape
161
+
162
+ # idx and targets are both (B,T) tensor of integers
163
+ tok_emb = self.token_embedding_table(idx) # (B,T,C)
164
+ pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)
165
+ x = tok_emb + pos_emb # (B,T,C)
166
+ x = self.blocks(x) # (B,T,C)
167
+ x = self.ln_f(x) # (B,T,C)
168
+ logits = self.lm_head(x) # (B,T,vocab_size)
169
+
170
+ if targets is None:
171
+ loss = None
172
+ else:
173
+ B, T, C = logits.shape
174
+ logits = logits.view(B*T, C)
175
+ targets = targets.view(B*T)
176
+ loss = F.cross_entropy(logits, targets)
177
+
178
+ return logits, loss
179
+
180
+ def generate(self, idx, max_new_tokens):
181
+ # idx is (B, T) array of indices in the current context
182
+ for _ in range(max_new_tokens):
183
+ # crop idx to the last block_size tokens
184
+ idx_cond = idx[:, -block_size:]
185
+ # get the predictions
186
+ logits, loss = self(idx_cond)
187
+ # focus only on the last time step
188
+ logits = logits[:, -1, :] # becomes (B, C)
189
+ # apply softmax to get probabilities
190
+ probs = F.softmax(logits, dim=-1) # (B, C)
191
+ # sample from the distribution
192
+ idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
193
+ # append sampled index to the running sequence
194
+ idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
195
+ return idx
196
+
197
+ model = GPTLanguageModel()
198
+ m = model.to(device)
199
+ # print the number of parameters in the model
200
+ print(sum(p.numel() for p in m.parameters())/1e6, 'M parameters')
201
+
202
+ # create a PyTorch optimizer
203
+ optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
204
+
205
+ for iter in range(max_iters):
206
+
207
+ # every once in a while evaluate the loss on train and val sets
208
+ if iter % eval_interval == 0 or iter == max_iters - 1:
209
+ losses = estimate_loss()
210
+ print(f"step {iter}: train loss {losses['train']:.4f}, val loss {losses['val']:.4f}")
211
+
212
+ # sample a batch of data
213
+ xb, yb = get_batch('train')
214
+
215
+ # evaluate the loss
216
+ logits, loss = model(xb, yb)
217
+ optimizer.zero_grad(set_to_none=True)
218
+ loss.backward()
219
+ optimizer.step()
220
+
221
+ # generate from the model
222
+ context = torch.zeros((1, 1), dtype=torch.long, device=device)
223
+ print(decode(m.generate(context, max_new_tokens=500)[0].tolist()))
224
+ #open('more.txt', 'w').write(decode(m.generate(context, max_new_tokens=10000)[0].tolist()))
input.txt ADDED
The diff for this file is too large to render. See raw diff