huang342 commited on
Commit
5ba915e
·
verified ·
1 Parent(s): a06ac01

Update app.py

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