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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import llm
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
from torch.nn import functional as F
|
5 |
+
import math
|
6 |
+
from dataclasses import dataclass
|
7 |
+
import pickle
|
8 |
+
|
9 |
+
import os
|
10 |
+
|
11 |
+
@llm.hookimpl
|
12 |
+
def register_models(register):
|
13 |
+
register(CharGPT())
|
14 |
+
|
15 |
+
# @torch.jit.script # good to enable when not using torch.compile, disable when using (our default)
|
16 |
+
def new_gelu(x):
|
17 |
+
"""
|
18 |
+
Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT).
|
19 |
+
Reference: Gaussian Error Linear Units (GELU) paper: https://arxiv.org/abs/1606.08415
|
20 |
+
"""
|
21 |
+
return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0))))
|
22 |
+
|
23 |
+
class LayerNorm(nn.Module):
|
24 |
+
""" LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False """
|
25 |
+
|
26 |
+
def __init__(self, ndim, bias):
|
27 |
+
super().__init__()
|
28 |
+
self.weight = nn.Parameter(torch.ones(ndim))
|
29 |
+
self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None
|
30 |
+
|
31 |
+
def forward(self, input):
|
32 |
+
return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5)
|
33 |
+
|
34 |
+
|
35 |
+
class CausalSelfAttention(nn.Module):
|
36 |
+
|
37 |
+
def __init__(self, config):
|
38 |
+
super().__init__()
|
39 |
+
assert config.n_embd % config.n_head == 0
|
40 |
+
# key, query, value projections for all heads, but in a batch
|
41 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
|
42 |
+
# output projection
|
43 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
|
44 |
+
# regularization
|
45 |
+
self.attn_dropout = nn.Dropout(config.dropout)
|
46 |
+
self.resid_dropout = nn.Dropout(config.dropout)
|
47 |
+
self.n_head = config.n_head
|
48 |
+
self.n_embd = config.n_embd
|
49 |
+
self.dropout = config.dropout
|
50 |
+
# flash attention make GPU go brrrrr but support is only in PyTorch nightly and still a bit scary
|
51 |
+
self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') and self.dropout == 0.0
|
52 |
+
if not self.flash:
|
53 |
+
# print("WARNING: using slow attention. Flash Attention atm needs PyTorch nightly and dropout=0.0")
|
54 |
+
# causal mask to ensure that attention is only applied to the left in the input sequence
|
55 |
+
self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
|
56 |
+
.view(1, 1, config.block_size, config.block_size))
|
57 |
+
|
58 |
+
def forward(self, x):
|
59 |
+
B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
|
60 |
+
|
61 |
+
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
|
62 |
+
q, k ,v = self.c_attn(x).split(self.n_embd, dim=2)
|
63 |
+
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
64 |
+
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
65 |
+
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
66 |
+
|
67 |
+
# causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
|
68 |
+
if self.flash:
|
69 |
+
# efficient attention using Flash Attention CUDA kernels
|
70 |
+
y = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=self.dropout, is_causal=True)
|
71 |
+
else:
|
72 |
+
# manual implementation of attention
|
73 |
+
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
|
74 |
+
att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float('-inf'))
|
75 |
+
att = F.softmax(att, dim=-1)
|
76 |
+
att = self.attn_dropout(att)
|
77 |
+
y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
|
78 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
|
79 |
+
|
80 |
+
# output projection
|
81 |
+
y = self.resid_dropout(self.c_proj(y))
|
82 |
+
return y
|
83 |
+
|
84 |
+
class MLP(nn.Module):
|
85 |
+
|
86 |
+
def __init__(self, config):
|
87 |
+
super().__init__()
|
88 |
+
self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)
|
89 |
+
self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)
|
90 |
+
self.dropout = nn.Dropout(config.dropout)
|
91 |
+
|
92 |
+
def forward(self, x):
|
93 |
+
x = self.c_fc(x)
|
94 |
+
x = new_gelu(x)
|
95 |
+
x = self.c_proj(x)
|
96 |
+
x = self.dropout(x)
|
97 |
+
return x
|
98 |
+
|
99 |
+
class Block(nn.Module):
|
100 |
+
|
101 |
+
def __init__(self, config):
|
102 |
+
super().__init__()
|
103 |
+
self.ln_1 = LayerNorm(config.n_embd, bias=config.bias)
|
104 |
+
self.attn = CausalSelfAttention(config)
|
105 |
+
self.ln_2 = LayerNorm(config.n_embd, bias=config.bias)
|
106 |
+
self.mlp = MLP(config)
|
107 |
+
|
108 |
+
def forward(self, x):
|
109 |
+
x = x + self.attn(self.ln_1(x))
|
110 |
+
x = x + self.mlp(self.ln_2(x))
|
111 |
+
return x
|
112 |
+
|
113 |
+
@dataclass
|
114 |
+
class GPTConfig:
|
115 |
+
block_size: int = 2048
|
116 |
+
vocab_size: int = 50304 # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency
|
117 |
+
n_layer: int = 12
|
118 |
+
n_head: int = 12
|
119 |
+
n_embd: int = 768
|
120 |
+
dropout: float = 0.0
|
121 |
+
bias: bool = True # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster
|
122 |
+
|
123 |
+
class GPT(nn.Module):
|
124 |
+
|
125 |
+
def __init__(self, config):
|
126 |
+
super().__init__()
|
127 |
+
assert config.vocab_size is not None
|
128 |
+
assert config.block_size is not None
|
129 |
+
self.config = config
|
130 |
+
|
131 |
+
self.transformer = nn.ModuleDict(dict(
|
132 |
+
wte = nn.Embedding(config.vocab_size, config.n_embd),
|
133 |
+
wpe = nn.Embedding(config.block_size, config.n_embd),
|
134 |
+
drop = nn.Dropout(config.dropout),
|
135 |
+
h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
|
136 |
+
ln_f = LayerNorm(config.n_embd, bias=config.bias),
|
137 |
+
))
|
138 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
139 |
+
# with weight tying when using torch.compile() some warnings get generated:
|
140 |
+
# "UserWarning: functional_call was passed multiple values for tied weights.
|
141 |
+
# This behavior is deprecated and will be an error in future versions"
|
142 |
+
# not 100% sure what this is, so far seems to be harmless. TODO investigate
|
143 |
+
self.transformer.wte.weight = self.lm_head.weight # https://paperswithcode.com/method/weight-tying
|
144 |
+
|
145 |
+
# init all weights
|
146 |
+
self.apply(self._init_weights)
|
147 |
+
# apply special scaled init to the residual projections, per GPT-2 paper
|
148 |
+
for pn, p in self.named_parameters():
|
149 |
+
if pn.endswith('c_proj.weight'):
|
150 |
+
torch.nn.init.normal_(p, mean=0.0, std=0.02/math.sqrt(2 * config.n_layer))
|
151 |
+
|
152 |
+
# report number of parameters
|
153 |
+
print("number of parameters: %.2fM" % (self.get_num_params()/1e6,))
|
154 |
+
|
155 |
+
def get_num_params(self, non_embedding=True):
|
156 |
+
"""
|
157 |
+
Return the number of parameters in the model.
|
158 |
+
For non-embedding count (default), the position embeddings get subtracted.
|
159 |
+
The token embeddings would too, except due to the parameter sharing these
|
160 |
+
params are actually used as weights in the final layer, so we include them.
|
161 |
+
"""
|
162 |
+
n_params = sum(p.numel() for p in self.parameters())
|
163 |
+
if non_embedding:
|
164 |
+
n_params -= self.transformer.wpe.weight.numel()
|
165 |
+
return n_params
|
166 |
+
|
167 |
+
def reset_parameters(self):
|
168 |
+
# Initialize weights using Glorot initialization
|
169 |
+
for param in self.parameters():
|
170 |
+
if param.dim() > 1:
|
171 |
+
torch.nn.init.xavier_uniform_(param)
|
172 |
+
|
173 |
+
def _init_weights(self, module):
|
174 |
+
if isinstance(module, nn.Linear):
|
175 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
176 |
+
if module.bias is not None:
|
177 |
+
torch.nn.init.zeros_(module.bias)
|
178 |
+
elif isinstance(module, nn.Embedding):
|
179 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
180 |
+
|
181 |
+
def forward(self, idx, targets=None):
|
182 |
+
device = idx.device
|
183 |
+
b, t = idx.size()
|
184 |
+
assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
|
185 |
+
pos = torch.arange(0, t, dtype=torch.long, device=device).unsqueeze(0) # shape (1, t)
|
186 |
+
|
187 |
+
# forward the GPT model itself
|
188 |
+
tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
|
189 |
+
pos_emb = self.transformer.wpe(pos) # position embeddings of shape (1, t, n_embd)
|
190 |
+
x = self.transformer.drop(tok_emb + pos_emb)
|
191 |
+
for block in self.transformer.h:
|
192 |
+
x = block(x)
|
193 |
+
x = self.transformer.ln_f(x)
|
194 |
+
|
195 |
+
if targets is not None:
|
196 |
+
# if we are given some desired targets also calculate the loss
|
197 |
+
logits = self.lm_head(x)
|
198 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
|
199 |
+
else:
|
200 |
+
# inference-time mini-optimization: only forward the lm_head on the very last position
|
201 |
+
logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim
|
202 |
+
loss = None
|
203 |
+
|
204 |
+
return logits, loss
|
205 |
+
|
206 |
+
|
207 |
+
@torch.no_grad()
|
208 |
+
def generate_streaming(self, idx, max_new_tokens, temperature=1.0, top_k=None):
|
209 |
+
"""
|
210 |
+
Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete
|
211 |
+
the sequence max_new_tokens times, feeding the predictions back into the model each time.
|
212 |
+
Yield the generated indices one at a time rather than concatenating them into a single tensor.
|
213 |
+
Most likely you'll want to make sure to be in model.eval() mode of operation for this.
|
214 |
+
"""
|
215 |
+
max_idx_length = self.config.block_size
|
216 |
+
for _ in range(max_new_tokens):
|
217 |
+
# if the sequence context is growing too long we must crop it at block_size
|
218 |
+
idx_cond = idx if idx.size(1) <= max_idx_length else idx[:, -max_idx_length:]
|
219 |
+
# forward the model to get the logits for the index in the sequence
|
220 |
+
logits, _ = self(idx_cond)
|
221 |
+
# pluck the logits at the final step and scale by desired temperature
|
222 |
+
logits = logits[:, -1, :] / temperature
|
223 |
+
# optionally crop the logits to only the top k options
|
224 |
+
if top_k is not None:
|
225 |
+
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
226 |
+
logits[logits < v[:, [-1]]] = -float('Inf')
|
227 |
+
# apply softmax to convert logits to (normalized) probabilities
|
228 |
+
probs = F.softmax(logits, dim=-1)
|
229 |
+
# sample from the distribution
|
230 |
+
idx_next = torch.multinomial(probs, num_samples=1)
|
231 |
+
# yield the next index
|
232 |
+
# append sampled index to the running sequence and continue
|
233 |
+
idx = torch.cat((idx, idx_next), dim=1)
|
234 |
+
yield idx_next.item()
|
235 |
+
|
236 |
+
|
237 |
+
|
238 |
+
def remove_caseifer(text):
|
239 |
+
new_text = ""
|
240 |
+
i = 0
|
241 |
+
while i < len(text):
|
242 |
+
if text[i] == "↨":
|
243 |
+
if i+1 < len(text):
|
244 |
+
new_text += text[i+1].upper()
|
245 |
+
i += 1
|
246 |
+
else:
|
247 |
+
pass # skip this index
|
248 |
+
else:
|
249 |
+
new_text += text[i]
|
250 |
+
i += 1
|
251 |
+
return new_text
|
252 |
+
|
253 |
+
def add_caseifer(text):
|
254 |
+
|
255 |
+
# Define your set of acceptable characters (original + keys from replace_map + replace_values)
|
256 |
+
#chars = "\n\"\t' &@!$#,/\\+=-<>*%.…_:;[]}{()^?0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz§↨©®™¶¥¼°½¾«»£βθ♪ƒ~±¤º·\x8f€¢"
|
257 |
+
tokenlist = "\n\t\x8f !#$%&()*+,-./:;<=>?@[\]^_{|}~§↨©®™¶¥¼°½¾«»£βθ♪ƒ±¤º·€¢\"'…0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
258 |
+
|
259 |
+
upperlist = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
260 |
+
new_text = []
|
261 |
+
for char in text:
|
262 |
+
if char in tokenlist:
|
263 |
+
if char in upperlist:
|
264 |
+
new_text.append("↨" + char.lower())
|
265 |
+
else:
|
266 |
+
new_text.append(char)
|
267 |
+
else:
|
268 |
+
pass
|
269 |
+
return "".join(new_text)
|
270 |
+
|
271 |
+
|
272 |
+
|
273 |
+
model_dir = '16bit'
|
274 |
+
device = 'cuda'
|
275 |
+
dtype = 'bfloat16'
|
276 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
277 |
+
torch.backends.cudnn.allow_tf32 = True
|
278 |
+
device_type = 'cuda' if 'cuda' in device else 'cpu'
|
279 |
+
ptdtype = {'float32': torch.float32, 'bfloat16': torch.bfloat16, 'float16': torch.float16}[dtype]
|
280 |
+
ctx = nullcontext() if device_type == 'cpu' else torch.amp.autocast(device_type=device_type, dtype=ptdtype)
|
281 |
+
max_new_tokens = 2048 # number of tokens generated in each sample
|
282 |
+
temperature = 0.8 # 1.0 = no change, < 1.0 = less random, > 1.0 = more random, in predictions
|
283 |
+
top_k = 24 # retain only the top_k most likely tokens, clamp others to have 0 probability
|
284 |
+
|
285 |
+
ckpt_path = os.path.join(model_dir, 'ckpt.pt')
|
286 |
+
checkpoint = torch.load(ckpt_path, map_location=device)
|
287 |
+
gptconf = GPTConfig(**checkpoint['model_args'])
|
288 |
+
model = GPT(gptconf)
|
289 |
+
state_dict = checkpoint['model']
|
290 |
+
unwanted_prefix = '_orig_mod.'
|
291 |
+
for k,v in list(state_dict.items()):
|
292 |
+
if k.startswith(unwanted_prefix):
|
293 |
+
state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
|
294 |
+
model.load_state_dict(state_dict)
|
295 |
+
|
296 |
+
model.eval()
|
297 |
+
model.to(device)
|
298 |
+
meta_path = os.path.join(model_dir, 'meta.pkl')
|
299 |
+
load_meta = os.path.exists(meta_path)
|
300 |
+
with open(meta_path, 'rb') as f:
|
301 |
+
meta = pickle.load(f)
|
302 |
+
# TODO want to make this more general to arbitrary encoder/decoder schemes
|
303 |
+
stoi, itos = meta['stoi'], meta['itos']
|
304 |
+
encode = lambda s: [stoi[c] for c in s]
|
305 |
+
decode = lambda l: ''.join([itos[i] for i in l])
|
306 |
+
|
307 |
+
class CharGPT(llm.Model):
|
308 |
+
model_id = "chargpt"
|
309 |
+
|
310 |
+
def execute(self, prompt, stream, response, conversation):
|
311 |
+
text = prompt.prompt
|
312 |
+
shift = False
|
313 |
+
# generated_text = ''
|
314 |
+
start_ids = encode(add_caseifer(text))
|
315 |
+
x = (torch.tensor(start_ids, dtype=torch.long, device=device)[None, ...])
|
316 |
+
for idx_next in model.generate_streaming(x, max_new_tokens, temperature=temperature, top_k=top_k):
|
317 |
+
# convert the index to a character and print it to the screen
|
318 |
+
char = decode([idx_next])
|
319 |
+
# check for newline character
|
320 |
+
if char == '§':
|
321 |
+
# append the completed line to the list or print it to the screen
|
322 |
+
# generated_sequences.append(generated_text)
|
323 |
+
# reset the generated text for the next line
|
324 |
+
# generated_data = generated_text
|
325 |
+
# generated_text = ''
|
326 |
+
break
|
327 |
+
|
328 |
+
# append the character to the generated text
|
329 |
+
if shift:
|
330 |
+
# generated_text += char.upper()
|
331 |
+
yield char.upper()# + ''
|
332 |
+
# print(char.upper(), end='', flush=True)
|
333 |
+
shift = False
|
334 |
+
elif char == '↨':
|
335 |
+
shift = True
|
336 |
+
else:
|
337 |
+
# generated_text += char
|
338 |
+
yield char# + ''
|
339 |
+
#print(char, end='', flush=True)
|
pyproject.toml
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[project]
|
2 |
+
name = "chargpt"
|
3 |
+
version = "0.1"
|
4 |
+
|
5 |
+
[project.entry-points.llm]
|
6 |
+
chargpt = "llm_chargpt"
|