rasbt commited on
Commit
6a867d4
·
verified ·
1 Parent(s): 5b8ed1b

Upload folder using huggingface_hub

Browse files
.DS_Store ADDED
Binary file (6.15 kB). View file
 
generate_example.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Sebastian Raschka under Apache License 2.0 (see LICENSE.txt).
2
+ # Source for "Build a Large Language Model From Scratch"
3
+ # https://github.com/rasbt/LLMs-from-scratch/blob/main/ch05/07_gpt_to_llama/standalone-llama32.ipynb
4
+
5
+ import os
6
+ import time
7
+ import urllib.request
8
+
9
+ import torch
10
+
11
+ from model import Llama3Model, generate, text_to_token_ids, token_ids_to_text
12
+ from tokenizer import Llama3Tokenizer, ChatFormat, clean_text
13
+
14
+ #######################################
15
+ # Model settings
16
+
17
+ MODEL_FILE = "llama3.2-1B-instruct.pth"
18
+ # MODEL_FILE = "llama3.2-1B-base.pth"
19
+ # MODEL_FILE = "llama3.2-3B-instruct.pth"
20
+ # MODEL_FILE = "llama3.2-3B-base.pth"
21
+
22
+ MODEL_CONTEXT_LENGTH = 8192 # Supports up to 131_072
23
+
24
+ # Text generation settings
25
+ if "instruct" in MODEL_FILE:
26
+ PROMPT = "What do llamas eat?"
27
+ else:
28
+ PROMPT = "Llamas eat"
29
+
30
+ MAX_NEW_TOKENS = 150
31
+ TEMPERATURE = 0.
32
+ TOP_K = 1
33
+ #######################################
34
+
35
+ url = f"https://huggingface.co/rasbt/llama-3.2-from-scratch/resolve/main/{MODEL_FILE}"
36
+
37
+ if not os.path.exists(MODEL_FILE):
38
+ urllib.request.urlretrieve(url, MODEL_FILE)
39
+ print(f"Downloaded to {MODEL_FILE}")
40
+
41
+
42
+ if "1B" in MODEL_FILE:
43
+ from model import LLAMA32_CONFIG_1B as LLAMA32_CONFIG
44
+ elif "3B" in MODEL_FILE:
45
+ from model import LLAMA32_CONFIG_3B as LLAMA32_CONFIG
46
+ else:
47
+ raise ValueError("Incorrect model file name")
48
+
49
+ LLAMA32_CONFIG["context_length"] = MODEL_CONTEXT_LENGTH
50
+
51
+ model = Llama3Model(LLAMA32_CONFIG)
52
+ model.load_state_dict(torch.load(MODEL_FILE, weights_only=True))
53
+
54
+ device = (
55
+ torch.device("cuda") if torch.cuda.is_available() else
56
+ torch.device("mps") if torch.backends.mps.is_available() else
57
+ torch.device("cpu")
58
+ )
59
+ model.to(device)
60
+
61
+ tokenizer = Llama3Tokenizer("tokenizer.model")
62
+
63
+ if "instruct" in MODEL_FILE:
64
+ tokenizer = ChatFormat(tokenizer)
65
+
66
+ torch.manual_seed(123)
67
+
68
+ start = time.time()
69
+
70
+ token_ids = generate(
71
+ model=model,
72
+ idx=text_to_token_ids(PROMPT, tokenizer).to(device),
73
+ max_new_tokens=MAX_NEW_TOKENS,
74
+ context_size=LLAMA32_CONFIG["context_length"],
75
+ top_k=TOP_K,
76
+ temperature=TEMPERATURE
77
+ )
78
+
79
+ print(f"Time: {time.time() - start:.2f} sec")
80
+
81
+ if torch.cuda.is_available():
82
+ max_mem_bytes = torch.cuda.max_memory_allocated()
83
+ max_mem_gb = max_mem_bytes / (1024 ** 3)
84
+ print(f"Max memory allocated: {max_mem_gb:.2f} GB")
85
+
86
+ output_text = token_ids_to_text(token_ids, tokenizer)
87
+
88
+ if "instruct" in MODEL_FILE:
89
+ output_text = clean_text(output_text)
90
+
91
+ print("\n\nOutput text:\n\n", output_text)
llama3.2-1B-base.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:af0de8aca49b5e6138c53a58bc72eb3a7dc6c37d9bceb9d0778b341cd12f1082
3
+ size 3064129762
llama3.2-1B-instruct.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4a1a0ff1c6e4d1aff871e50ab75684c4704e0cacabe6adf4cdbb5da3d4fcc077
3
+ size 3064130434
llama3.2-3B-base.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a41b5e512faeec28da58f144b4bb1739756f16294f105dfc7ee54849645d4253
3
+ size 7280710838
llama3.2-3B-instruct.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:459af5c3c14d19f72a48ddeadd01e53c1a521b7b3df517a6c4f9187d2757df0a
3
+ size 7280711878
model.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Sebastian Raschka under Apache License 2.0 (see LICENSE.txt).
2
+ # Source for "Build a Large Language Model From Scratch"
3
+ # https://github.com/rasbt/LLMs-from-scratch/blob/main/ch05/07_gpt_to_llama/standalone-llama32.ipynb
4
+
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+
9
+
10
+ LLAMA32_CONFIG_1B = {
11
+ "vocab_size": 128_256, # Vocabulary size
12
+ "context_length": 8192, # Maximum context length to use (reduced to save memory)
13
+ "orig_context_length": 131_072, # Context length that was used to train the model
14
+ "emb_dim": 2048, # Embedding dimension
15
+ "n_heads": 32, # Number of attention heads
16
+ "n_layers": 16, # Number of layers
17
+ "hidden_dim": 8192, # Size of the intermediate dimension in FeedForward
18
+ "n_kv_groups": 8, # Key-Value groups for grouped-query attention
19
+ "rope_base": 500_000.0, # The base in RoPE's "theta"
20
+ "dtype": torch.bfloat16, # Lower-precision dtype to reduce memory usage
21
+ "rope_freq": { # RoPE frequency scaling
22
+ "factor": 32.0,
23
+ "low_freq_factor": 1.0,
24
+ "high_freq_factor": 4.0,
25
+ "original_context_length": 8192,
26
+ }
27
+ }
28
+
29
+ LLAMA32_CONFIG_3B = {
30
+ "vocab_size": 128_256, # Vocabulary size
31
+ "context_length": 8192, # Maximum context length to use (reduced to save memory)
32
+ "orig_context_length": 131_072, # Context length that was used to train the model
33
+ "emb_dim": 3072, # Embedding dimension
34
+ "n_heads": 24, # Number of attention heads
35
+ "n_layers": 28, # Number of layers
36
+ "hidden_dim": 8192, # Size of the intermediate dimension in FeedForward
37
+ "n_kv_groups": 8, # Key-Value groups for grouped-query attention
38
+ "rope_base": 500_000.0, # The base in RoPE's "theta"
39
+ "dtype": torch.bfloat16, # Lower-precision dtype to reduce memory usage
40
+ "rope_freq": { # RoPE frequency scaling
41
+ "factor": 32.0,
42
+ "low_freq_factor": 1.0,
43
+ "high_freq_factor": 4.0,
44
+ "original_context_length": 8192,
45
+ }
46
+ }
47
+
48
+
49
+ class Llama3Model(nn.Module):
50
+ def __init__(self, cfg):
51
+ super().__init__()
52
+
53
+ # Main model parameters
54
+ self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["emb_dim"], dtype=cfg["dtype"])
55
+
56
+ self.trf_blocks = nn.ModuleList( # ModuleList since Sequential can only accept one input, and we need `x, mask, cos, sin`
57
+ [TransformerBlock(cfg) for _ in range(cfg["n_layers"])]
58
+ )
59
+
60
+ self.final_norm = nn.RMSNorm(cfg["emb_dim"], eps=1e-5, dtype=cfg["dtype"])
61
+ self.out_head = nn.Linear(cfg["emb_dim"], cfg["vocab_size"], bias=False, dtype=cfg["dtype"])
62
+
63
+ # Reusuable utilities
64
+ self.register_buffer("mask", torch.triu(torch.ones(cfg["context_length"], cfg["context_length"]), diagonal=1).bool())
65
+
66
+ if cfg["orig_context_length"] != cfg["context_length"]:
67
+ cfg["rope_base"] = rescale_theta(
68
+ cfg["rope_base"],
69
+ cfg["orig_context_length"],
70
+ cfg["context_length"]
71
+ )
72
+ cos, sin = compute_rope_params(
73
+ head_dim=cfg["emb_dim"] // cfg["n_heads"],
74
+ theta_base=cfg["rope_base"],
75
+ context_length=cfg["context_length"],
76
+ freq_config=cfg["rope_freq"]
77
+ )
78
+ self.register_buffer("cos", cos, persistent=False)
79
+ self.register_buffer("sin", sin, persistent=False)
80
+ self.cfg = cfg
81
+
82
+ def forward(self, in_idx):
83
+ # Forward pass
84
+ tok_embeds = self.tok_emb(in_idx)
85
+ x = tok_embeds
86
+
87
+ for block in self.trf_blocks:
88
+ x = block(x, self.mask, self.cos, self.sin)
89
+ x = self.final_norm(x)
90
+ logits = self.out_head(x.to(self.cfg["dtype"]))
91
+ return logits
92
+
93
+
94
+ class TransformerBlock(nn.Module):
95
+ def __init__(self, cfg):
96
+ super().__init__()
97
+ self.att = GroupedQueryAttention(
98
+ d_in=cfg["emb_dim"],
99
+ d_out=cfg["emb_dim"],
100
+ context_length=cfg["context_length"],
101
+ num_heads=cfg["n_heads"],
102
+ num_kv_groups=cfg["n_kv_groups"],
103
+ rope_base=cfg["rope_base"],
104
+ rope_config=cfg["rope_freq"],
105
+ dtype=cfg["dtype"]
106
+ )
107
+ self.ff = FeedForward(cfg)
108
+ self.norm1 = nn.RMSNorm(cfg["emb_dim"], eps=1e-5, dtype=cfg["dtype"])
109
+ self.norm2 = nn.RMSNorm(cfg["emb_dim"], eps=1e-5, dtype=cfg["dtype"])
110
+
111
+ def forward(self, x, mask, cos, sin):
112
+ # Shortcut connection for attention block
113
+ shortcut = x
114
+ x = self.norm1(x)
115
+ x = self.att(x, mask, cos, sin) # Shape [batch_size, num_tokens, emb_size]
116
+ x = x + shortcut # Add the original input back
117
+
118
+ # Shortcut connection for feed-forward block
119
+ shortcut = x
120
+ x = self.norm2(x)
121
+ x = self.ff(x)
122
+ x = x + shortcut # Add the original input back
123
+
124
+ return x
125
+
126
+
127
+ class FeedForward(nn.Module):
128
+ def __init__(self, cfg):
129
+ super().__init__()
130
+ self.fc1 = nn.Linear(cfg["emb_dim"], cfg["hidden_dim"], dtype=cfg["dtype"], bias=False)
131
+ self.fc2 = nn.Linear(cfg["emb_dim"], cfg["hidden_dim"], dtype=cfg["dtype"], bias=False)
132
+ self.fc3 = nn.Linear(cfg["hidden_dim"], cfg["emb_dim"], dtype=cfg["dtype"], bias=False)
133
+
134
+ def forward(self, x):
135
+ x_fc1 = self.fc1(x)
136
+ x_fc2 = self.fc2(x)
137
+ x = nn.functional.silu(x_fc1) * x_fc2
138
+ return self.fc3(x)
139
+
140
+
141
+ class GroupedQueryAttention(nn.Module):
142
+ def __init__(
143
+ self, d_in, d_out, context_length, num_heads,
144
+ num_kv_groups,
145
+ rope_base=10_000,
146
+ rope_config=None,
147
+ dtype=None
148
+ ):
149
+ super().__init__()
150
+ assert d_out % num_heads == 0, "d_out must be divisible by num_heads"
151
+ assert num_heads % num_kv_groups == 0, "num_heads must be divisible by num_kv_groups"
152
+
153
+ self.d_out = d_out
154
+ self.num_heads = num_heads
155
+ self.head_dim = d_out // num_heads
156
+
157
+ self.W_key = nn.Linear(d_in, num_kv_groups * self.head_dim, bias=False, dtype=dtype)
158
+ self.W_value = nn.Linear(d_in, num_kv_groups * self.head_dim, bias=False, dtype=dtype)
159
+ self.num_kv_groups = num_kv_groups
160
+ self.group_size = num_heads // num_kv_groups
161
+
162
+ self.W_query = nn.Linear(d_in, d_out, bias=False, dtype=dtype)
163
+ self.out_proj = nn.Linear(d_out, d_out, bias=False, dtype=dtype)
164
+
165
+ def forward(self, x, mask, cos, sin):
166
+ b, num_tokens, d_in = x.shape
167
+
168
+ queries = self.W_query(x) # Shape: (b, num_tokens, d_out)
169
+ keys = self.W_key(x) # Shape: (b, num_tokens, num_kv_groups * head_dim)
170
+ values = self.W_value(x) # Shape: (b, num_tokens, num_kv_groups * head_dim)
171
+
172
+ # Reshape queries, keys, and values
173
+ queries = queries.view(b, num_tokens, self.num_heads, self.head_dim)
174
+ keys = keys.view(b, num_tokens, self.num_kv_groups, self.head_dim)
175
+ values = values.view(b, num_tokens, self.num_kv_groups, self.head_dim)
176
+
177
+ # Transpose keys, values, and queries
178
+ keys = keys.transpose(1, 2) # Shape: (b, num_heads, num_tokens, head_dim)
179
+ values = values.transpose(1, 2) # Shape: (b, num_heads, num_tokens, head_dim)
180
+ queries = queries.transpose(1, 2) # Shape: (b, num_query_groups, num_tokens, head_dim)
181
+
182
+ # Apply RoPE
183
+ keys = apply_rope(keys, cos, sin)
184
+ queries = apply_rope(queries, cos, sin)
185
+
186
+ # Expand keys and values to match the number of heads
187
+ # Shape: (b, num_heads, num_tokens, head_dim)
188
+ keys = keys.repeat_interleave(self.group_size, dim=1) # Shape: (b, num_heads, num_tokens, head_dim)
189
+ values = values.repeat_interleave(self.group_size, dim=1) # Shape: (b, num_heads, num_tokens, head_dim)
190
+ # For example, before repeat_interleave along dim=1 (query groups):
191
+ # [K1, K2]
192
+ # After repeat_interleave (each query group is repeated group_size times):
193
+ # [K1, K1, K2, K2]
194
+ # If we used regular repeat instead of repeat_interleave, we'd get:
195
+ # [K1, K2, K1, K2]
196
+
197
+ # Compute scaled dot-product attention (aka self-attention) with a causal mask
198
+ # Shape: (b, num_heads, num_tokens, num_tokens)
199
+ attn_scores = queries @ keys.transpose(2, 3) # Dot product for each head
200
+
201
+ # Use the mask to fill attention scores
202
+ attn_scores = attn_scores.masked_fill(mask[:num_tokens, :num_tokens], -torch.inf)
203
+
204
+ attn_weights = torch.softmax(attn_scores / keys.shape[-1]**0.5, dim=-1)
205
+ assert keys.shape[-1] == self.head_dim
206
+
207
+ # Shape: (b, num_tokens, num_heads, head_dim)
208
+ context_vec = (attn_weights @ values).transpose(1, 2)
209
+
210
+ # Combine heads, where self.d_out = self.num_heads * self.head_dim
211
+ context_vec = context_vec.reshape(b, num_tokens, self.d_out)
212
+ context_vec = self.out_proj(context_vec) # optional projection
213
+
214
+ return context_vec
215
+
216
+
217
+ def compute_rope_params(head_dim, theta_base=10_000, context_length=4096, freq_config=None, dtype=torch.float32):
218
+ assert head_dim % 2 == 0, "Embedding dimension must be even"
219
+
220
+ # Compute the inverse frequencies
221
+ inv_freq = 1.0 / (theta_base ** (torch.arange(0, head_dim, 2, dtype=dtype)[: (head_dim // 2)].float() / head_dim))
222
+
223
+ # Frequency adjustments
224
+ if freq_config is not None:
225
+ low_freq_wavelen = freq_config["original_context_length"] / freq_config["low_freq_factor"]
226
+ high_freq_wavelen = freq_config["original_context_length"] / freq_config["high_freq_factor"]
227
+
228
+ wavelen = 2 * torch.pi / inv_freq
229
+
230
+ inv_freq_llama = torch.where(
231
+ wavelen > low_freq_wavelen, inv_freq / freq_config["factor"], inv_freq
232
+ )
233
+
234
+ smooth_factor = (freq_config["original_context_length"] / wavelen - freq_config["low_freq_factor"]) / (
235
+ freq_config["high_freq_factor"] - freq_config["low_freq_factor"]
236
+ )
237
+
238
+ smoothed_inv_freq = (
239
+ (1 - smooth_factor) * (inv_freq / freq_config["factor"]) + smooth_factor * inv_freq
240
+ )
241
+
242
+ is_medium_freq = (wavelen <= low_freq_wavelen) & (wavelen >= high_freq_wavelen)
243
+ inv_freq_llama = torch.where(is_medium_freq, smoothed_inv_freq, inv_freq_llama)
244
+ inv_freq = inv_freq_llama
245
+
246
+ # Generate position indices
247
+ positions = torch.arange(context_length, dtype=dtype)
248
+
249
+ # Compute the angles
250
+ angles = positions[:, None] * inv_freq[None, :] # Shape: (context_length, head_dim // 2)
251
+
252
+ # Expand angles to match the head_dim
253
+ angles = torch.cat([angles, angles], dim=1) # Shape: (context_length, head_dim)
254
+
255
+ # Precompute sine and cosine
256
+ cos = torch.cos(angles)
257
+ sin = torch.sin(angles)
258
+
259
+ return cos, sin
260
+
261
+
262
+ def apply_rope(x, cos, sin):
263
+ # x: (batch_size, num_heads, seq_len, head_dim)
264
+ batch_size, num_heads, seq_len, head_dim = x.shape
265
+ assert head_dim % 2 == 0, "Head dimension must be even"
266
+
267
+ # Split x into first half and second half
268
+ x1 = x[..., : head_dim // 2] # First half
269
+ x2 = x[..., head_dim // 2:] # Second half
270
+
271
+ # Adjust sin and cos shapes
272
+ cos = cos[:seq_len, :].unsqueeze(0).unsqueeze(0) # Shape: (1, 1, seq_len, head_dim)
273
+ sin = sin[:seq_len, :].unsqueeze(0).unsqueeze(0)
274
+
275
+ # Apply the rotary transformation
276
+ rotated = torch.cat((-x2, x1), dim=-1)
277
+ x_rotated = (x * cos) + (rotated * sin)
278
+
279
+ # It's ok to use lower-precision after applying cos and sin rotation
280
+ return x_rotated.to(dtype=x.dtype)
281
+
282
+
283
+ def rescale_theta(theta_old, context_length_old, context_length_new):
284
+ scaling_factor = context_length_new / context_length_old
285
+ theta_new = theta_old * scaling_factor
286
+ return theta_new
287
+
288
+
289
+ def text_to_token_ids(text, tokenizer):
290
+ encoded = tokenizer.encode(text)
291
+ encoded_tensor = torch.tensor(encoded).unsqueeze(0) # add batch dimension
292
+ return encoded_tensor
293
+
294
+
295
+ def token_ids_to_text(token_ids, tokenizer):
296
+ flat = token_ids.squeeze(0) # remove batch dimension
297
+ return tokenizer.decode(flat.tolist())
298
+
299
+
300
+ def generate(model, idx, max_new_tokens, context_size, temperature=0.0, top_k=None, eos_id=None):
301
+
302
+ # For-loop is the same as before: Get logits, and only focus on last time step
303
+ for _ in range(max_new_tokens):
304
+ idx_cond = idx[:, -context_size:]
305
+ with torch.no_grad():
306
+ logits = model(idx_cond)
307
+ logits = logits[:, -1, :]
308
+
309
+ # New: Filter logits with top_k sampling
310
+ if top_k is not None:
311
+ # Keep only top_k values
312
+ top_logits, _ = torch.topk(logits, top_k)
313
+ min_val = top_logits[:, -1]
314
+ logits = torch.where(logits < min_val, torch.tensor(float('-inf')).to(logits.device), logits)
315
+
316
+ # New: Apply temperature scaling
317
+ if temperature > 0.0:
318
+ logits = logits / temperature
319
+
320
+ # Apply softmax to get probabilities
321
+ probs = torch.softmax(logits, dim=-1) # (batch_size, context_len)
322
+
323
+ # Sample from the distribution
324
+ idx_next = torch.multinomial(probs, num_samples=1) # (batch_size, 1)
325
+
326
+ # Otherwise same as before: get idx of the vocab entry with the highest logits value
327
+ else:
328
+ idx_next = torch.argmax(logits, dim=-1, keepdim=True) # (batch_size, 1)
329
+
330
+ if idx_next == eos_id: # Stop generating early if end-of-sequence token is encountered and eos_id is specified
331
+ break
332
+
333
+ # Same as before: append sampled index to the running sequence
334
+ idx = torch.cat((idx, idx_next), dim=1) # (batch_size, num_tokens+1)
335
+
336
+ return idx
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:82e9d31979e92ab929cd544440f129d9ecd797b69e327f80f17e1c50d5551b55
3
+ size 2183982
tokenizer.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Sebastian Raschka under Apache License 2.0 (see LICENSE.txt).
2
+ # Source for "Build a Large Language Model From Scratch"
3
+ # https://github.com/rasbt/LLMs-from-scratch/blob/main/ch05/07_gpt_to_llama/standalone-llama32.ipynb
4
+
5
+
6
+ import os
7
+ from pathlib import Path
8
+
9
+ import tiktoken
10
+ from tiktoken.load import load_tiktoken_bpe
11
+
12
+
13
+ class Tokenizer:
14
+ def __init__(self, model_path):
15
+ assert os.path.isfile(model_path), f"Model file {model_path} not found"
16
+ mergeable_ranks = load_tiktoken_bpe(model_path)
17
+
18
+ self.special_tokens = {
19
+ "<|begin_of_text|>": 128000,
20
+ "<|end_of_text|>": 128001,
21
+ "<|start_header_id|>": 128006,
22
+ "<|end_header_id|>": 128007,
23
+ "<|eot_id|>": 128009,
24
+ }
25
+ self.special_tokens.update({
26
+ f"<|reserved_{i}|>": 128002 + i for i in range(256) if (128002 + i) not in self.special_tokens.values()
27
+ })
28
+
29
+ self.model = tiktoken.Encoding(
30
+ name=Path(model_path).name,
31
+ pat_str=r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+",
32
+ mergeable_ranks=mergeable_ranks,
33
+ special_tokens=self.special_tokens
34
+ )
35
+
36
+ def encode(self, text, bos=False, eos=False, allowed_special=set(), disallowed_special=()):
37
+ if bos:
38
+ tokens = [self.special_tokens["<|begin_of_text|>"]]
39
+ else:
40
+ tokens = []
41
+
42
+ tokens += self.model.encode(text, allowed_special=allowed_special, disallowed_special=disallowed_special)
43
+
44
+ if eos:
45
+ tokens.append(self.special_tokens["<|end_of_text|>"])
46
+ return tokens
47
+
48
+ def decode(self, tokens):
49
+ return self.model.decode(tokens)
50
+
51
+
52
+ class ChatFormat:
53
+ def __init__(self, tokenizer):
54
+ self.tokenizer = tokenizer
55
+
56
+ def encode_header(self, message):
57
+ tokens = []
58
+ tokens.append(self.tokenizer.special_tokens["<|start_header_id|>"])
59
+ tokens.extend(self.tokenizer.encode(message["role"], bos=False, eos=False))
60
+ tokens.append(self.tokenizer.special_tokens["<|end_header_id|>"])
61
+ tokens.extend(self.tokenizer.encode("\n\n", bos=False, eos=False))
62
+ return tokens
63
+
64
+ def encode(self, text):
65
+ message = {
66
+ "role": "user",
67
+ "content": text
68
+ }
69
+
70
+ tokens = self.encode_header(message)
71
+ tokens.extend(
72
+ self.tokenizer.encode(message["content"].strip(), bos=False, eos=False)
73
+ )
74
+ tokens.append(self.tokenizer.special_tokens["<|eot_id|>"])
75
+ return tokens
76
+
77
+ def decode(self, token_ids):
78
+ return self.tokenizer.decode(token_ids)
79
+
80
+
81
+ def clean_text(text, header_end="assistant<|end_header_id|>\n\n"):
82
+ # Find the index of the first occurrence of "<|end_header_id|>"
83
+ index = text.find(header_end)
84
+
85
+ if index != -1:
86
+ # Return the substring starting after "<|end_header_id|>"
87
+ return text[index + len(header_end):].strip() # Strip removes leading/trailing whitespace
88
+ else:
89
+ # If the token is not found, return the original text
90
+ return text