raja5259 commited on
Commit
1030703
·
verified ·
1 Parent(s): a5bb12c

Upload 3 files

Browse files
Files changed (3) hide show
  1. input.txt +0 -0
  2. s19_cpu_gradio_2.py +181 -0
  3. wt_25k.pth +3 -0
input.txt ADDED
The diff for this file is too large to render. See raw diff
 
s19_cpu_gradio_2.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """2_S19_cpu.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1laKI3fOJgsqMey3iQ5u3r8mhekJg-inM
8
+
9
+ ## Building a GPT
10
+
11
+ Companion notebook to the [Zero To Hero](https://karpathy.ai/zero-to-hero.html) video on GPT.
12
+ """
13
+ import torch
14
+ import torch.nn as nn
15
+ from torch.nn import functional as F
16
+
17
+ def GPT(txt, max_new_tokens=100):
18
+
19
+ # hyperparameters
20
+ batch_size = 16 # how many independent sequences will we process in parallel?
21
+ block_size = 32 # what is the maximum context length for predictions?
22
+ max_iters = 5000
23
+ eval_interval = 100
24
+ learning_rate = 1e-3
25
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
26
+ eval_iters = 200
27
+ n_embd = 64
28
+ n_head = 4
29
+ n_layer = 4
30
+ dropout = 0.0
31
+ # ------------
32
+
33
+ torch.manual_seed(1337)
34
+
35
+ with open('input.txt', 'r', encoding='utf-8') as f:
36
+ text = f.read()
37
+ # here are all the unique characters that occur in this text
38
+ chars = sorted(list(set(text)))
39
+ vocab_size = len(chars)
40
+ # create a mapping from characters to integers
41
+ stoi = { ch:i for i,ch in enumerate(chars) }
42
+ itos = { i:ch for i,ch in enumerate(chars) }
43
+ encode = lambda s: [stoi[c] for c in s] # encoder: take a string, output a list of integers
44
+ decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string
45
+
46
+ class Head(nn.Module):
47
+ """ one head of self-attention """
48
+
49
+ def __init__(self, head_size):
50
+ super().__init__()
51
+ self.key = nn.Linear(n_embd, head_size, bias=False)
52
+ self.query = nn.Linear(n_embd, head_size, bias=False)
53
+ self.value = nn.Linear(n_embd, head_size, bias=False)
54
+ self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
55
+
56
+ self.dropout = nn.Dropout(dropout)
57
+
58
+ def forward(self, x):
59
+ B,T,C = x.shape
60
+ k = self.key(x) # (B,T,C)
61
+ q = self.query(x) # (B,T,C)
62
+ # compute attention scores ("affinities")
63
+ wei = q @ k.transpose(-2,-1) * C**-0.5 # (B, T, C) @ (B, C, T) -> (B, T, T)
64
+ wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
65
+ wei = F.softmax(wei, dim=-1) # (B, T, T)
66
+ wei = self.dropout(wei)
67
+ # perform the weighted aggregation of the values
68
+ v = self.value(x) # (B,T,C)
69
+ out = wei @ v # (B, T, T) @ (B, T, C) -> (B, T, C)
70
+ return out
71
+
72
+ class MultiHeadAttention(nn.Module):
73
+ """ multiple heads of self-attention in parallel """
74
+
75
+ def __init__(self, num_heads, head_size):
76
+ super().__init__()
77
+ self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
78
+ self.proj = nn.Linear(n_embd, n_embd)
79
+ self.dropout = nn.Dropout(dropout)
80
+
81
+ def forward(self, x):
82
+ out = torch.cat([h(x) for h in self.heads], dim=-1)
83
+ out = self.dropout(self.proj(out))
84
+ return out
85
+
86
+ class FeedFoward(nn.Module):
87
+ """ a simple linear layer followed by a non-linearity """
88
+
89
+ def __init__(self, n_embd):
90
+ super().__init__()
91
+ self.net = nn.Sequential(
92
+ nn.Linear(n_embd, 4 * n_embd),
93
+ nn.ReLU(),
94
+ nn.Linear(4 * n_embd, n_embd),
95
+ nn.Dropout(dropout),
96
+ )
97
+
98
+ def forward(self, x):
99
+ return self.net(x)
100
+
101
+ class Block(nn.Module):
102
+ """ Transformer block: communication followed by computation """
103
+
104
+ def __init__(self, n_embd, n_head):
105
+ # n_embd: embedding dimension, n_head: the number of heads we'd like
106
+ super().__init__()
107
+ head_size = n_embd // n_head
108
+ self.sa = MultiHeadAttention(n_head, head_size)
109
+ self.ffwd = FeedFoward(n_embd)
110
+ self.ln1 = nn.LayerNorm(n_embd)
111
+ self.ln2 = nn.LayerNorm(n_embd)
112
+
113
+ def forward(self, x):
114
+ x = x + self.sa(self.ln1(x))
115
+ x = x + self.ffwd(self.ln2(x))
116
+ return x
117
+
118
+ # super simple bigram model
119
+ class BigramLanguageModel(nn.Module):
120
+
121
+ def __init__(self):
122
+ super().__init__()
123
+ # each token directly reads off the logits for the next token from a lookup table
124
+ self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
125
+ self.position_embedding_table = nn.Embedding(block_size, n_embd)
126
+ self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])
127
+ self.ln_f = nn.LayerNorm(n_embd) # final layer norm
128
+ self.lm_head = nn.Linear(n_embd, vocab_size)
129
+
130
+ def forward(self, idx, targets=None):
131
+ B, T = idx.shape
132
+
133
+ # idx and targets are both (B,T) tensor of integers
134
+ tok_emb = self.token_embedding_table(idx) # (B,T,C)
135
+ pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)
136
+ x = tok_emb + pos_emb # (B,T,C)
137
+ x = self.blocks(x) # (B,T,C)
138
+ x = self.ln_f(x) # (B,T,C)
139
+ logits = self.lm_head(x) # (B,T,vocab_size)
140
+
141
+ if targets is None:
142
+ loss = None
143
+ else:
144
+ B, T, C = logits.shape
145
+ logits = logits.view(B*T, C)
146
+ targets = targets.view(B*T)
147
+ loss = F.cross_entropy(logits, targets)
148
+
149
+ return logits, loss
150
+
151
+ def generate(self, idx, max_new_tokens):
152
+ # idx is (B, T) array of indices in the current context
153
+ for _ in range(max_new_tokens):
154
+ # crop idx to the last block_size tokens
155
+ idx_cond = idx[:, -block_size:]
156
+ # get the predictions
157
+ logits, loss = self(idx_cond)
158
+ # focus only on the last time step
159
+ logits = logits[:, -1, :] # becomes (B, C)
160
+ # apply softmax to get probabilities
161
+ probs = F.softmax(logits, dim=-1) # (B, C)
162
+ # sample from the distribution
163
+ idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
164
+ # append sampled index to the running sequence
165
+ idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
166
+ return idx
167
+
168
+ model = BigramLanguageModel()
169
+ m = model.to(device)
170
+ # print the number of parameters in the model
171
+ print(sum(p.numel() for p in m.parameters())/1e6, 'M parameters')
172
+
173
+ # create a PyTorch optimizer
174
+ optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
175
+
176
+
177
+ m.load_state_dict(torch.load('wt_25k.pth', map_location=torch.device(device)))
178
+ context = torch.tensor(encode(txt), dtype=torch.long)
179
+ context = context.reshape(1, -1)
180
+ ret_val = decode(m.generate(context, max_new_tokens=max_new_tokens)[0].tolist())
181
+ return ret_val
wt_25k.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f31a4015218f7c3c099dec1ba88aa33b926d915ecbbe82d016172515f565825e
3
+ size 938098