dcrunchg commited on
Commit
758c573
·
verified ·
1 Parent(s): d838caf

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +97 -0
  2. final_model.pth +3 -0
  3. model.py +183 -0
  4. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gradio as gr
3
+ from model import GPT, GPTConfig
4
+ import tiktoken
5
+ import os
6
+
7
+ # Configuration
8
+ device = 'cpu'
9
+ if torch.cuda.is_available():
10
+ device = 'cuda'
11
+ elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
12
+ device = "mps"
13
+
14
+ print(f"Using device: {device}")
15
+
16
+ # Load Model
17
+ model_path = "final_model.pth"
18
+ if not os.path.exists(model_path):
19
+ raise FileNotFoundError(f"Model file not found: {model_path}")
20
+
21
+ # Initialize model with same config as training
22
+ config = GPTConfig()
23
+ model = GPT(config)
24
+
25
+ # Load state dict
26
+ checkpoint = torch.load(model_path, map_location=device)
27
+ # Handle if checkpoint is a full checkpoint dict or just state_dict
28
+ if 'model_state_dict' in checkpoint:
29
+ state_dict = checkpoint['model_state_dict']
30
+ else:
31
+ state_dict = checkpoint
32
+
33
+ model.load_state_dict(state_dict)
34
+ model.to(device)
35
+ model.eval()
36
+
37
+ # Tokenizer
38
+ enc = tiktoken.get_encoding('gpt2')
39
+
40
+ def generate_text(start_text, max_new_tokens=100, temperature=0.8, top_k=50):
41
+ if not start_text:
42
+ return "Please enter some text to start."
43
+
44
+ # Encode input
45
+ start_ids = enc.encode(start_text)
46
+ x = torch.tensor(start_ids, dtype=torch.long, device=device)[None, ...]
47
+
48
+ # Generate
49
+ with torch.no_grad():
50
+ for _ in range(max_new_tokens):
51
+ # Crop context if needed
52
+ idx_cond = x if x.size(1) <= config.block_size else x[:, -config.block_size:]
53
+
54
+ # Forward pass
55
+ logits, _ = model(idx_cond)
56
+ logits = logits[:, -1, :] / temperature
57
+
58
+ # Top-k sampling
59
+ if top_k is not None:
60
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
61
+ logits[logits < v[:, [-1]]] = -float('Inf')
62
+
63
+ probs = torch.nn.functional.softmax(logits, dim=-1)
64
+ idx_next = torch.multinomial(probs, num_samples=1)
65
+
66
+ x = torch.cat((x, idx_next), dim=1)
67
+
68
+ # Decode output
69
+ output_tokens = x[0].tolist()
70
+ decoded_text = enc.decode(output_tokens)
71
+ return decoded_text
72
+
73
+ # Gradio Interface
74
+ with gr.Blocks(title="GPT Text Generation") as demo:
75
+ gr.Markdown("# GPT Text Generation")
76
+ gr.Markdown("Enter some text and the model will continue it.")
77
+
78
+ with gr.Row():
79
+ with gr.Column():
80
+ input_text = gr.Textbox(label="Input Text", placeholder="Once upon a time...", lines=5)
81
+ with gr.Row():
82
+ max_tokens = gr.Slider(minimum=10, maximum=500, value=100, step=10, label="Max New Tokens")
83
+ temperature = gr.Slider(minimum=0.1, maximum=2.0, value=0.8, step=0.1, label="Temperature")
84
+ top_k = gr.Slider(minimum=1, maximum=100, value=50, step=1, label="Top-K")
85
+ generate_btn = gr.Button("Generate", variant="primary")
86
+
87
+ with gr.Column():
88
+ output_text = gr.Textbox(label="Generated Text", lines=10)
89
+
90
+ generate_btn.click(
91
+ fn=generate_text,
92
+ inputs=[input_text, max_tokens, temperature, top_k],
93
+ outputs=output_text
94
+ )
95
+
96
+ if __name__ == "__main__":
97
+ demo.launch()
final_model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:659a06d0320c90708c5897fa866f9f5bed31bf0dcb2dd61f0cb679665460b10d
3
+ size 548149399
model.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch.nn import functional as F
5
+ from dataclasses import dataclass
6
+
7
+ class CausalSelfAttention(nn.Module):
8
+
9
+ def __init__(self, config):
10
+ super().__init__()
11
+ assert config.n_embd % config.n_head == 0
12
+ # key, query, value projections for all heads, but in a batch
13
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
14
+ # output projection
15
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
16
+ self.c_proj.NANGPT_SCALE_INIT = 1
17
+ # regularization
18
+ self.n_head = config.n_head
19
+ self.n_embd = config.n_embd
20
+ self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size)).view(1, 1, config.block_size, config.block_size))
21
+
22
+ def forward(self, x):
23
+ B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
24
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
25
+ # nh is "number of heads", hs is "head size", and C (number of channels) = nh * hs
26
+ # e.g. in GPT-2 (124M), n_head=12, hs=64, so nh*hs=C=768 channels in the Transformer
27
+ qkv = self.c_attn(x)
28
+ q, k, v = qkv.split(self.n_embd, dim=2)
29
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
30
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
31
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
32
+
33
+ att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
34
+ att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf'))
35
+ att = F.softmax(att, dim=-1)
36
+ y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
37
+
38
+ y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
39
+ # output projection
40
+ y = self.c_proj(y)
41
+ return y
42
+
43
+
44
+ class MLP(nn.Module):
45
+
46
+ def __init__(self, config):
47
+ super().__init__()
48
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
49
+ self.gelu = nn.GELU(approximate='tanh')
50
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
51
+ self.c_proj.NANOGPT_SCALE_INIT = 1
52
+
53
+ def forward(self, x):
54
+ x = self.c_fc(x)
55
+ x = self.gelu(x)
56
+ x = self.c_proj(x)
57
+ return x
58
+
59
+ class Block(nn.Module):
60
+
61
+ def __init__(self, config):
62
+ super().__init__()
63
+ self.ln_1 = nn.LayerNorm(config.n_embd)
64
+ self.attn = CausalSelfAttention(config)
65
+ self.ln_2 = nn.LayerNorm(config.n_embd)
66
+ self.mlp = MLP(config)
67
+
68
+ def forward(self, x):
69
+ x = x + self.attn(self.ln_1(x))
70
+ x = x + self.mlp(self.ln_2(x))
71
+ return x
72
+
73
+
74
+ @dataclass
75
+ class GPTConfig:
76
+ block_size: int = 1024 # max sequence length
77
+ vocab_size: int = 50257 # number of tokens: 50,000 BPE merges + 256 bytes tokens + 1 <|endoftext|> token
78
+ n_layer: int = 12 # number of layers
79
+ n_head: int = 12 # number of heads
80
+ n_embd: int = 768 # embedding dimension
81
+
82
+
83
+ class GPT(nn.Module):
84
+
85
+ def __init__(self, config):
86
+ super().__init__()
87
+ self.config = config
88
+
89
+ self.transformer = nn.ModuleDict(dict(
90
+ wte = nn.Embedding(config.vocab_size, config.n_embd),
91
+ wpe = nn.Embedding(config.block_size, config.n_embd),
92
+ h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
93
+ ln_f = nn.LayerNorm(config.n_embd),
94
+ ))
95
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
96
+
97
+ # weight sharing
98
+ self.transformer.wte.weight = self.lm_head.weight
99
+
100
+ # weight initialization
101
+ self.apply(self._init_weights)
102
+
103
+ def _init_weights(self, module):
104
+ if isinstance(module, nn.Linear):
105
+ std = 0.02
106
+ if hasattr(module, 'NANGPT_SCALE_INIT'):
107
+ std *= (2 * self.config.n_layer) ** -0.5
108
+ torch.nn.init.normal_(module.weight, mean = 0.0, std = std)
109
+ if module.bias is not None:
110
+ torch.nn.init.zeros_(module.bias)
111
+ elif isinstance(module, nn.Embedding):
112
+ torch.nn.init.normal_(module.weight, mean=0.0, std = 0.02)
113
+
114
+
115
+
116
+ def forward(self, idx, targets=None):
117
+ # idx is of shape (B, T)
118
+ B, T = idx.size()
119
+ assert T <= self.config.block_size, f"Cannot forward sequence of length {T}, block size is only {self.config.block_size}"
120
+ # forward the token and posisition embeddings
121
+ pos = torch.arange(0, T, dtype=torch.long, device=idx.device) # shape (T)
122
+ pos_emb = self.transformer.wpe(pos) # position embeddings of shape (T, n_embd)
123
+ tok_emb = self.transformer.wte(idx) # token embeddings of shape (B, T, n_embd)
124
+ x = tok_emb + pos_emb
125
+ # forward the blocks of the transformer
126
+ for block in self.transformer.h:
127
+ x = block(x)
128
+ # forward the final layernorm and the classifier
129
+ x = self.transformer.ln_f(x)
130
+ logits = self.lm_head(x) # (B, T, vocab_size)
131
+ loss = None
132
+ if targets is not None:
133
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
134
+ return logits, loss
135
+
136
+ @classmethod
137
+ def from_pretrained(cls, model_type):
138
+ """Loads pretrained GPT-2 model weights from huggingface"""
139
+ assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
140
+ from transformers import GPT2LMHeadModel
141
+ print("loading weights from pretrained gpt: %s" % model_type)
142
+
143
+ # n_layer, n_head and n_embd are determined from model_type
144
+ config_args = {
145
+ 'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
146
+ 'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
147
+ 'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
148
+ 'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
149
+ }[model_type]
150
+ config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
151
+ config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
152
+ # create a from-scratch initialized minGPT model
153
+ config = GPTConfig(**config_args)
154
+ model = GPT(config)
155
+ sd = model.state_dict()
156
+ sd_keys = sd.keys()
157
+ sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param
158
+
159
+ # init a huggingface/transformers model
160
+ model_hf = GPT2LMHeadModel.from_pretrained(model_type)
161
+ sd_hf = model_hf.state_dict()
162
+
163
+ # copy while ensuring all of the parameters are aligned and match in names and shapes
164
+ sd_keys_hf = sd_hf.keys()
165
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
166
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
167
+ transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
168
+ # basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
169
+ # this means that we have to transpose these weights when we import them
170
+ assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
171
+ for k in sd_keys_hf:
172
+ if any(k.endswith(w) for w in transposed):
173
+ # special treatment for the Conv1D weights we need to transpose
174
+ assert sd_hf[k].shape[::-1] == sd[k].shape
175
+ with torch.no_grad():
176
+ sd[k].copy_(sd_hf[k].t())
177
+ else:
178
+ # vanilla copy over the other parameters
179
+ assert sd_hf[k].shape == sd[k].shape
180
+ with torch.no_grad():
181
+ sd[k].copy_(sd_hf[k])
182
+
183
+ return model
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ torch
2
+ tiktoken
3
+ gradio
4
+ transformers