Byte-level BPE tokenizer
Build a byte-level BPE tokenizer from scratch, including regular-expression pretokenization, incremental pair-count training, efficient encoding, and special tokens. Verify it by loading GPT-2 merges and comparing with tiktoken, then train a custom vocabulary on a sample of the pretraining corpus.
After this lesson you can
- Implement BPE training with incremental pair counts and merge-rank encoding.
- Guarantee an exact round trip for any byte sequence, including invalid UTF-8.
- Reproduce GPT-2 tokenization exactly by loading its merges.
- Train a custom vocabulary and compare its compression with GPT-2 on the corpus.
Before you start
Before GPT sees a word
The model receives integer IDs rather than letters or words. Their choice determines how much context a document occupies, what regularities the network must learn, and how much the embedding table costs. A tokenizer that cannot represent a character can lose information before training begins. A base vocabulary with all 256 possible byte values can represent any finite byte sequence without an unknown token.
The figure trains a small BPE on the supplied text. Step through the training, change the corpus, and try a new input. The merge list is learned from the corpus. When encoding a new input, merges are applied in learned order rather than by their frequency in that input. This example uses explicit rules and simplified pretokenization; it does not attempt to reproduce GPT-2.
BPE training starts with elementary units and merges adjacent pairs. Byte-level BPE keeps all 256 bytes as its base vocabulary and adds one unit per merge. It represents an open vocabulary with a finite set of IDs. This does not imply that each token is a readable character or that malformed text is valid UTF-8.
Bytes, text, and boundaries
A Unicode character can occupy several UTF-8 bytes. Encoding converts a Unicode string into bytes; decoding produces text only when the sequence is valid UTF-8. The tokenizer must support a byte round trip, decode_bytes(encode_bytes(b)) == b, even when b is not valid UTF-8. For text, first encode as UTF-8 and recover the text by decoding the concatenated byte sequence. These two guarantees apply to different domains.
Pretokenization splits text into fragments before applying BPE and prevents a merge from crossing their boundaries. A regular expression changes which sequences can become tokens as well as accelerating the process. GPT-2 uses a specific expression that distinguishes contractions, letters, numbers, punctuation, and whitespace, among other cases; ordering and spaces matter. The GPT-2 encoding definition in tiktoken is an executable reference. Replacing it with split() does not reproduce that segmentation: split() discards separators and does not preserve the original text.
A special token is an interface decision, not a string that must automatically be recognized in every input. If untrusted text contains the spelling of the end-of-document token, treating it as ordinary text prevents it from producing the reserved ID. An API that supports special tokens should require explicit authorization and define which ones it accepts. The tiktoken interface distinguishes ordinary encoding from encoding that controls special tokens.
Learning merges while keeping the counts correct
Consider a sequence of IDs . The count of a pair is the number of positions for which . In a corpus of fragments, sum across fragments and never count a pair that crosses a boundary. A step selects a pair with maximum frequency, resolves ties deterministically, and replaces its non-overlapping occurrences from left to right with a new ID. For example, in a a a, the pair a a appears in two windows, but only one non-overlapping replacement fits. The number of windows and the number of replacements are different quantities.
When an occurrence is merged, only pairs touching its boundaries change: internal pairs disappear and new neighbors appear alongside the merged symbol. An incremental trainer maintains a frequency table and an index of fragments affected by each pair. After selecting the pair, it updates the contributions of affected fragments instead of scanning the entire corpus again. A priority queue can contain stale entries: when extracting one, verify that its frequency is still current and discard it otherwise. Index memory and update costs depend on the pair distribution. A constant time per merge cannot be claimed without specifying the cost of affected occurrences.
A reference implementation that recounts the entire corpus is useful for checking incremental results on small examples. Use the same tie-breaking rule, check every merge, and compare both frequencies and final IDs. Repeated full recounting takes, in the worst case, work proportional to the number of merges times the length of the traversed sequence. This is not a universally exact bound for all distributions because the sequence becomes shorter during the process.
The next cell is deliberately simple: it performs a full recount, making it an independent reference for small cases rather than a trainer for FineWeb-Edu. Ties are resolved by selecting the lexicographically smallest pair of IDs among those with maximum frequency. Fragments are supplied separately and each is encoded as UTF-8. The requested number of merges is an upper limit: if no pairs remain, the algorithm stops early.
from collections import Counter
def pair_counts(chunks):
counts = Counter()
for chunk in chunks:
counts.update(zip(chunk, chunk[1:]))
return counts
def merge_pair(ids, pair, new_id):
out, i = [], 0
while i < len(ids):
if i + 1 < len(ids) and (ids[i], ids[i + 1]) == pair:
out.append(new_id)
i += 2
else:
out.append(ids[i])
i += 1
return out
def train_reference(texts, limit):
vocab = [bytes([i]) for i in range(256)]
chunks = [list(s.encode('utf-8')) for s in texts]
merges = []
for _ in range(limit):
counts = pair_counts(chunks)
if not counts:
break
pair = min(counts, key=lambda p: (-counts[p], p))
new_id = len(vocab)
vocab.append(vocab[pair[0]] + vocab[pair[1]])
merges.append((pair, new_id, counts[pair]))
chunks = [merge_pair(c, pair, new_id) for c in chunks]
return vocab, merges, chunks
vocab_demo, merges_demo, chunks_demo = train_reference(['aaa', 'ab'], 2)
assert merges_demo[0] == ((97, 97), 256, 2)
assert b''.join(vocab_demo[t] for t in chunks_demo[0]) == b'aaa'
print('Fusiones:', merges_demo)
print('Fragmentos finales:', chunks_demo)The frequency 2 of the first merge comes from the two windows of aaa, although only one is replaced. The second merge is chosen after updating the sequence. The binary check confirms that the first fragment still represents exactly its original bytes.
Encoding is not retraining
Once the merge list has been learned, each pair has a rank given by its training order. To encode a fragment, start with its bytes and select the available adjacent pair with the lowest rank. Replace it and repeat until none remain. Frequency within the new text does not determine the order. Repeated fragments can be encoded once and stored in a cache tied to the exact versions of the merges and pretokenization. Invalidate the cache if the vocabulary changes.
The distinction appears in a sequence containing two learned pairs. If the earlier-ranked pair appears once and the later-ranked pair appears several times, the first still has priority. Each replacement changes adjacency, so sorting a list of pairs calculated only once at the start is insufficient. An efficient implementation can maintain neighbors in a linked list and keep candidates in a priority queue, invalidating pairs that are no longer adjacent. For short fragments, a full search can be easier to check, and managing the queue may not pay off. The answer depends on the actual length distribution and implementation.
A token created by merging is defined as the concatenation of its components’ bytes. By induction, each token represents exactly the bytes from which it came. Every replacement preserves the concatenation, and once finished, concatenating the IDs’ bytes returns the input. The proof also works for bytes that are invalid UTF-8. Text pretokenization must preserve every fragment and their concatenation for the argument to apply to the entire string.
Step 1 of 3. What is the invariant before the first merge?
Comparing with GPT-2 and measuring compression
Tokenizer parity evaluation compares complete ID sequences for the same inputs, not just token counts or decoded text. Different segmentations can decode to the same text. Comparing with GPT-2 requires reproducing merge ranks, the regular expression, and the special-token policy; a single difference can change IDs. Use ordinary text, verify each document individually, and keep examples of discrepancies with their bytes and fragments. Arbitrary bytes that are not UTF-8 are tested separately because GPT-2’s pretokenization interface operates on Unicode text.
To compare compression, define bytes per token as the total UTF-8 bytes divided by the total number of ordinary tokens in a collection. Aggregating numerators and denominators before dividing weights by tokens, whereas averaging per-document ratios answers a different question. Train the custom vocabulary only on the training set and measure both tokenizers on the same held-out documents. Record the source, version or revision, selection, size, and treatment of special tokens. A figure from one sample does not automatically describe other languages or code. The FineWeb-Edu dataset card documents its provenance and fields.
For example, if two documents have very different ratios and one requires many more tokens, the aggregate ratio gives that document more weight. If the question concerns typical behavior per document, also show the distribution of individual ratios. If the cost of processing a specific volume of text matters, the aggregate ratio directly relates total bytes to the number of positions. The same text, with the same boundaries and no added special tokens, should provide the common numerator for both comparisons.
More bytes per token reduces the positions required for that text, but does not guarantee better loss or arithmetic. A larger vocabulary also increases the parameters in input and output tables and can create tokens with few observations. Splitting digits may make the representation of numbers of different lengths more uniform, but its effect on a task depends on training and evaluation. It does not by itself prove that a model will calculate correctly. Singh and Strouse study how digit grouping and tokenization direction relate to arithmetic errors in particular models; they do not establish a general guarantee for all models.
Lab
Install the dependencies in your local environment with python -m pip install "tiktoken==0.14.0" "hypothesis==6.170.12" regex. Run the three cells in order. The first defines the encoder and incremental trainer; the second compares its merges against an independent full recount; the third downloads FineWeb-Edu, verifies parity, and measures compression. Access to the Hugging Face API and tiktoken’s GPT-2 files is required. The download may take time, and the service may rate-limit requests: the code retries on HTTP 429.
The bpe_lab_data directory keeps the document and result cache. Change it with the BPE_DATA_DIR environment variable. The training set consists of the first 100 documents and evaluation uses the next 100, without overlap; parity is tested on the first 10000. The API does not pin an immutable revision, so keep the files to repeat the experiment on exactly the same sample. GPT-2 has a much larger vocabulary than the custom 512-token vocabulary, so the table does not isolate the effect of the corpus.
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor
from functools import lru_cache
from heapq import heappop, heappush
from pathlib import Path
import json
import hashlib
import os
import time
import urllib.error
import urllib.request
HERE = Path(os.environ.get('BPE_DATA_DIR', 'bpe_lab_data'))
HERE.mkdir(parents=True, exist_ok=True)
os.environ['TIKTOKEN_CACHE_DIR'] = str(HERE / 'tiktoken-cache')
import regex
import tiktoken
from hypothesis import given, settings, strategies as st
PAT = regex.compile(r"'(?:[sdmt]|ll|ve|re)| ?\p{L}++| ?\p{N}++| ?[^\s\p{L}\p{N}]++|\s++$|\s+(?!\S)|\s")
def load_gpt2_original():
base = 'https://openaipublic.blob.core.windows.net/gpt-2/models/124M/'
for name in ('encoder.json', 'vocab.bpe'):
path = HERE / name
if not path.exists():
with urllib.request.urlopen(base + name, timeout=90) as response:
path.write_bytes(response.read())
encoder = json.loads((HERE / 'encoder.json').read_text(encoding='utf-8'))
bs = list(range(33, 127)) + list(range(161, 173)) + list(range(174, 256))
cs = bs[:]
for b in range(256):
if b not in bs:
bs.append(b)
cs.append(256 + len(cs) - (94 + 12 + 82))
unicode_to_byte = {chr(c): b for b, c in zip(bs, cs)}
ranks = {bytes(unicode_to_byte[c] for c in token): rank
for token, rank in encoder.items() if token != '<|endoftext|>'}
lines = (HERE / 'vocab.bpe').read_text(encoding='utf-8').splitlines()
pairs = [line.split() for line in lines[1:] if line.strip()]
assert len(pairs) == 50000
for rank, pair in enumerate(pairs, start=256):
assert len(pair) == 2 and encoder[''.join(pair)] == rank
assert encoder['<|endoftext|>'] == 50256
return ranks
def fetch(offset):
path = HERE / f'rows-{offset:05d}.json'
if not path.exists():
url = ('https://datasets-server.huggingface.co/rows?dataset='
'HuggingFaceFW%2Ffineweb-edu&config=sample-10BT&split=train'
f'&offset={offset}&length=100')
for attempt in range(8):
try:
with urllib.request.urlopen(url, timeout=90) as response:
raw = response.read()
break
except urllib.error.HTTPError as error:
if error.code != 429 or attempt == 7:
raise
time.sleep(min(60, 5 * 2**attempt))
path.write_bytes(raw)
data = json.loads(path.read_text(encoding='utf-8'))
rows = data['rows']
assert len(rows) == 100
return [row['row']['text'] for row in rows]
def encode_piece(piece, ranks):
parts = [bytes([b]) for b in piece]
while len(parts) > 1:
candidates = [(ranks.get(parts[i] + parts[i+1], 10**9), i)
for i in range(len(parts)-1)]
rank, i = min(candidates)
if rank == 10**9:
break
parts[i:i+2] = [parts[i] + parts[i+1]]
return [ranks[p] for p in parts]
def encode_heap(piece, ranks):
"""BPE por cola de prioridad y lista enlazada de índices."""
n = len(piece)
if not n:
return []
parts = [bytes([b]) for b in piece]
prev = [i-1 for i in range(n)]
nxt = [i+1 if i+1 < n else -1 for i in range(n)]
alive = [True] * n
heap = []
def push(i):
if i >= 0 and alive[i] and nxt[i] >= 0:
j = nxt[i]
rank = ranks.get(parts[i] + parts[j])
if rank is not None:
heappush(heap, (rank, i, j))
for i in range(n-1):
push(i)
while heap:
rank, i, j = heappop(heap)
if not alive[i] or not alive[j] or nxt[i] != j:
continue
if ranks.get(parts[i] + parts[j]) != rank:
continue
parts[i] += parts[j]
alive[j] = False
nxt[i] = nxt[j]
if nxt[i] >= 0:
prev[nxt[i]] = i
push(prev[i])
push(i)
out = []
i = 0
while i >= 0:
out.append(ranks[parts[i]])
i = nxt[i]
return out
def decode_bytes(ids, id_to_bytes):
return b''.join(id_to_bytes[i] for i in ids)
def make_text_encoder(ranks, special_literal='<|endoftext|>', special_id=None):
"""El especial solo se reconoce si el llamador lo autoriza explícitamente."""
if special_id is not None and special_id in ranks.values():
raise ValueError('El ID especial colisiona con el vocabulario ordinario')
@lru_cache(maxsize=200000)
def cached(piece):
return tuple(encode_heap(piece, ranks))
def ordinary(text):
return [i for m in PAT.finditer(text) for i in cached(m.group().encode('utf-8'))]
def encode(text, allow_special=False):
if not allow_special:
return ordinary(text)
if special_id is None:
raise ValueError('No se ha configurado un ID especial')
chunks = text.split(special_literal)
out = []
for i, chunk in enumerate(chunks):
if i:
out.append(special_id)
out.extend(ordinary(chunk))
return out
return encode
def train(texts, vocab_size=512):
"""Conteo incremental por fragmento ponderado; desempate lexicográfico.
Cada fusión solo actualiza fragmentos que contienen el par elegido. El
heap usa entradas antiguas descartables; el coste depende de los fragmentos
afectados, no de una promesa de complejidad lineal total.
"""
words = Counter(m.group().encode('utf-8') for t in texts for m in PAT.finditer(t))
pieces = [list(word) for word in words]
weights = list(words.values())
counts = Counter()
places = defaultdict(set)
for i, ids in enumerate(pieces):
local = Counter(zip(ids, ids[1:]))
for pair, n in local.items():
counts[pair] += n * weights[i]
places[pair].add(i)
heap = [(-n, pair) for pair, n in counts.items()]
import heapq
heapq.heapify(heap)
merges = []
tokens = [bytes([i]) for i in range(256)]
while len(tokens) < vocab_size and heap:
negative, pair = heappop(heap)
if counts[pair] != -negative or not counts[pair]:
continue
new = len(tokens)
tokens.append(tokens[pair[0]] + tokens[pair[1]])
merges.append((pair, new, -negative))
affected = list(places[pair])
touched = set()
for i in affected:
ids = pieces[i]
before = Counter(zip(ids, ids[1:]))
out = []
j = 0
while j < len(ids):
if j+1 < len(ids) and (ids[j], ids[j+1]) == pair:
out.append(new)
j += 2
else:
out.append(ids[j])
j += 1
pieces[i] = out
after = Counter(zip(out, out[1:]))
for p in before.keys() | after.keys():
delta = after[p] - before[p]
if delta:
counts[p] += delta * weights[i]
touched.add(p)
if after[p]:
places[p].add(i)
else:
places[p].discard(i)
for p in touched:
if counts[p] > 0:
heappush(heap, (-counts[p], p))
ranks = {token: i for i, token in enumerate(tokens)}
assert len(ranks) == len(tokens)
return ranks, mergesnpm run lab and open the connection link.Each fragment is counted with its multiplicity in the corpus. After a merge, only fragments containing the pair are recalculated, and the priority queue discards stale entries. The cost depends on how many fragments change, so this does not imply linear time. Lexicographic tie-breaking fixes the result. The encoder maintains a linked list and a heap of pairs by rank and left index, invalidates stale candidates, and uses a per-fragment cache. The version that scans all pairs remains as an independent reference.
def reference(texts, vocab_size):
words = Counter(m.group().encode('utf-8') for t in texts for m in PAT.finditer(t))
seq = {w: list(w) for w in words}
merges = []
for new in range(256, vocab_size):
counts = Counter()
for w, ids in seq.items():
for pair, n in Counter(zip(ids, ids[1:])).items():
counts[pair] += words[w] * n
if not counts:
break
pair = min(counts, key=lambda p: (-counts[p], p))
merges.append((pair, new, counts[pair]))
for w, ids in seq.items():
out = []
i = 0
while i < len(ids):
if i+1 < len(ids) and (ids[i], ids[i+1]) == pair:
out.append(new)
i += 2
else:
out.append(ids[i])
i += 1
seq[w] = out
return merges
test_count = [0]
@settings(max_examples=500, deadline=None, database=None, derandomize=True)
@given(st.lists(st.text(alphabet='abc 12é', min_size=0, max_size=60), min_size=1, max_size=5))
def test(texts):
test_count[0] += 1
_, got = train(texts, 280)
expected = reference(texts, 280)
assert got == expected, (texts, got, expected)
test()
assert test_count[0] == 500
print('500 corpora deterministas: fusiones y frecuencias idénticas al recuento completo.')npm run lab and open the connection link.The code reconstructs GPT-2’s byte-to-character map, loads its original encoder.json and vocab.bpe files, verifies all 50000 merges, and checks every rank against tiktoken. The original GPT-2 encoder documents its reversible mapping and application of merges. The binary check uses a custom decoder that concatenates bytes. The custom tokenizer treats text as ordinary by default and converts the special-token literal to its ID only when explicitly requested with allow_special=True. Parity is compared with tiktoken’s encode_ordinary for each complete list of IDs. Fragments come from GPT-2’s regular expression, and merges across them are disallowed.
def main():
gpt = tiktoken.get_encoding('gpt2')
ranks = load_gpt2_original()
assert ranks == gpt._mergeable_ranks
print('Encoder y 50000 fusiones oficiales: rangos idénticos a tiktoken', flush=True)
id_to_bytes = {rank: raw for raw, rank in ranks.items()}
id_to_bytes[gpt.eot_token] = b'<|endoftext|>'
assert PAT.pattern == gpt._pat_str
own = make_text_encoder(ranks, special_id=gpt.eot_token)
byte_tests = [0]
@settings(max_examples=1000, deadline=None, database=None, derandomize=True)
@given(st.binary(max_size=500))
def bytes_roundtrip(data):
byte_tests[0] += 1
ids = encode_heap(data, ranks)
assert ids == encode_piece(data, ranks)
assert decode_bytes(ids, id_to_bytes) == data
bytes_roundtrip()
assert byte_tests[0] == 1000
special = '<|endoftext|>'
assert own(special) == gpt.encode_ordinary(special)
assert gpt.eot_token not in own(special)
assert decode_bytes(own(special), id_to_bytes) == special.encode('utf-8')
assert own(special, allow_special=True) == [gpt.eot_token]
print('1000 casos deterministas de bytes arbitrarios: ida y vuelta exacta', flush=True)
print('Descargando 10 000 documentos FineWeb-Edu...', flush=True)
with ThreadPoolExecutor(max_workers=2) as pool:
batches = list(pool.map(fetch, range(0, 10000, 100)))
docs = [text for batch in batches for text in batch]
print('documentos:', len(docs), flush=True)
digest = hashlib.sha256()
for doc in docs:
raw = doc.encode('utf-8')
digest.update(len(raw).to_bytes(8, 'big'))
digest.update(raw)
print('dataset: HuggingFaceFW/fineweb-edu sample-10BT train, offsets 0:10000')
print('tiktoken:', tiktoken.__version__, 'sha256 documentos:', digest.hexdigest(), flush=True)
for i, doc in enumerate(docs):
a, b = own(doc), gpt.encode_ordinary(doc)
if a != b:
raise AssertionError(f'paridad fallida en documento {i}')
if (i+1) % 1000 == 0:
print('paridad exacta:', i+1, flush=True)
training, heldout = docs[:100], docs[100:200]
local, merges = train(training, vocab_size=512)
own_payload = {'vocab_hex': {k.hex(): v for k, v in local.items()},
'merges': merges, 'special_literal': special,
'special_id': len(local), 'dataset': 'HuggingFaceFW/fineweb-edu',
'config': 'sample-10BT', 'train_offsets': [0, 100],
'evaluation_offsets': [100, 200], 'sample_sha256': digest.hexdigest()}
(HERE / 'vocabulario.json').write_text(json.dumps(own_payload, ensure_ascii=False, indent=2), encoding='utf-8')
loaded = json.loads((HERE / 'vocabulario.json').read_text(encoding='utf-8'))
restored = {bytes.fromhex(k): v for k, v in loaded['vocab_hex'].items()}
own_local = make_text_encoder(restored, loaded['special_literal'], loaded['special_id'])
reverse_local = {v: k for k, v in restored.items()}
reverse_local[loaded['special_id']] = loaded['special_literal'].encode('utf-8')
sample = 'Hola <|endoftext|> 😀'
for allow in (False, True):
ids = own_local(sample, allow_special=allow)
assert (loaded['special_id'] in ids) == allow
assert decode_bytes(ids, reverse_local) == sample.encode('utf-8')
def measure(documents, vocabulary):
return sum(len(d.encode('utf-8')) for d in documents), sum(
len(encode_piece(m.group().encode('utf-8'), vocabulary))
for d in documents for m in PAT.finditer(d))
byte_count, own_count = measure(heldout, local)
gpt_count = sum(len(gpt.encode_ordinary(d)) for d in heldout)
print('Entrenamiento: 100 documentos; evaluación disjunta: 100 documentos')
print(f'Vocabulario propio: {len(local)} tokens, {len(merges)} fusiones')
print(f'Bytes: {byte_count}; tokens propios: {own_count}; bytes/token: {byte_count/own_count:.6f}')
print(f'Bytes: {byte_count}; tokens GPT-2: {gpt_count}; bytes/token: {byte_count/gpt_count:.6f}')
print('Primeras diez fusiones (par de IDs, ID nuevo, frecuencia):', merges[:10])
result = {'train_docs': 100, 'heldout_docs': 100, 'parity_docs': len(docs),
'bytes': byte_count, 'own_tokens': own_count, 'gpt2_tokens': gpt_count,
'own_vocab': len(local), 'merges': merges}
(HERE / 'result.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
main()npm run lab and open the connection link.In the recorded run, the custom encoder produced exactly the same IDs as tiktoken for 10000 out of 10000 documents. All 1000 deterministic arbitrary-byte tests preserved the input exactly, and the incremental trainer matched the full recount on 500 generated corpora. The first 100 documents in the split train the custom vocabulary, and the next 100 form the evaluation set. The table uses their 407643 UTF-8 bytes:
| Tokenizer | Evaluation tokens | Bytes per token |
|---|---|---|
| Custom, 512 ordinary tokens | 203340 | 2.004736 |
| GPT-2 | 87774 | 4.644234 |
The custom vocabulary adds the special token with ID 512, for 513 IDs in total. These results describe this particular sample and are not a comparison controlled for vocabulary size. The SHA-256 fingerprint of the first 10000 documents of the split identifies the sample. It is computed by concatenating, for each document, its length in eight big-endian bytes and its UTF-8 content: 7294c62ff7a92792d8ab472285f15a3acc3ee2064a4c0f62f889f3457ca2fa65.
The vocabulario.json file stores the vocabulary in hexadecimal, the merges, and sample metadata. To load it, convert each key with bytes.fromhex and pass the resulting map to make_text_encoder; reserve the special ID indicated in the file and construct the reverse ID-to-byte mapping for decoding, including the special literal. This distinguishes the model trained here from GPT-2’s official rank set.
Exercises
def get_pair_counts(ids):
pass
def merge(ids, pair, new_id):
passReversibility comes from preserving bytes. Parity with another tokenizer additionally requires the same boundaries, ranks, and special-token policy. Compression is a property measured on a corpus, not a guarantee of model quality.