v1peridae commited on
Commit
36ba552
1 Parent(s): 60374f1

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +184 -0
  2. dataset.txt +0 -0
  3. requirements.txt +3 -0
  4. state.skibidi +0 -0
app.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # imports
2
+ import gradio as gr
3
+ import torch
4
+ import torch.nn as nn
5
+ from torch.nn import functional as F
6
+ print("done importing packages...")
7
+
8
+ with open('dataset.txt', 'r') as f:
9
+ text = f.read()
10
+
11
+ # hyperparms
12
+ batch_size = 16
13
+ block_size = 32
14
+ max_iters = 5000
15
+ eval_interval = 100
16
+ learning_rate = 0.001
17
+ eval_iters = 200
18
+ n_embd = 64
19
+ n_head = 4
20
+ n_layer = 4
21
+ dropout = 0.0
22
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
23
+ torch.manual_seed(1337)
24
+ print("big brain stuff! setting up hyperparams")
25
+
26
+ #chars and mapping
27
+ chars = sorted(list(set(text)))
28
+ vocab_size = len(chars)
29
+ stoi = { ch:i for i,ch in enumerate(chars) }
30
+ itos = { i:ch for i,ch in enumerate(chars) }
31
+ encode = lambda s: [stoi[c] for c in s]
32
+ decode = lambda l: ''.join([itos[i] for i in l])
33
+ print("making human language understandable for my computer brain")
34
+
35
+ # training and test data split
36
+ data = torch.tensor(encode(text), dtype=torch.long)
37
+ n = int(0.9*len(data))
38
+ train_data = data[:n]
39
+ val_data = data[n:]
40
+
41
+ # data loading
42
+ def get_batch(split):
43
+ data = train_data if split == 'train' else val_data
44
+ ix = torch.randint(len(data) - block_size, (batch_size,))
45
+ x = torch.stack([data[i:i+block_size] for i in ix])
46
+ y = torch.stack([data[i+1:i+block_size+1] for i in ix])
47
+ x, y = x.to(device), y.to(device)
48
+ return x, y
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
+ def __init__(self, head_size):
65
+ super().__init__()
66
+ self.key = nn.Linear(n_embd, head_size, bias=False)
67
+ self.query = nn.Linear(n_embd, head_size, bias=False)
68
+ self.value = nn.Linear(n_embd, head_size, bias=False)
69
+ self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
70
+ self.dropout = nn.Dropout(dropout)
71
+
72
+ def forward(self, x):
73
+ B,T,C = x.shape
74
+ k = self.key(x)
75
+ q = self.query(x)
76
+ wei = q @ k.transpose(-2,-1) * C**-0.5
77
+ wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf'))
78
+ wei = F.softmax(wei, dim=-1)
79
+ wei = self.dropout(wei)
80
+ v = self.value(x)
81
+ out = wei @ v
82
+ return out
83
+
84
+ class MultiHeadAttention(nn.Module):
85
+ def __init__(self, num_heads, head_size):
86
+ super().__init__()
87
+ self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
88
+ self.proj = nn.Linear(n_embd, n_embd)
89
+ self.dropout = nn.Dropout(dropout)
90
+
91
+ def forward(self, x):
92
+ out = torch.cat([h(x) for h in self.heads], dim=-1)
93
+ out = self.dropout(self.proj(out))
94
+ return out
95
+
96
+ class FeedFoward(nn.Module):
97
+ def __init__(self, n_embd):
98
+ super().__init__()
99
+ self.net = nn.Sequential(
100
+ nn.Linear(n_embd, 4 * n_embd),
101
+ nn.ReLU(),
102
+ nn.Linear(4 * n_embd, n_embd),
103
+ nn.Dropout(dropout),
104
+ )
105
+
106
+ def forward(self, x):
107
+ return self.net(x)
108
+
109
+ class Block(nn.Module):
110
+ def __init__(self, n_embd, n_head):
111
+ super().__init__()
112
+ head_size = n_embd // n_head
113
+ self.sa = MultiHeadAttention(n_head, head_size)
114
+ self.ffwd = FeedFoward(n_embd)
115
+ self.ln1 = nn.LayerNorm(n_embd)
116
+ self.ln2 = nn.LayerNorm(n_embd)
117
+
118
+ def forward(self, x):
119
+ x = x + self.sa(self.ln1(x))
120
+ x = x + self.ffwd(self.ln2(x))
121
+ return x
122
+
123
+ # bigram model
124
+ class BigramLanguageModel(nn.Module):
125
+ def __init__(self):
126
+ super().__init__()
127
+ self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
128
+ self.position_embedding_table = nn.Embedding(block_size, n_embd)
129
+ self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])
130
+ self.ln_f = nn.LayerNorm(n_embd)
131
+ self.lm_head = nn.Linear(n_embd, vocab_size)
132
+
133
+ def forward(self, idx, targets=None):
134
+ B, T = idx.shape
135
+ tok_emb = self.token_embedding_table(idx)
136
+ pos_emb = self.position_embedding_table(torch.arange(T, device=device))
137
+ x = tok_emb + pos_emb
138
+ x = self.blocks(x)
139
+ x = self.ln_f(x)
140
+ logits = self.lm_head(x)
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
+ return logits, loss
149
+
150
+ def generate(self, idx, max_new_tokens):
151
+ for _ in range(max_new_tokens):
152
+ idx_cond = idx[:, -block_size:]
153
+ logits, loss = self(idx_cond)
154
+ logits = logits[:, -1, :]
155
+ probs = F.softmax(logits, dim=-1)
156
+ idx_next = torch.multinomial(probs, num_samples=1)
157
+ idx = torch.cat((idx, idx_next), dim=1)
158
+ return idx
159
+
160
+ model = BigramLanguageModel()
161
+ model.load_state_dict(torch.load("state.skibidi",map_location = torch.device(device)))
162
+ m = model.to(device)
163
+
164
+ def generate_text(input_word, max_new_tokens=100):
165
+ model.eval()
166
+ input_indices = torch.tensor([encode(input_word)], dtype=torch.long, device=device)
167
+ generated_indices = model.generate(input_indices, max_new_tokens=max_new_tokens)
168
+ return decode(generated_indices[0].tolist())
169
+
170
+ iface = gr.Interface(
171
+ fn=generate_text,
172
+ inputs=[
173
+ gr.Textbox(label="Prompt", placeholder="W Sigma GPT according to critics"),
174
+ gr.Slider(minimum=1, maximum=1000, step=1, label="Number of characters to generate", value=100)
175
+ ],
176
+ outputs=gr.Textbox(label="Generated Text"),
177
+ title="RizzlerGPT",
178
+ description="Best GPT in Ohio"
179
+ )
180
+
181
+ if __name__ == "__main__":
182
+ iface.launch()
183
+
184
+ print("running!")
dataset.txt ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ huggingface_hub==0.22.2
2
+ gradio
3
+ torch == 2.4.0
state.skibidi ADDED
Binary file (943 kB). View file