Spaces:
Sleeping
Sleeping
load model
Browse files- gpt_load.py +73 -0
- gpt_parts.py +132 -0
gpt_load.py
ADDED
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import gradio as gr
|
3 |
+
import tiktoken # Import tiktoken for GPT-2 tokenization
|
4 |
+
from gpt_parts import GPTModel # Ensure gpt_parts.py contains your GPTModel definition
|
5 |
+
|
6 |
+
# Configuration for GPT-2 model, same as used during training
|
7 |
+
GPT_CONFIG_124M = {
|
8 |
+
"vocab_size": 50257, # Vocabulary size
|
9 |
+
"context_length": 1024, # Context length
|
10 |
+
"emb_dim": 768, # Embedding dimension
|
11 |
+
"n_heads": 12, # Number of attention heads
|
12 |
+
"n_layers": 12, # Number of layers
|
13 |
+
"drop_rate": 0.1, # Dropout rate
|
14 |
+
"qkv_bias": False # Query-Key-Value bias
|
15 |
+
}
|
16 |
+
|
17 |
+
# Initialize the tokenizer using tiktoken's GPT-2 encoding
|
18 |
+
tokenizer = tiktoken.get_encoding("gpt2")
|
19 |
+
|
20 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
21 |
+
model = GPTModel(GPT_CONFIG_124M).to(device)
|
22 |
+
model.load_state_dict(torch.load("model.pth", map_location=device, weights_only=True))
|
23 |
+
model.eval() # Set model to evaluation mode
|
24 |
+
|
25 |
+
def text_to_token_ids(text, tokenizer):
|
26 |
+
"""Encode text to token IDs."""
|
27 |
+
encoded = tokenizer.encode(text)
|
28 |
+
return torch.tensor(encoded).unsqueeze(0)
|
29 |
+
|
30 |
+
def token_ids_to_text(token_ids, tokenizer):
|
31 |
+
"""Decode token IDs to text."""
|
32 |
+
return tokenizer.decode(token_ids.squeeze(0).tolist())
|
33 |
+
|
34 |
+
def generate_text_simple(model, idx, max_new_tokens, context_size):
|
35 |
+
"""Autoregressively generate new tokens."""
|
36 |
+
for _ in range(max_new_tokens):
|
37 |
+
idx_cond = idx[:, -context_size:]
|
38 |
+
with torch.no_grad():
|
39 |
+
logits = model(idx_cond)
|
40 |
+
logits = logits[:, -1, :]
|
41 |
+
idx_next = torch.argmax(logits, dim=-1, keepdim=True)
|
42 |
+
idx = torch.cat((idx, idx_next), dim=1)
|
43 |
+
return idx
|
44 |
+
|
45 |
+
# Define text generation function for Gradio
|
46 |
+
def generate_text(start_context, max_new_tokens=50):
|
47 |
+
# Encode the starting context
|
48 |
+
encoded_input = text_to_token_ids(start_context, tokenizer).to(device)
|
49 |
+
|
50 |
+
# Generate text
|
51 |
+
generated_token_ids = generate_text_simple(
|
52 |
+
model=model,
|
53 |
+
idx=encoded_input,
|
54 |
+
max_new_tokens=max_new_tokens,
|
55 |
+
context_size=GPT_CONFIG_124M["context_length"]
|
56 |
+
)
|
57 |
+
|
58 |
+
# Decode the generated tokens to text
|
59 |
+
generated_text = token_ids_to_text(generated_token_ids, tokenizer)
|
60 |
+
return generated_text.replace("\n", " ")
|
61 |
+
|
62 |
+
iface = gr.Interface(
|
63 |
+
fn=generate_text,
|
64 |
+
inputs=[
|
65 |
+
gr.Textbox(lines=2, placeholder="Enter starting text here...", label="Start Context"),
|
66 |
+
gr.Slider(minimum=1, maximum=100, step=1, label="Max New Tokens")
|
67 |
+
],
|
68 |
+
outputs="text",
|
69 |
+
title="GPT-2 Text Generation",
|
70 |
+
description="Generate text using a fine-tuned GPT-2 model. Enter some starting text, and choose the maximum number of tokens to generate."
|
71 |
+
)
|
72 |
+
iface.launch(share=True)
|
73 |
+
|
gpt_parts.py
ADDED
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
|
4 |
+
class MultiHeadAttention(nn.Module):
|
5 |
+
def __init__(self, d_in, d_out, context_length, dropout, num_heads, qkv_bias=False):
|
6 |
+
super().__init__()
|
7 |
+
assert d_out % num_heads == 0, "d_out must be divisible by n_heads"
|
8 |
+
|
9 |
+
self.d_out = d_out
|
10 |
+
self.num_heads = num_heads
|
11 |
+
self.head_dim = d_out // num_heads
|
12 |
+
|
13 |
+
self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias)
|
14 |
+
self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias)
|
15 |
+
self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias)
|
16 |
+
self.out_proj = nn.Linear(d_out, d_out)
|
17 |
+
self.dropout = nn.Dropout(dropout)
|
18 |
+
self.register_buffer('mask', torch.triu(torch.ones(context_length, context_length), diagonal=1))
|
19 |
+
|
20 |
+
def forward(self, x):
|
21 |
+
b, num_tokens, d_in = x.shape
|
22 |
+
|
23 |
+
keys = self.W_key(x)
|
24 |
+
queries = self.W_query(x)
|
25 |
+
values = self.W_value(x)
|
26 |
+
keys = keys.view(b, num_tokens, self.num_heads, self.head_dim)
|
27 |
+
values = values.view(b, num_tokens, self.num_heads, self.head_dim)
|
28 |
+
queries = queries.view(b, num_tokens, self.num_heads, self.head_dim)
|
29 |
+
keys = keys.transpose(1, 2)
|
30 |
+
queries = queries.transpose(1, 2)
|
31 |
+
values = values.transpose(1, 2)
|
32 |
+
attn_scores = queries @ keys.transpose(2, 3)
|
33 |
+
mask_bool = self.mask.bool()[:num_tokens, :num_tokens]
|
34 |
+
attn_scores.masked_fill_(mask_bool, -torch.inf)
|
35 |
+
attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
|
36 |
+
attn_weights = self.dropout(attn_weights)
|
37 |
+
context_vec = (attn_weights @ values).transpose(1, 2)
|
38 |
+
context_vec = context_vec.reshape(b, num_tokens, self.d_out)
|
39 |
+
context_vec = self.out_proj(context_vec)
|
40 |
+
return context_vec
|
41 |
+
|
42 |
+
class LayerNorm(nn.Module):
|
43 |
+
def __init__(self, emb_dim):
|
44 |
+
super().__init__()
|
45 |
+
self.eps = 1e-5
|
46 |
+
self.scale = nn.Parameter(torch.ones(emb_dim))
|
47 |
+
self.shift = nn.Parameter(torch.zeros(emb_dim))
|
48 |
+
|
49 |
+
def forward(self, x):
|
50 |
+
mean = x.mean(dim=-1, keepdim=True)
|
51 |
+
var = x.var(dim=-1, keepdim=True, unbiased=False)
|
52 |
+
norm_x = (x - mean) / torch.sqrt(var + self.eps)
|
53 |
+
return self.scale * norm_x + self.shift
|
54 |
+
|
55 |
+
|
56 |
+
class GELU(nn.Module):
|
57 |
+
def __init__(self):
|
58 |
+
super().__init__()
|
59 |
+
|
60 |
+
def forward(self, x):
|
61 |
+
return 0.5 * x * (1 + torch.tanh(
|
62 |
+
torch.sqrt(torch.tensor(2.0 / torch.pi)) *
|
63 |
+
(x + 0.044715 * torch.pow(x, 3))
|
64 |
+
))
|
65 |
+
|
66 |
+
|
67 |
+
class FeedForward(nn.Module):
|
68 |
+
def __init__(self, cfg):
|
69 |
+
super().__init__()
|
70 |
+
self.layers = nn.Sequential(
|
71 |
+
nn.Linear(cfg["emb_dim"], 4 * cfg["emb_dim"]),
|
72 |
+
GELU(),
|
73 |
+
nn.Linear(4 * cfg["emb_dim"], cfg["emb_dim"]),
|
74 |
+
)
|
75 |
+
|
76 |
+
def forward(self, x):
|
77 |
+
return self.layers(x)
|
78 |
+
|
79 |
+
class TransformerBlock(nn.Module):
|
80 |
+
def __init__(self, cfg):
|
81 |
+
super().__init__()
|
82 |
+
self.att = MultiHeadAttention(
|
83 |
+
d_in=cfg["emb_dim"],
|
84 |
+
d_out=cfg["emb_dim"],
|
85 |
+
context_length=cfg["context_length"],
|
86 |
+
num_heads=cfg["n_heads"],
|
87 |
+
dropout=cfg["drop_rate"],
|
88 |
+
qkv_bias=cfg["qkv_bias"])
|
89 |
+
self.ff = FeedForward(cfg)
|
90 |
+
self.norm1 = LayerNorm(cfg["emb_dim"])
|
91 |
+
self.norm2 = LayerNorm(cfg["emb_dim"])
|
92 |
+
self.drop_shortcut = nn.Dropout(cfg["drop_rate"])
|
93 |
+
|
94 |
+
def forward(self, x):
|
95 |
+
shortcut = x
|
96 |
+
x = self.norm1(x)
|
97 |
+
x = self.att(x)
|
98 |
+
x = self.drop_shortcut(x)
|
99 |
+
x = x + shortcut
|
100 |
+
|
101 |
+
shortcut = x
|
102 |
+
x = self.norm2(x)
|
103 |
+
x = self.ff(x)
|
104 |
+
x = self.drop_shortcut(x)
|
105 |
+
x = x + shortcut
|
106 |
+
|
107 |
+
return x
|
108 |
+
|
109 |
+
|
110 |
+
class GPTModel(nn.Module):
|
111 |
+
def __init__(self, cfg):
|
112 |
+
super().__init__()
|
113 |
+
self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"])
|
114 |
+
self.pos_emb = nn.Embedding(cfg["context_length"], cfg["emb_dim"])
|
115 |
+
self.drop_emb = nn.Dropout(cfg["drop_rate"])
|
116 |
+
|
117 |
+
self.trf_blocks = nn.Sequential(
|
118 |
+
*[TransformerBlock(cfg) for _ in range(cfg["n_layers"])])
|
119 |
+
|
120 |
+
self.final_norm = LayerNorm(cfg["emb_dim"])
|
121 |
+
self.out_head = nn.Linear(cfg["emb_dim"], cfg["vocab_size"], bias=False)
|
122 |
+
|
123 |
+
def forward(self, in_idx):
|
124 |
+
batch_size, seq_len = in_idx.shape
|
125 |
+
tok_embeds = self.tok_emb(in_idx)
|
126 |
+
pos_embeds = self.pos_emb(torch.arange(seq_len, device=in_idx.device))
|
127 |
+
x = tok_embeds + pos_embeds
|
128 |
+
x = self.drop_emb(x)
|
129 |
+
x = self.trf_blocks(x)
|
130 |
+
x = self.final_norm(x)
|
131 |
+
logits = self.out_head(x)
|
132 |
+
return logits
|