Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,12 +1,108 @@
|
|
1 |
-
|
|
|
2 |
import torch
|
|
|
|
|
3 |
import gradio as gr
|
4 |
-
from model import GPT, GPTConfig # Assuming your model code is in a file named model.py
|
5 |
import tiktoken
|
6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
# Load the trained model
|
8 |
def load_model(model_path):
|
9 |
-
config = GPTConfig()
|
10 |
model = GPT(config)
|
11 |
model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
|
12 |
model.eval()
|
@@ -20,8 +116,8 @@ def generate_text(prompt, max_length=100, temperature=0.7):
|
|
20 |
|
21 |
with torch.no_grad():
|
22 |
for _ in range(max_length):
|
23 |
-
outputs = model(input_ids)
|
24 |
-
next_token_logits = outputs[
|
25 |
next_token = torch.multinomial(torch.softmax(next_token_logits, dim=-1), num_samples=1)
|
26 |
input_ids = torch.cat([input_ids, next_token], dim=-1)
|
27 |
|
|
|
1 |
+
import os
|
2 |
+
import math
|
3 |
import torch
|
4 |
+
import torch.nn as nn
|
5 |
+
from torch.nn import functional as F
|
6 |
import gradio as gr
|
|
|
7 |
import tiktoken
|
8 |
|
9 |
+
# GPT model code
|
10 |
+
class GPTConfig:
|
11 |
+
def __init__(self):
|
12 |
+
self.block_size = 1024
|
13 |
+
self.vocab_size = 50304
|
14 |
+
self.n_layer = 12
|
15 |
+
self.n_head = 12
|
16 |
+
self.n_embd = 768
|
17 |
+
|
18 |
+
class CausalSelfAttention(nn.Module):
|
19 |
+
def __init__(self, config):
|
20 |
+
super().__init__()
|
21 |
+
assert config.n_embd % config.n_head == 0
|
22 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
|
23 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
|
24 |
+
self.n_head = config.n_head
|
25 |
+
self.n_embd = config.n_embd
|
26 |
+
self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size)).view(1, 1, config.block_size, config.block_size))
|
27 |
+
|
28 |
+
def forward(self, x):
|
29 |
+
B, T, C = x.size()
|
30 |
+
q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
|
31 |
+
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
|
32 |
+
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
|
33 |
+
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
|
34 |
+
y = F.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=0.0, is_causal=True)
|
35 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C)
|
36 |
+
return self.c_proj(y)
|
37 |
+
|
38 |
+
class MLP(nn.Module):
|
39 |
+
def __init__(self, config):
|
40 |
+
super().__init__()
|
41 |
+
self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
|
42 |
+
self.gelu = nn.GELU()
|
43 |
+
self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
|
44 |
+
|
45 |
+
def forward(self, x):
|
46 |
+
return self.c_proj(self.gelu(self.c_fc(x)))
|
47 |
+
|
48 |
+
class Block(nn.Module):
|
49 |
+
def __init__(self, config):
|
50 |
+
super().__init__()
|
51 |
+
self.ln_1 = nn.LayerNorm(config.n_embd)
|
52 |
+
self.attn = CausalSelfAttention(config)
|
53 |
+
self.ln_2 = nn.LayerNorm(config.n_embd)
|
54 |
+
self.mlp = MLP(config)
|
55 |
+
|
56 |
+
def forward(self, x):
|
57 |
+
x = x + self.attn(self.ln_1(x))
|
58 |
+
x = x + self.mlp(self.ln_2(x))
|
59 |
+
return x
|
60 |
+
|
61 |
+
class GPT(nn.Module):
|
62 |
+
def __init__(self, config):
|
63 |
+
super().__init__()
|
64 |
+
self.config = config
|
65 |
+
self.transformer = nn.ModuleDict(dict(
|
66 |
+
wte = nn.Embedding(config.vocab_size, config.n_embd),
|
67 |
+
wpe = nn.Embedding(config.block_size, config.n_embd),
|
68 |
+
h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
|
69 |
+
ln_f = nn.LayerNorm(config.n_embd),
|
70 |
+
))
|
71 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
72 |
+
self.transformer.wte.weight = self.lm_head.weight
|
73 |
+
self.apply(self._init_weights)
|
74 |
+
|
75 |
+
def _init_weights(self, module):
|
76 |
+
if isinstance(module, nn.Linear):
|
77 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
78 |
+
if module.bias is not None:
|
79 |
+
torch.nn.init.zeros_(module.bias)
|
80 |
+
elif isinstance(module, nn.Embedding):
|
81 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
82 |
+
|
83 |
+
def forward(self, idx, targets=None):
|
84 |
+
device = idx.device
|
85 |
+
b, t = idx.size()
|
86 |
+
assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
|
87 |
+
pos = torch.arange(0, t, dtype=torch.long, device=device).unsqueeze(0)
|
88 |
+
|
89 |
+
tok_emb = self.transformer.wte(idx)
|
90 |
+
pos_emb = self.transformer.wpe(pos)
|
91 |
+
x = tok_emb + pos_emb
|
92 |
+
for block in self.transformer.h:
|
93 |
+
x = block(x)
|
94 |
+
x = self.transformer.ln_f(x)
|
95 |
+
logits = self.lm_head(x)
|
96 |
+
|
97 |
+
loss = None
|
98 |
+
if targets is not None:
|
99 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
|
100 |
+
|
101 |
+
return logits, loss
|
102 |
+
|
103 |
# Load the trained model
|
104 |
def load_model(model_path):
|
105 |
+
config = GPTConfig()
|
106 |
model = GPT(config)
|
107 |
model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
|
108 |
model.eval()
|
|
|
116 |
|
117 |
with torch.no_grad():
|
118 |
for _ in range(max_length):
|
119 |
+
outputs, _ = model(input_ids)
|
120 |
+
next_token_logits = outputs[:, -1, :] / temperature
|
121 |
next_token = torch.multinomial(torch.softmax(next_token_logits, dim=-1), num_samples=1)
|
122 |
input_ids = torch.cat([input_ids, next_token], dim=-1)
|
123 |
|