First script in the no-magic repository. Phase 1 of the implementation sequence — establishes the project's first working educational script. BPE tokenization was chosen as the entry point because it requires no autograd, has clear success criteria, and is the first step in the learning path ("How text becomes numbers").
Target file:01-foundations/microtokenizer.pyExpected: ~180-200 lines, < 2 min runtime, zero dependencies
Implementation Structure
Section 0: File Thesis + Reference
python
"""
How text becomes numbers -- the compression algorithm hiding inside every LLM.
Byte-Pair Encoding learns a vocabulary by iteratively merging the most frequent
adjacent token pairs, then encodes new text by replaying those merges in priority order.
"""
# Reference: Philip Gage, "A New Algorithm for Data Compression" (1994).
# GPT-2's byte-level BPE variant (Radford et al., 2019) starts from raw bytes
# rather than characters -- that's the version implemented here.
Section 1: Imports + Seed
os, urllib.request, collections.Counter
random.seed(42) (repo convention, BPE itself is deterministic)
Section 2: Constants
Constant
Value
Rationale
NUM_MERGES
256
Vocab = 512 tokens. Enough compression for demo, fast training.
Key intuition: each merge absorbs the most redundancy per step — greedy compression that naturally discovers morphological units ("play" + "ing") without linguistic rules.
Section 5: Encoding + Decoding
build_vocab(merges) -> dict[int, bytes]
Base: {i: bytes([i]) for i in range(256)}
Merged: vocab[new_id] = vocab[a] + vocab[b]
Recursive expansion makes decoding trivial — every token maps to definite bytes
encode(text, merges) -> list[int]
Convert text to bytes → apply merges in priority order (NOT frequency order on new text)
Critical "why" comment: priority order ensures deterministic tokenization; re-counting would make output input-dependent
Signpost: O(n * M) naive encoding; production uses trie structures for O(n)
decode(token_ids, vocab) -> str
Lookup + concatenate + UTF-8 decode
Intuition: decode is just a lookup table — round-trip correctness is guaranteed by construction
Section 6: Inference Demo
Print output in four blocks:
Round-trip tests: 6 test strings (common name, uncommon name, hyphenated, apostrophe, empty, single char) — each shows [PASS/FAIL] with encoded tokens and decoded result.
Compression ratio: Full corpus byte count vs BPE token count. Must be >= 1.5x.
Top 20 merges: Show each merge's component tokens and resulting token in human-readable form.
Tokenization example: One name broken into bytes → tokens → pieces.
Constants, Data Loading, BPE Training, Encoding/Decoding, Inference
"Why" comments
4+
Left-to-right merge, priority order encoding, bytes-as-base, greedy compression
Math-to-code
2
Pair counting formulation, compression ratio
Intuition
3+
No unknown tokens, morphology emergence, decode simplicity
Signpost
3
256 vs 50K merges, O(n*M) vs trie, naive vs priority queue
Target density: 30-40% comment/blank lines.
Verification
python 01-foundations/microtokenizer.py exits 0, prints training + inference
All round-trip tests print [PASS]
Compression ratio >= 1.5x
Runtime < 2 minutes (expected: 10-30 seconds)
No imports outside stdlib
Line count ~180-200
If you need specific details from before exiting plan mode (like exact code snippets, error messages, or content you generated), read the full transcript at: /Users/druk/.REDACTED.jsonl
If this plan can be broken down into multiple independent tasks, consider using the TeamCreate tool to create a team and parallelize the work.
Assistant
Let me read the implementation spec and check the repo structure before writing.
Assistant
★ Insight ─────────────────────────────────────
BPE is the tokenization algorithm behind GPT-2/3/4. The key insight: start from raw bytes (256 base tokens — covers all of Unicode automatically), then greedily merge the most frequent adjacent pair into a new token. This compression process naturally discovers morphological units like "ing", "tion", "un" without any linguistic rules. Encoding new text replays merges in priority order (the order they were learned), not by re-counting frequencies — this guarantees deterministic tokenization.
─────────────────────────────────────────────────
Assistant
Now run it to verify correctness and timing.
Assistant
All checks pass. Let me verify line count.
Assistant
★ Insight ─────────────────────────────────────
The first merges reveal dataset structure: n\n, a\n, e\n merge letters with newlines because names.txt is newline-delimited — BPE finds corpus-level patterns, not just linguistic ones.
Compression ratio of 2.01x means each BPE token represents ~2 bytes on average with only 256 merges. Production tokenizers achieve 3-4x with 50K+ merges on diverse corpora.
"Elizabeth" → ['E', 'li', 'z', 'ab', 'et', 'h'] shows BPE discovering common character bigrams in names without any phonological rules.
─────────────────────────────────────────────────
Verification summary:
Criterion
Result
All round-trip tests
6/6 PASS
Compression ratio
2.01x (threshold: >= 1.5x)
Runtime
12 seconds (threshold: < 2 min)
External imports
None (stdlib only)
Line count
227 lines (target: ~180-200, slightly over due to comment density)
Zero arguments
python script.py runs full demo
The 227 lines vs the ~200 target is due to the comment density requirement (30-40%). Every comment type from the plan is present: file thesis, section headers (# === ... ===), "why" comments (4), math-to-code mappings (2), intuition comments (3), signpost comments (3).
User
Verification
python 01-foundations/microtokenizer.py exits 0, prints training + inference
All round-trip tests print [PASS]
Compression ratio >= 1.5x
Runtime < 2 minutes (expected: 10-30 seconds)
No imports outside stdlib
Line count ~180-200
If you need specific details from before exiting plan mode (like exact code snippets, error messages, or content you generated), read the full transcript at: /Users/druk/.REDACTED.jsonl
If this plan can be broken down into multiple independent tasks, consider using the TeamCreate tool to create a team and parallelize the work.
User
Comment Plan
Type
Count
Key Locations
File thesis
1
Top docstring
Section headers
5
Constants, Data Loading, BPE Training, Encoding/Decoding, Inference
"Why" comments
4+
Left-to-right merge, priority order encoding, bytes-as-base, greedy compression
Math-to-code
2
Pair counting formulation, compression ratio
Intuition
3+
No unknown tokens, morphology emergence, decode simplicity
Signpost
3
256 vs 50K merges, O(n*M) vs trie, naive vs priority queue
"""
How text becomes numbers -- the compression algorithm hiding inside every LLM.
Byte-Pair Encoding learns a vocabulary by iteratively merging the most frequent
adjacent token pairs, then encodes new text by replaying those merges in priority order.
"""
# Reference: Philip Gage, "A New Algorithm for Data Compression" (1994).
# GPT-2's byte-level BPE variant (Radford et al., 2019) starts from raw bytes
# rather than characters -- that's the version implemented here.
Section 1: Imports + Seed
os, urllib.request, collections.Counter
random.seed(42) (repo convention, BPE itself is deterministic)
Section 2: Constants
Constant
Value
Rationale
NUM_MERGES
256
Vocab = 512 tokens. Enough compression for demo, fast training.
Key intuition: each merge absorbs the most redundancy per step — greedy compression that naturally discovers morphological units ("play" + "ing") without linguistic rules.
Section 5: Encoding + Decoding
build_vocab(merges) -> dict[int, bytes]
Base: {i: bytes([i]) for i in range(256)}
Merged: vocab[new_id] = vocab[a] + vocab[b]
Recursive expansion makes decoding trivial — every token maps to definite bytes
encode(text, merges) -> list[int]
Convert text to bytes → apply merges in priority order (NOT frequency order on new text)
Critical "why" comment: priority order ensures deterministic tokenization; re-counting would make output input-dependent
Signpost: O(n * M) naive encoding; production uses trie structures for O(n)
decode(token_ids, vocab) -> str
Lookup + concatenate + UTF-8 decode
Intuition: decode is just a lookup table — round-trip correctness is guaranteed by construction
Section 6: Inference Demo
Print output in four blocks:
Round-trip tests: 6 test strings (common name, uncommon name, hyphenated, apostrophe, empty, single char) — each shows [PASS/FAIL] with encoded tokens and decoded result.
Compression ratio: Full corpus byte count vs BPE token count. Must be >= 1.5x.
Top 20 merges: Show each merge's component tokens and resulting token in human-readable form.
Tokenization example: One name broken into bytes → tokens → pieces.