MaxMillion404 commited on
Commit
5b46ece
·
verified ·
1 Parent(s): 918906a

MaxGPT-1: weights (safetensors), code to run it, model card

Browse files
Files changed (8) hide show
  1. README.md +49 -0
  2. config.py +39 -0
  3. model.py +202 -0
  4. model.safetensors +3 -0
  5. run.py +21 -0
  6. sample.py +129 -0
  7. tokenizer.json +0 -0
  8. tokenizer.py +325 -0
README.md ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ library_name: pytorch
6
+ tags:
7
+ - from-scratch
8
+ - small-language-model
9
+ - gpt
10
+ - pytorch
11
+ - safetensors
12
+ pipeline_tag: text-generation
13
+ ---
14
+
15
+ # MaxGPT-1 (23M)
16
+
17
+ The first of four language models built from scratch. Written entirely by hand: no line of its code was written by an AI.
18
+
19
+ ## What it is
20
+
21
+ - 23M parameters: 6 transformer blocks, hidden size 384, 6 heads, a 256-token context.
22
+ - Its own byte-pair tokenizer (16,000 tokens), trained on a sample of the data.
23
+ - Trained in about 30 minutes on one RTX 5070 (12 GB), 15,000 steps, on TinyStories plus OpenAssistant, the same small mix as MaxGPT-2 so the only thing that changes between them is size.
24
+
25
+ ## What to expect
26
+
27
+ Word salad with English shape, which is the point of the smallest model in the series: you can watch coherence appear as the models grow.
28
+
29
+ ## Run it
30
+
31
+ ```bash
32
+ pip install torch safetensors
33
+ python run.py "USER: How do I make brownies?\nASSISTANT:"
34
+ ```
35
+
36
+ `run.py` loads `model.safetensors` with the model's own code in this folder (`config.py`, `model.py`, `tokenizer.py`, `sample.py`) and samples 120 tokens at temperature 0.8, top-k 50, on CUDA, Apple MPS or CPU.
37
+
38
+ ## The MaxGPT family
39
+
40
+ Built from scratch by [Maxwell Brohm](https://maxwellbrohm.com), a high school senior, in PyTorch with no pretrained weights and no `transformers` library. Code and full write-up: [https://github.com/MaxwellBrohm/MaxGPT](https://github.com/MaxwellBrohm/MaxGPT).
41
+
42
+ | Model | Parameters | Layers x width | Context | What it shows |
43
+ |---|---|---|---|---|
44
+ | MaxGPT-1 | 23M | 6 x 384 | 256 | coherent English emerges |
45
+ | MaxGPT-2 | 110M | 12 x 768 | 512 | learns the USER/ASSISTANT chat format |
46
+ | MaxGPT-3 | 235M | 16 x 1024 | 1024 | a real-looking chatbot |
47
+ | MaxGPT-3.5 | 235M | MaxGPT-3 plus chat fine-tuning | 1024 | replies like an assistant |
48
+
49
+ MaxGPT-Ultra, a 1.09B model on a modern decoder design, is in progress.
config.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ @dataclass
4
+ class Config:
5
+ # Architecture (MaxGPT-1)
6
+ vocab_size: int = 16000
7
+ context_window: int = 256
8
+ hidden_dim: int = 384
9
+ num_heads: int = 6
10
+ num_blocks: int = 6
11
+
12
+ # Training hyperparameters
13
+ batch_size: int = 128 # number of sequences per step, was bumped from 32 to 128 after bf16+Flash freed VRAM
14
+ learning_rate: float = 4e-4 # AdamW base learning rate, was 3e-4 but was bumped slightly higher for the larger batch
15
+ weight_decay: float = 0.1 # AdamW weight decay
16
+ beta1: float = 0.9 # AdamW beta1
17
+ beta2: float = 0.95 # AdamW beta2 (modern LLM standard, not 0.999)
18
+ grad_clip: float = 1.0 # max gradient norm before clipping
19
+
20
+ # Schedule
21
+ max_steps: int = 15000 # total training steps, was 20000 but was halved since each step now sees 4x more tokens and then brought back up to 15000 in order to allign with Chinchilla-optimal training
22
+ warmup_steps: int = 200 # linear warmup at start
23
+ eval_interval: int = 500 # how often to compute val loss
24
+ eval_iters: int = 50 # how many batches to average for val loss
25
+ log_interval: int = 50 # how often to print training loss
26
+
27
+ # Checkpointing
28
+ checkpoint_interval: int = 2000 # save every N steps
29
+ checkpoint_dir: str = "checkpoints"
30
+
31
+ # Data
32
+ data_dir: str = "data"
33
+
34
+ # Device — auto-detect, but allow override
35
+ # Will be set by train.py based on what's available
36
+ device: str = "auto"
37
+
38
+ # toggle for Flash Attention vs manual attention
39
+ use_flash_attention: bool = True # switch to False to use the manual version (for presentations)
model.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ class MLP(nn.Module):
6
+ def __init__(self, hidden_dim):
7
+ super().__init__()
8
+ # Expand to 4x, then back to hidden_dim
9
+ self.fc1 = nn.Linear(hidden_dim, 4 * hidden_dim)
10
+ self.gelu = nn.GELU()
11
+ self.fc2 = nn.Linear(4 * hidden_dim, hidden_dim)
12
+
13
+ def forward(self, x):
14
+ # x shape: (B, T, C)
15
+ x = self.fc1(x) # (B, T, 4C)
16
+ x = self.gelu(x) # (B, T, 4C)
17
+ x = self.fc2(x) # (B, T, C)
18
+ return x
19
+
20
+ class CausalSelfAttention(nn.Module):
21
+ def __init__(self, hidden_dim, num_heads, context_window, use_flash=True):
22
+ super().__init__()
23
+ assert hidden_dim % num_heads == 0, "hidden_dim must be divisible by num_heads"
24
+
25
+ self.num_heads = num_heads
26
+ self.head_dim = hidden_dim // num_heads # e.g., 384 / 6 = 64
27
+ self.hidden_dim = hidden_dim
28
+ self.use_flash = use_flash
29
+
30
+ # One linear layer that produces Q, K, V all at once
31
+ # Input C, output 3C — then we'll split into Q, K, V
32
+ # (More efficient than three separate linear layers)
33
+ self.qkv_proj = nn.Linear(hidden_dim, 3 * hidden_dim)
34
+
35
+ # After attention, project back to hidden_dim
36
+ self.out_proj = nn.Linear(hidden_dim, hidden_dim)
37
+
38
+ # Precompute the causal mask: a (T, T) lower-triangular matrix of 1s.
39
+ # Position i can attend to positions 0..i but not i+1, i+2, ..., T-1.
40
+ # We use register_buffer because we want this tensor to move with the model
41
+ # (e.g., to GPU) but NOT be a learnable parameter.
42
+ mask = torch.tril(torch.ones(context_window, context_window))
43
+ self.register_buffer("causal_mask", mask)
44
+
45
+ def forward(self, x):
46
+ # x shape: (B, T, C)
47
+ B, T, C = x.shape
48
+
49
+ # Project to Q, K, V all at once
50
+ qkv = self.qkv_proj(x) # (B, T, 3C)
51
+
52
+ # Split the last dimension into three pieces: Q, K, V
53
+ # Each will be shape (B, T, C)
54
+ q, k, v = qkv.split(C, dim=-1)
55
+ # or equivalently: q, k, v = qkv.chunk(3, dim=-1)
56
+
57
+ # Reshape for multi-head attention:
58
+ # We want to split C into (num_heads, head_dim) and move num_heads
59
+ # to the second dimension so heads are processed in parallel.
60
+ #
61
+ # (B, T, C) → (B, T, num_heads, head_dim) → (B, num_heads, T, head_dim)
62
+ q = q.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
63
+ k = k.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
64
+ v = v.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
65
+ # Now all three have shape (B, num_heads, T, head_dim)
66
+
67
+ # Compute attention scores: Q @ K^T
68
+ # (B, num_heads, T, head_dim) @ (B, num_heads, head_dim, T)
69
+ # = (B, num_heads, T, T)
70
+ #
71
+ # Divide by sqrt(head_dim) to stabilize gradients
72
+ # (Without scaling, dot products grow large with head_dim, pushing
73
+ # softmax into regions where gradients vanish)
74
+ # Branch: use Flash Attention OR manual computation
75
+ if self.use_flash:
76
+ # PyTorch's fused kernel — picks Flash Attention on Ampere+ GPUs,
77
+ # memory-efficient attention elsewhere. Handles scaling, causal mask,
78
+ # softmax, and Q@K@V in one fused operation
79
+ out = F.scaled_dot_product_attention(
80
+ q, k, v,
81
+ is_causal=True # auto-applies causal mask, no need for our custom one
82
+ )
83
+ else:
84
+ # Manual attention (for presentations — shows what's actually happening)
85
+ scores = (q @ k.transpose(-2, -1)) / (self.head_dim ** 0.5)
86
+ scores = scores.masked_fill(self.causal_mask[:T, :T] == 0, float("-inf"))
87
+ attn = F.softmax(scores, dim=-1)
88
+ out = attn @ v
89
+
90
+ # Continue with existing reshape and output projection
91
+ out = out.transpose(1, 2).contiguous().view(B, T, C)
92
+ out = self.out_proj(out)
93
+ return out
94
+
95
+ class TransformerBlock(nn.Module):
96
+ def __init__(self, hidden_dim, num_heads, context_window, use_flash=True):
97
+ super().__init__()
98
+ # Pre-norm style: normalize BEFORE the sub-layer, not after
99
+ self.ln1 = nn.LayerNorm(hidden_dim)
100
+ self.attn = CausalSelfAttention(hidden_dim, num_heads, context_window, use_flash=use_flash)
101
+ self.ln2 = nn.LayerNorm(hidden_dim)
102
+ self.mlp = MLP(hidden_dim)
103
+
104
+ def forward(self, x):
105
+ # x shape: (B, T, C), stays (B, T, C) throughout
106
+ # Each sub-layer is wrapped: residual + pre-norm
107
+ x = x + self.attn(self.ln1(x))
108
+ x = x + self.mlp(self.ln2(x))
109
+ return x
110
+
111
+ class Transformer(nn.Module):
112
+ def __init__(self, vocab_size, context_window, hidden_dim, num_heads, num_blocks, use_flash=True):
113
+ super().__init__()
114
+
115
+ self.context_window = context_window
116
+
117
+ # Token embedding: vocab_size → hidden_dim
118
+ self.token_embed = nn.Embedding(vocab_size, hidden_dim)
119
+
120
+ # Positional embedding: context_window → hidden_dim
121
+ # We learn a separate embedding for each position 0, 1, ..., T-1
122
+ self.pos_embed = nn.Embedding(context_window, hidden_dim)
123
+
124
+ # Stack of N transformer blocks
125
+ self.blocks = nn.ModuleList([
126
+ TransformerBlock(hidden_dim, num_heads, context_window, use_flash=use_flash)
127
+ for _ in range(num_blocks)
128
+ ])
129
+
130
+ # Final layer norm before the output projection
131
+ self.ln_f = nn.LayerNorm(hidden_dim)
132
+
133
+ # Output projection: hidden_dim → vocab_size
134
+ # bias=False is standard practice for the lm_head
135
+ self.lm_head = nn.Linear(hidden_dim, vocab_size, bias=False)
136
+
137
+ def forward(self, token_ids, targets=None):
138
+ # token_ids shape: (B, T)
139
+ # targets shape: (B, T) — same shape, shifted by one position
140
+ # If targets is provided, we compute loss; otherwise just return logits.
141
+
142
+ B, T = token_ids.shape
143
+ assert T <= self.context_window, "sequence longer than context window"
144
+
145
+ # Position indices: [0, 1, 2, ..., T-1]
146
+ positions = torch.arange(0, T, device=token_ids.device)
147
+
148
+ # Look up embeddings
149
+ tok_emb = self.token_embed(token_ids) # (B, T, C)
150
+ pos_emb = self.pos_embed(positions) # (T, C)
151
+
152
+ # Add them. pos_emb is (T, C); it broadcasts across the B dimension.
153
+ x = tok_emb + pos_emb # (B, T, C)
154
+
155
+ # Pass through all transformer blocks
156
+ for block in self.blocks:
157
+ x = block(x)
158
+
159
+ # Final layer norm
160
+ x = self.ln_f(x) # (B, T, C)
161
+
162
+ # Project to vocabulary logits
163
+ logits = self.lm_head(x) # (B, T, vocab_size)
164
+
165
+ # Compute loss if targets provided (during training)
166
+ if targets is not None:
167
+ # Cross-entropy needs logits flattened to (B*T, vocab_size)
168
+ # and targets flattened to (B*T,)
169
+ loss = F.cross_entropy(
170
+ logits.view(-1, logits.size(-1)),
171
+ targets.view(-1)
172
+ )
173
+ return logits, loss
174
+ else:
175
+ return logits, None
176
+
177
+ if __name__ == "__main__":
178
+ # Quick shape + forward-pass test
179
+ model = Transformer(
180
+ vocab_size=16000,
181
+ context_window=256,
182
+ hidden_dim=384,
183
+ num_heads=6,
184
+ num_blocks=6,
185
+ )
186
+
187
+ # Count parameters
188
+ n_params = sum(p.numel() for p in model.parameters())
189
+ print(f"Total parameters: {n_params:,}")
190
+
191
+ # Fake input batch: 2 sequences of 64 tokens, random IDs in vocab range
192
+ token_ids = torch.randint(0, 16000, (2, 64))
193
+ targets = torch.randint(0, 16000, (2, 64))
194
+
195
+ # Test forward pass without targets (inference mode)
196
+ logits, loss = model(token_ids)
197
+ print(f"Logits shape: {logits.shape} # should be (2, 64, 16000)")
198
+ print(f"Loss (no targets): {loss} # should be None")
199
+
200
+ # Test forward pass with targets (training mode)
201
+ logits, loss = model(token_ids, targets)
202
+ print(f"Loss (with targets): {loss.item():.4f} # should be around log(16000) ≈ 9.68")
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:957672161d5808c1d40d0e42f002fe45da32d02610de2c234183a81678b5ea62
3
+ size 93715968
run.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate text with this model: python run.py "USER: How do I make brownies?\nASSISTANT:"
2
+ Needs torch and safetensors. Runs on CUDA, Apple MPS or CPU."""
3
+ import sys
4
+ import torch
5
+ from safetensors.torch import load_file
6
+ from config import Config
7
+ from model import Transformer
8
+ from tokenizer import BPETokenizer
9
+ from sample import generate
10
+
11
+ device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
12
+ config = Config()
13
+ tokenizer = BPETokenizer()
14
+ tokenizer.load("tokenizer.json")
15
+ model = Transformer(vocab_size=config.vocab_size, context_window=config.context_window,
16
+ hidden_dim=config.hidden_dim, num_heads=config.num_heads, num_blocks=config.num_blocks)
17
+ model.load_state_dict(load_file("model.safetensors"))
18
+ model.to(device).eval()
19
+ prompt = sys.argv[1] if len(sys.argv) > 1 else "USER: How do I make brownies?\nASSISTANT:"
20
+ with torch.no_grad():
21
+ print(generate(model, tokenizer, prompt.replace("\\n", "\n"), 120, 0.8, 50, device))
sample.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from config import Config
3
+ from model import Transformer
4
+ from tokenizer import BPETokenizer
5
+
6
+ def generate(model, tokenizer, prompt, max_new_tokens, temperature, top_k, device):
7
+ """
8
+ Generate text by sampling tokens autoregressively.
9
+
10
+ model: the trained Transformer
11
+ tokenizer: trained BPETokenizer (loaded with merges/vocab)
12
+ prompt: starting text (string)
13
+ max_new_tokens: how many tokens to generate (in addition to the prompt)
14
+ temperature: randomness knob (1.0 = default, lower = more focused)
15
+ top_k: only consider top K candidates each step (e.g., 50)
16
+ """
17
+
18
+ model.eval() # Make sure we're in eval mode
19
+
20
+ # Encode the prompt → list of token IDs
21
+ token_ids = tokenizer.encode(prompt)
22
+
23
+ # Convert to tensor of shape (1, T) — batch size 1
24
+ tokens = torch.tensor([token_ids], dtype=torch.long, device=device)
25
+
26
+ context_window = model.context_window
27
+
28
+ with torch.no_grad(): # We're not training, don't track gradients
29
+ for _ in range(max_new_tokens):
30
+ # If sequence is longer than context window, crop to last context_window tokens
31
+ # (model can only see this many at once)
32
+ if tokens.size(1) > context_window:
33
+ input_tokens = tokens[:, -context_window:]
34
+ else:
35
+ input_tokens = tokens
36
+
37
+ # Forward pass
38
+ logits, _ = model(input_tokens)
39
+ # logits shape: (1, T, vocab_size)
40
+
41
+ # We only care about the LAST position's prediction
42
+ # (what comes after the entire sequence so far)
43
+ logits = logits[:, -1, :] # shape: (1, vocab_size)
44
+
45
+ # Apply temperature scaling
46
+ logits = logits / temperature
47
+
48
+ # Apply top-k filtering: zero out all but top K
49
+ if top_k is not None:
50
+ top_values, _ = torch.topk(logits, top_k, dim=-1)
51
+ # The smallest of the top K becomes our threshold
52
+ threshold = top_values[:, -1].unsqueeze(-1)
53
+ # Set everything below threshold to -infinity (so softmax gives them 0)
54
+ logits = torch.where(logits < threshold, float("-inf"), logits)
55
+
56
+ # Softmax → probabilities
57
+ probs = torch.softmax(logits, dim=-1)
58
+
59
+ # Sample one token from the distribution
60
+ next_token = torch.multinomial(probs, num_samples=1)
61
+ # shape: (1, 1)
62
+
63
+ # Append to our sequence
64
+ tokens = torch.cat([tokens, next_token], dim=1)
65
+
66
+ # Decode back to text
67
+ all_token_ids = tokens[0].tolist() # remove batch dim
68
+ text = tokenizer.decode(all_token_ids)
69
+ return text
70
+
71
+ def main():
72
+ config = Config()
73
+ device = "cuda" if torch.cuda.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu")
74
+
75
+ # Load tokenizer
76
+ tokenizer = BPETokenizer()
77
+ tokenizer.load(config.data_dir + "/tokenizer.json")
78
+
79
+ # Build model architecture (same as training)
80
+ model = Transformer(
81
+ vocab_size=config.vocab_size,
82
+ context_window=config.context_window,
83
+ hidden_dim=config.hidden_dim,
84
+ num_heads=config.num_heads,
85
+ num_blocks=config.num_blocks,
86
+ )
87
+
88
+ # Load trained weights
89
+ # weights_only=False because checkpoint contains the Config dataclass, not just weights.
90
+ # Safe because we created the file ourselves.
91
+ checkpoint = torch.load(config.checkpoint_dir + "/final.pt", map_location=device, weights_only=False)
92
+ model.load_state_dict(checkpoint["model_state"])
93
+ model = model.to(device)
94
+
95
+ print(f"Loaded model from step {checkpoint['step']}")
96
+ print("Chat with MaxGPT-1. Type 'quit' to exit.\n")
97
+
98
+ # Simple chat loop
99
+ while True:
100
+ user_input = input("USER: ")
101
+ if user_input.strip().lower() in ["quit", "exit"]:
102
+ break
103
+
104
+ # Format prompt in the same format as training data
105
+ prompt = f"USER: {user_input}\nASSISTANT:"
106
+
107
+ # Generate
108
+ full_text = generate(
109
+ model=model,
110
+ tokenizer=tokenizer,
111
+ prompt=prompt,
112
+ max_new_tokens=200,
113
+ temperature=0.8,
114
+ top_k=50,
115
+ device=device,
116
+ )
117
+
118
+ # full_text contains both the prompt and the generated text
119
+ # Extract just the new part (after the prompt)
120
+ generated = full_text[len(prompt):]
121
+
122
+ # Optionally stop at next "USER:" since our format puts user turns there
123
+ if "USER:" in generated:
124
+ generated = generated.split("USER:")[0]
125
+
126
+ print(f"ASSISTANT:{generated}\n")
127
+
128
+ if __name__ == "__main__":
129
+ main()
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import Counter
2
+ from tqdm import tqdm
3
+ import json
4
+
5
+ class BPETokenizer:
6
+ def __init__(self):
7
+ # state: self.merges (dict mapping pair -> new id) and self.vocab (dict mapping id -> bytes)
8
+ self.merges = {}
9
+ # will map pair-of-token-IDs -> new token ID
10
+ # example: {(116, 104): 256} means "the pair (t, h) becomes token 256"
11
+
12
+ self.vocab = {i: bytes([i]) for i in range(256)}
13
+ # the initial 256 tokens are just the 256 possible byte values
14
+ # i.e., vocab[97] == b"a", vocab[98] == b"b", etc.
15
+
16
+ def train(self, text: str, vocab_size: int) -> None:
17
+ # ============================================================
18
+ # OPTIMIZED BPE TRAINING
19
+ # Per-merge cost: O(occurrences of merged pair), not O(total tokens)
20
+ # ============================================================
21
+
22
+ # --- STEP 1: Initialize tokens + linked list pointers ---
23
+ tokens = list(text.encode("utf-8"))
24
+ n = len(tokens)
25
+
26
+ # Doubly-linked list pointers so we can splice elements in O(1)
27
+ prev = [i - 1 for i in range(n)] # prev[0] = -1 (sentinel: no prev)
28
+ next_ = [i + 1 for i in range(n)] # next_[n-1] = n (sentinel: no next)
29
+ is_dead = [False] * n # tracks spliced-out positions
30
+
31
+ # --- STEP 2: One-time O(n) pass to populate pair counts + positions ---
32
+ pair_counts = {} # pair -> count
33
+ pair_positions = {} # pair -> SET of positions (left index)
34
+
35
+ for i in range(n - 1):
36
+ pair = (tokens[i], tokens[i+1])
37
+ pair_counts[pair] = pair_counts.get(pair, 0) + 1
38
+ pair_positions.setdefault(pair, set()).add(i)
39
+
40
+ num_merges = vocab_size - 256
41
+
42
+ print(f"Initial corpus: {n:,} tokens, {len(pair_counts):,} unique pairs")
43
+ print(f"Training {num_merges:,} merges...")
44
+
45
+ # --- STEP 3: The merge loop ---
46
+ for merge_index in tqdm(range(num_merges), desc="Training BPE"):
47
+
48
+ # 3a. Find max pair (and bail if no pairs left)
49
+ if not pair_counts:
50
+ break
51
+ (a, b) = max(pair_counts, key=pair_counts.get)
52
+ if pair_counts[(a, b)] <= 0:
53
+ break
54
+
55
+ new_id = 256 + merge_index
56
+
57
+ # 3b. Snapshot positions in sorted order, then process each
58
+ positions_to_process = sorted(pair_positions[(a, b)])
59
+
60
+ for pos in positions_to_process:
61
+
62
+ # 3c. Validity checks — skip dead or stale positions
63
+ if is_dead[pos]:
64
+ continue
65
+
66
+ j = next_[pos] # position of the right half of the pair
67
+ if j >= n or is_dead[j]:
68
+ continue
69
+ if tokens[pos] != a or tokens[j] != b:
70
+ continue
71
+
72
+ # 3d. Find neighbors
73
+ left_idx = prev[pos] # -1 if no left
74
+ right_idx = next_[j] # n if no right
75
+
76
+ # 3e. Update LEFT neighbor pair counts
77
+ # Before: (tokens[left_idx], a) -> After: (tokens[left_idx], new_id)
78
+ if left_idx >= 0:
79
+ old_left = (tokens[left_idx], a)
80
+ new_left = (tokens[left_idx], new_id)
81
+ pair_counts[old_left] -= 1
82
+ pair_positions[old_left].discard(left_idx)
83
+ pair_counts[new_left] = pair_counts.get(new_left, 0) + 1
84
+ pair_positions.setdefault(new_left, set()).add(left_idx)
85
+
86
+ # 3f. Update RIGHT neighbor pair counts
87
+ # Before: (b, tokens[right_idx]) at position j
88
+ # After: (new_id, tokens[right_idx]) at position pos
89
+ if right_idx < n:
90
+ old_right = (b, tokens[right_idx])
91
+ new_right = (new_id, tokens[right_idx])
92
+ pair_counts[old_right] -= 1
93
+ pair_positions[old_right].discard(j)
94
+ pair_counts[new_right] = pair_counts.get(new_right, 0) + 1
95
+ pair_positions.setdefault(new_right, set()).add(pos)
96
+
97
+ # 3g. Decrement the merged pair's count for THIS position
98
+ pair_counts[(a, b)] -= 1
99
+
100
+ # 3h. Splice — replace pos with new_id, remove j from the list
101
+ tokens[pos] = new_id
102
+ next_[pos] = right_idx
103
+ if right_idx < n:
104
+ prev[right_idx] = pos
105
+ is_dead[j] = True
106
+
107
+ # 3i. Clean up: clear the merged pair's position set
108
+ pair_positions[(a, b)] = set()
109
+ pair_counts[(a, b)] = 0
110
+
111
+ # 3j. Record the merge in tokenizer state
112
+ self.merges[(a, b)] = new_id
113
+ self.vocab[new_id] = self.vocab[a] + self.vocab[b]
114
+
115
+ print(f"Done! Final vocab size: {len(self.vocab):,}")
116
+ # All done. tokens, prev, next_, is_dead, pair_counts, pair_positions can be discarded.
117
+
118
+ def train_naive(self, text: str, vocab_size: int) -> None:
119
+ """Original naive O(n) per merge implementation. Kept for benchmarking."""
120
+ # Reset state (so we can call this on a fresh tokenizer)
121
+ self.merges = {}
122
+ self.vocab = {i: bytes([i]) for i in range(256)}
123
+
124
+ tokens = list(text.encode("utf-8"))
125
+ num_merges = vocab_size - 256
126
+
127
+ for i in tqdm(range(num_merges), desc="Training BPE (naive)"):
128
+ pair_counts = Counter(zip(tokens, tokens[1:]))
129
+ if not pair_counts:
130
+ break
131
+ most_common_pair = pair_counts.most_common(1)[0][0]
132
+ new_id = 256 + i
133
+ tokens = self._replace_pair(tokens, most_common_pair, new_id)
134
+ self.merges[most_common_pair] = new_id
135
+ self.vocab[new_id] = self.vocab[most_common_pair[0]] + self.vocab[most_common_pair[1]]
136
+
137
+ def encode(self, text: str) -> list[int]:
138
+ import heapq
139
+
140
+ # Convert to bytes
141
+ tokens = list(text.encode("utf-8"))
142
+ n = len(tokens)
143
+
144
+ if n < 2:
145
+ return tokens
146
+
147
+ # Linked list state (same pattern as train)
148
+ prev = [i - 1 for i in range(n)]
149
+ next_ = [i + 1 for i in range(n)]
150
+ is_dead = [False] * n
151
+
152
+ # Build initial heap: for every position with an applicable merge,
153
+ # push (rank, position) where rank = the merge ID (= merge order learned)
154
+ heap = []
155
+ for i in range(n-1):
156
+ pair = (tokens[i], tokens[i+1])
157
+ if pair in self.merges:
158
+ heapq.heappush(heap, (self.merges[pair], i))
159
+
160
+ # Process merges in order of rank
161
+ while heap:
162
+ rank, pos = heapq.heappop(heap)
163
+
164
+ # === Validity checks ===
165
+ if is_dead[pos]:
166
+ continue
167
+ j = next_[pos]
168
+ if j >= n or is_dead[j]:
169
+ continue
170
+
171
+ # Check the pair is STILL what we expected (might have changed since being pushed)
172
+ current_pair = (tokens[pos], tokens[j])
173
+ if current_pair not in self.merges or self.merges[current_pair] != rank:
174
+ continue
175
+
176
+ new_id = rank # rank IS the merge's new token ID
177
+
178
+ # === Splice (same as training) ===
179
+ right_idx = next_[j]
180
+ tokens[pos] = new_id
181
+ next_[pos] = right_idx
182
+ if right_idx < n:
183
+ prev[right_idx] = pos
184
+ is_dead[j] = True
185
+
186
+ # === Push new pairs created by this merge ===
187
+ # Left neighbor + this position
188
+ if prev[pos] >= 0:
189
+ left_pair = (tokens[prev[pos]], new_id)
190
+ if left_pair in self.merges:
191
+ heapq.heappush(heap, (self.merges[left_pair], prev[pos]))
192
+
193
+ # This position + right neighbor
194
+ if right_idx < n:
195
+ right_pair = (new_id, tokens[right_idx])
196
+ if right_pair in self.merges:
197
+ heapq.heappush(heap, (self.merges[right_pair], pos))
198
+
199
+ # === Walk the linked list to extract live tokens in order ===
200
+ result = []
201
+ i = 0
202
+ while i < n:
203
+ result.append(tokens[i])
204
+ i = next_[i]
205
+
206
+ return result
207
+
208
+ def decode(self, ids: list[int]) -> str:
209
+ # ids → bytes → utf-8 string
210
+ # Look up each ID's bytes, concatenate, decode as UTF-8
211
+
212
+ all_bytes = b"".join(self.vocab[id] for id in ids)
213
+
214
+ return all_bytes.decode("utf-8", errors="replace")
215
+ # errors="replace" is important — if a model generates a weird
216
+ # token sequence that doesn't decode as valid UTF-8, we get a
217
+ # replacement character (�) instead of crashing
218
+
219
+ def save(self, path: str) -> None:
220
+ # Convert self.merges (which has tuple keys, not JSON-friendly)
221
+ # into a list of plain records that preserve the training order
222
+ # Note: dicts preserve insertion order in Python 3.7+,
223
+ # so iterating gives merges in the order they were learned
224
+ merges_list = [
225
+ {"pair": [a, b], "id": new_id}
226
+ for (a, b), new_id in self.merges.items()
227
+ ]
228
+ data = {"merges": merges_list}
229
+
230
+ with open(path, "w") as f:
231
+ json.dump(data, f)
232
+
233
+ def load(self, path: str) -> None:
234
+ with open(path) as f:
235
+ data = json.load(f)
236
+
237
+ # Reset state to fresh
238
+ self.merges = {}
239
+ self.vocab = {i: bytes([i]) for i in range(256)}
240
+
241
+ # Replay each merge in training order, rebuilding both merges and vocab
242
+ for entry in data["merges"]:
243
+ a, b = entry["pair"]
244
+ new_id = entry["id"]
245
+ pair = (a, b)
246
+
247
+ self.merges[pair] = new_id
248
+ # Vocab entry = concatenation of the two halves' bytes
249
+ self.vocab[new_id] = self.vocab[a] + self.vocab[b]
250
+
251
+ def _replace_pair(self, tokens, pair, new_id):
252
+ # Walks the tokens list, replacing every occurrence of `pair` with `new_id`.
253
+ # Returns a new list (doesn't mutate the input).
254
+
255
+ result = []
256
+ i = 0
257
+ while i < len(tokens):
258
+ if i < len(tokens) - 1 and tokens[i] == pair[0] and tokens[i+1] == pair[1]:
259
+ result.append(new_id)
260
+ i = i + 2 # skip past both elements we just merged
261
+ else:
262
+ result.append(tokens[i])
263
+ i = i + 1
264
+ return result
265
+
266
+ if __name__ == "__main__":
267
+ import urllib.request
268
+ import os
269
+ import time
270
+
271
+ # Download Tiny Shakespeare (cache locally so we only download once)
272
+ cache_path = "/tmp/tinyshakespeare.txt"
273
+ if not os.path.exists(cache_path):
274
+ print("Downloading Tiny Shakespeare...")
275
+ url = "https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt"
276
+ urllib.request.urlretrieve(url, cache_path)
277
+
278
+ with open(cache_path) as f:
279
+ text = f.read()
280
+ print(f"Benchmark text: {len(text):,} chars\n")
281
+
282
+ vocab_size = 1000 # 744 merges
283
+
284
+ # === NEW algorithm ===
285
+ tok_new = BPETokenizer()
286
+ start = time.time()
287
+ tok_new.train(text, vocab_size=vocab_size)
288
+ new_time = time.time() - start
289
+ print(f"\nNEW algorithm: {new_time:.2f}s\n")
290
+
291
+ # === OLD (naive) algorithm ===
292
+ tok_old = BPETokenizer()
293
+ start = time.time()
294
+ tok_old.train_naive(text, vocab_size=vocab_size)
295
+ old_time = time.time() - start
296
+ print(f"\nOLD algorithm: {old_time:.2f}s\n")
297
+
298
+ # === RESULTS ===
299
+ print(f"=== Speedup: {old_time / new_time:.1f}x ===")
300
+
301
+ # Quick correctness check
302
+ sample = "To be or not to be"
303
+ enc_new = tok_new.encode(sample)
304
+ enc_old = tok_old.encode(sample)
305
+ print(f"New algorithm encodes '{sample}' as: {enc_new}")
306
+ print(f"Old algorithm encodes '{sample}' as: {enc_old}")
307
+ print(f"(Different token IDs are expected due to tie-breaking — both are valid)")
308
+
309
+ text = "the quick brown fox jumps over the lazy dog. " * 100
310
+ tok = BPETokenizer()
311
+ tok.train(text, vocab_size=300)
312
+
313
+ encoded = tok.encode("the quick fox")
314
+ decoded = tok.decode(encoded)
315
+ print(f"Encoded: {encoded}")
316
+ print(f"Decoded: '{decoded}'")
317
+ print(f"Match: {decoded == 'the quick fox'}")
318
+
319
+ # Speed test on a bigger chunk
320
+ big_text = "the quick brown fox " * 50000 # ~1MB
321
+ start = time.time()
322
+ encoded = tok.encode(big_text)
323
+ elapsed = time.time() - start
324
+ print(f"Encoded {len(big_text):,} chars in {elapsed:.2f}s "
325
+ f"({len(big_text)/elapsed:,.0f} chars/sec)")