Spaces:
Sleeping
Sleeping
Upload 3 files
Browse files- app.py +47 -0
- model.py +202 -0
- requirements.txt +4 -0
app.py
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import torch
|
3 |
+
from tiktoken import get_encoding
|
4 |
+
from model import GPT, GPTConfig # Replace with your actual model file/module
|
5 |
+
|
6 |
+
# Load the GPT-2 tokenizer
|
7 |
+
tokenizer = get_encoding("gpt2")
|
8 |
+
|
9 |
+
# Load your custom model (adjust as necessary for your model's implementation)
|
10 |
+
model_path = "model.pth" # Replace with the path to your model weights
|
11 |
+
model = GPT(GPTConfig()) # Initialize your custom model
|
12 |
+
model.load_state_dict(torch.load(model_path, map_location=torch.device("cpu")))
|
13 |
+
model.eval() # Set the model to evaluation mode
|
14 |
+
|
15 |
+
|
16 |
+
# Function to tokenize input and generate text
|
17 |
+
def generate_text(prompt, max_length=50):
|
18 |
+
# Tokenize the input
|
19 |
+
input_ids = tokenizer.encode(prompt)
|
20 |
+
input_tensor = torch.tensor([input_ids]) # Add batch dimension
|
21 |
+
|
22 |
+
# Generate text using the model
|
23 |
+
with torch.no_grad():
|
24 |
+
output_ids = model.generate(input_tensor, max_length=max_length) # Adjust if your model uses another method
|
25 |
+
|
26 |
+
# Decode the output back to text
|
27 |
+
generated_text = tokenizer.decode(output_ids[0].tolist())
|
28 |
+
return generated_text
|
29 |
+
|
30 |
+
|
31 |
+
# Gradio interface
|
32 |
+
with gr.Blocks() as demo:
|
33 |
+
gr.Markdown("# Custom Transformer Text Generation")
|
34 |
+
gr.Markdown("Provide an input text prompt, and the model will generate text based on it.")
|
35 |
+
|
36 |
+
with gr.Row():
|
37 |
+
input_text = gr.Textbox(label="Input Prompt", placeholder="Enter your text here...", lines=2)
|
38 |
+
max_len = gr.Slider(label="Max Output Length", minimum=10, maximum=100, value=50, step=5)
|
39 |
+
|
40 |
+
output_text = gr.Textbox(label="Generated Text", lines=5)
|
41 |
+
generate_button = gr.Button("Generate")
|
42 |
+
|
43 |
+
generate_button.click(generate_text, inputs=[input_text, max_len], outputs=output_text)
|
44 |
+
|
45 |
+
# Run the app
|
46 |
+
if __name__ == "__main__":
|
47 |
+
demo.launch()
|
model.py
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Solving for residual std scaling issue
|
2 |
+
import os
|
3 |
+
import math
|
4 |
+
import time
|
5 |
+
import inspect
|
6 |
+
from dataclasses import dataclass
|
7 |
+
import torch
|
8 |
+
import torch.nn as nn
|
9 |
+
from torch.nn import functional as F
|
10 |
+
|
11 |
+
|
12 |
+
class CausalSelfAttention(nn.Module):
|
13 |
+
|
14 |
+
def __init__(self, config):
|
15 |
+
super().__init__()
|
16 |
+
assert config.n_embd % config.n_head == 0
|
17 |
+
# key, query, value projections for all heads, but in a batch
|
18 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
|
19 |
+
# output projection
|
20 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
|
21 |
+
self.c_proj.NANGPT_SCALE_INIT = 1
|
22 |
+
# regularization
|
23 |
+
self.n_head = config.n_head
|
24 |
+
self.n_embd = config.n_embd
|
25 |
+
self.register_buffer("bias",
|
26 |
+
torch.tril(torch.ones(config.block_size, config.block_size)).view(1, 1, config.block_size,
|
27 |
+
config.block_size))
|
28 |
+
|
29 |
+
def forward(self, x):
|
30 |
+
B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
|
31 |
+
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
|
32 |
+
# nh is "number of heads", hs is "head size", and C (number of channels) = nh * hs
|
33 |
+
# e.g. in GPT-2 (124M), n_head=12, hs=64, so nh*hs=C=768 channels in the Transformer
|
34 |
+
qkv = self.c_attn(x)
|
35 |
+
q, k, v = qkv.split(self.n_embd, dim=2)
|
36 |
+
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
37 |
+
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
38 |
+
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
39 |
+
|
40 |
+
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
|
41 |
+
att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf'))
|
42 |
+
att = F.softmax(att, dim=-1)
|
43 |
+
y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
|
44 |
+
|
45 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
|
46 |
+
# output projection
|
47 |
+
y = self.c_proj(y)
|
48 |
+
return y
|
49 |
+
|
50 |
+
|
51 |
+
class MLP(nn.Module):
|
52 |
+
|
53 |
+
def __init__(self, config):
|
54 |
+
super().__init__()
|
55 |
+
self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
|
56 |
+
self.gelu = nn.GELU(approximate='tanh')
|
57 |
+
self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
|
58 |
+
self.c_proj.NANOGPT_SCALE_INIT = 1
|
59 |
+
|
60 |
+
def forward(self, x):
|
61 |
+
x = self.c_fc(x)
|
62 |
+
x = self.gelu(x)
|
63 |
+
x = self.c_proj(x)
|
64 |
+
return x
|
65 |
+
|
66 |
+
|
67 |
+
class Block(nn.Module):
|
68 |
+
|
69 |
+
def __init__(self, config):
|
70 |
+
super().__init__()
|
71 |
+
self.ln_1 = nn.LayerNorm(config.n_embd)
|
72 |
+
self.attn = CausalSelfAttention(config)
|
73 |
+
self.ln_2 = nn.LayerNorm(config.n_embd)
|
74 |
+
self.mlp = MLP(config)
|
75 |
+
|
76 |
+
def forward(self, x):
|
77 |
+
x = x + self.attn(self.ln_1(x))
|
78 |
+
x = x + self.mlp(self.ln_2(x))
|
79 |
+
return x
|
80 |
+
|
81 |
+
|
82 |
+
@dataclass
|
83 |
+
class GPTConfig:
|
84 |
+
block_size: int = 1024 # max sequence length
|
85 |
+
vocab_size: int = 50257 # number of tokens: 50,000 BPE merges + 256 bytes tokens + 1 <|endoftext|> token
|
86 |
+
n_layer: int = 12 # number of layers
|
87 |
+
n_head: int = 8 # number of heads
|
88 |
+
n_embd: int = 768 # embedding dimension
|
89 |
+
|
90 |
+
|
91 |
+
class GPT(nn.Module):
|
92 |
+
|
93 |
+
def __init__(self, config):
|
94 |
+
super().__init__()
|
95 |
+
self.config = config
|
96 |
+
|
97 |
+
self.transformer = nn.ModuleDict(dict(
|
98 |
+
wte=nn.Embedding(config.vocab_size, config.n_embd),
|
99 |
+
wpe=nn.Embedding(config.block_size, config.n_embd),
|
100 |
+
h=nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
|
101 |
+
ln_f=nn.LayerNorm(config.n_embd),
|
102 |
+
))
|
103 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
104 |
+
|
105 |
+
# weight sharing
|
106 |
+
self.transformer.wte.weight = self.lm_head.weight
|
107 |
+
|
108 |
+
# weight initialization
|
109 |
+
self.apply(self._init_weights)
|
110 |
+
|
111 |
+
def _init_weights(self, module):
|
112 |
+
if isinstance(module, nn.Linear):
|
113 |
+
std = 0.02
|
114 |
+
if hasattr(module, 'NANGPT_SCALE_INIT'):
|
115 |
+
std *= (2 * self.config.n_layer) ** -0.5
|
116 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=std)
|
117 |
+
if module.bias is not None:
|
118 |
+
torch.nn.init.zeros_(module.bias)
|
119 |
+
elif isinstance(module, nn.Embedding):
|
120 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
121 |
+
|
122 |
+
def forward(self, idx, targets=None):
|
123 |
+
# idx is of shape (B, T)
|
124 |
+
B, T = idx.size()
|
125 |
+
assert T <= self.config.block_size, f"Cannot forward sequence of length {T}, block size is only {self.config.block_size}"
|
126 |
+
# forward the token and posisition embeddings
|
127 |
+
pos = torch.arange(0, T, dtype=torch.long, device=idx.device) # shape (T)
|
128 |
+
pos_emb = self.transformer.wpe(pos) # position embeddings of shape (T, n_embd)
|
129 |
+
tok_emb = self.transformer.wte(idx) # token embeddings of shape (B, T, n_embd)
|
130 |
+
x = tok_emb + pos_emb
|
131 |
+
# forward the blocks of the transformer
|
132 |
+
for block in self.transformer.h:
|
133 |
+
x = block(x)
|
134 |
+
# forward the final layernorm and the classifier
|
135 |
+
x = self.transformer.ln_f(x)
|
136 |
+
logits = self.lm_head(x) # (B, T, vocab_size)
|
137 |
+
loss = None
|
138 |
+
if targets is not None:
|
139 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
|
140 |
+
return logits, loss
|
141 |
+
|
142 |
+
@classmethod
|
143 |
+
def from_pretrained(cls, model_type):
|
144 |
+
"""Loads pretrained GPT-2 model weights from huggingface"""
|
145 |
+
assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
|
146 |
+
from transformers import GPT2LMHeadModel
|
147 |
+
print("loading weights from pretrained gpt: %s" % model_type)
|
148 |
+
|
149 |
+
# n_layer, n_head and n_embd are determined from model_type
|
150 |
+
config_args = {
|
151 |
+
'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
|
152 |
+
'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
|
153 |
+
'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
|
154 |
+
'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
|
155 |
+
}[model_type]
|
156 |
+
config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
|
157 |
+
config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
|
158 |
+
# create a from-scratch initialized minGPT model
|
159 |
+
config = GPTConfig(**config_args)
|
160 |
+
model = GPT(config)
|
161 |
+
sd = model.state_dict()
|
162 |
+
sd_keys = sd.keys()
|
163 |
+
sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param
|
164 |
+
|
165 |
+
# init a huggingface/transformers model
|
166 |
+
model_hf = GPT2LMHeadModel.from_pretrained(model_type)
|
167 |
+
sd_hf = model_hf.state_dict()
|
168 |
+
|
169 |
+
# copy while ensuring all of the parameters are aligned and match in names and shapes
|
170 |
+
sd_keys_hf = sd_hf.keys()
|
171 |
+
sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
|
172 |
+
sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
|
173 |
+
transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
|
174 |
+
# basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
|
175 |
+
# this means that we have to transpose these weights when we import them
|
176 |
+
assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
|
177 |
+
for k in sd_keys_hf:
|
178 |
+
if any(k.endswith(w) for w in transposed):
|
179 |
+
# special treatment for the Conv1D weights we need to transpose
|
180 |
+
assert sd_hf[k].shape[::-1] == sd[k].shape
|
181 |
+
with torch.no_grad():
|
182 |
+
sd[k].copy_(sd_hf[k].t())
|
183 |
+
else:
|
184 |
+
# vanilla copy over the other parameters
|
185 |
+
assert sd_hf[k].shape == sd[k].shape
|
186 |
+
with torch.no_grad():
|
187 |
+
sd[k].copy_(sd_hf[k])
|
188 |
+
|
189 |
+
return model
|
190 |
+
|
191 |
+
def generate(self, input_tensor, max_length, EOS_TOKEN_ID=50256):
|
192 |
+
output_ids = input_tensor # Start with input
|
193 |
+
self.eval()
|
194 |
+
for _ in range(max_length - input_tensor.size(1)):
|
195 |
+
logits = self(input_tensor) # Forward pass
|
196 |
+
if isinstance(logits, tuple):
|
197 |
+
logits = logits[0]
|
198 |
+
next_token = torch.argmax(logits[:, -1, :], dim=-1) # Get the next token
|
199 |
+
input_tensor = torch.cat([input_tensor, next_token.unsqueeze(0)], dim=1)
|
200 |
+
if next_token.item() == EOS_TOKEN_ID: # Stop if end-of-sequence token is generated
|
201 |
+
break
|
202 |
+
return input_tensor
|
requirements.txt
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch
|
2 |
+
tiktoken
|
3 |
+
dataclasses
|
4 |
+
gradio
|