bobofamilyNIU CHUN
29/44

The Regex Draws the Boundaries, Training Decides Inside: GPT-2 and GPT-4's Split Patterns, and tiktoken

14 MIN—READS

Of the 20 merges part 28 trained on Shakespeare, 8 glue characters of different categories together:

e· t· s· d· y· o· ← word-final letter + space
,· :\n ← punctuation + whitespace

(Here and in the figures, · stands for one space.) GPT’s tokenizer can’t learn tokens like these: it adds a step before BPE, cutting the text into chunks with a regular expression and merging only inside each chunk.

text ──regex split──→ ['Hello', "'ve", '·world', '123', '·how', "'s", '·are', '·you', '!!!?']
BPE runs on each chunk separately; chunks never merge with each other
──→ the chunks' IDs are joined in order

Why chunk first

The GPT-2 paper’s section on input representation (2.2 Input Representation) says that running BPE directly on text learns tokens like dog., dog! and dog? — the same word with different punctuation, each taking a vocabulary slot, so the limited vocabulary and model capacity go to duplicates. So they don’t merge across character categories (letters, digits, punctuation and whitespace are each a category) — in their words, they “prevent BPE from merging across character categories” — with one exception for spaces: a space may join the word after it, which improves compression a lot.

In code this is one regular expression: cut the text into chunks first, then run BPE on each chunk separately. The boundary between two chunks can never form a pair, so it is never merged — e sits at the end of one word and the space after it at the start of the next chunk, so a token like e· can’t be learned.

GPT-2’s split pattern

The pattern lives in encoder.py, part of the GPT-2 code OpenAI published:

import regex as re # not the built-in re, which doesn't understand \p{L}: pip install regex
gpt2pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
print(re.findall(gpt2pat, "Hello've world123 how's are you!!!?"))
# ['Hello', "'ve", ' world', '123', ' how', "'s", ' are', ' you', '!!!?']
  • findall scans left to right; at each position it tries the alternatives separated by | in order, and the first one that matches is cut off as a chunk
  • Notation: \p{L} is a letter in any language (Hanzi included); \p{N} a digit; \s whitespace (space, newline, tab); [^…] “none of these”; a space followed by a question mark means “one space, or none”

Split on |, there are six kinds of chunk:

's|'t|'re|'ve|'m|'ll|'d ① English contractions: how's → how + 's
?\p{L}+ ② optional space + a run of letters → '·world'
?\p{N}+ ③ optional space + a run of digits, any length → '123', '·677'
?[^\s\p{L}\p{N}]+ ④ optional space + a run of punctuation → '!!!?', '·+'
\s+(?!\S) ⑤ a run of whitespace, but the last space is left for the next chunk
\s+ ⑥ whatever whitespace is left, e.g. at the end of the text
  • The optional space at the start of ②③④ is the paper’s exception for spaces: a space can only stick to the front of the following chunk. That is what the end of part 28 meant by GPT-2 “attaching the space to the following word” — GPT-2’s vocabulary has ·egg, and not a single token of letters followed by a trailing space
  • Walk ⑤ through the indent ····if: \s+ first eats all 4 spaces; (?!\S) requires that no non-whitespace character follows, but i does, so it fails; backing off by one, it eats 3 spaces, is followed by a space, and succeeds. That cuts ··· (3 spaces), and ② takes the remaining space with if as ·if — however many spaces come before, the word itself is always the same ·if it would be in ordinary prose

Cutting a few texts

These are the kinds of text the start of the video used to show the quirks:

Egg. I have an egg. EGG! → ['Egg', '.', ' I', ' have', ' an', ' egg', '.', ' EGG', '!']
127 + 677 = 804 → ['127', ' +', ' 677', ' =', ' 804']
if i % 2 == 0: → [' ', ' if', ' i', ' %', ' 2', ' ==', ' 0', ':']
分词是大模型许多怪现象的根源。 → ['分词是大模型许多怪现象的根源', '。']
  • Egg, ·egg and ·EGG are three different chunks: case and a leading space both count, so they come out as different IDs — the “can’t spell” row in part 28
  • ·677 is one chunk, which the learned merges then cut into ·6 and 77. A digit chunk can be any length, and how it ends up cut depends on which merges training happened to learn — that is where part 28’s “bad at arithmetic” row, digits not lining up with place values, comes from
  • ··· is one chunk too, yet GPT-2’s vocabulary has not a single token made of two or more spaces (all 50,257 checked), so it can only split into three 220s — part 28’s “GPT-2 struggles with Python” row
  • Chinese has no spaces, so the whole sentence before the full stop is one letter chunk (Hanzi count as \p{L}). BPE still runs inside the chunk, so chunking doesn’t prevent part 28’s cross-character fragments
  • Karpathy points out two small flaws: contractions are lowercase only (next subsection), and only the straight apostrophe ' counts — with a curly ’, how’s is cut into three chunks, how, ’ and s

Contractions are lowercase only

Contractions are the apostrophe short forms: he’s, don’t, they’re, I’ve, I’m, we’ll, I’d. The pattern’s first rule cuts the apostrophe and what follows into a chunk of its own: how's becomes how and 's, don't becomes don and 't — whatever word 's or 'll follows, it is the same chunk, and the model only has to learn it once.

The trouble is case. GPT-2 wrote 's|'t|'re|'ve|'m|'ll|'d, all lowercase, and a regular expression is case-sensitive by default:

GPT-2 GPT-4
how's how | 's how | 's
HOW'S HOW | ' | S HOW | 'S
DON'T DON | ' | T DON | 'T

An all-caps contraction misses the first rule, so ④ cuts the apostrophe off as punctuation and ② cuts the letters after it: 2 chunks in lowercase, 3 in capitals. The stranded S and T each become a chunk of their own, and the model has to learn separately that “this S belongs to a contraction” — so all-caps text (headings, emphasis) is cut finer in GPT-2. GPT-4 changed the rule to (?i:…), which ignores case inside the brackets. None of these three examples is cut further inside a chunk, so the chunks are the final tokens (checked with tiktoken).


tiktoken and GPT-4’s pattern

tiktoken is OpenAI’s official tokenizer library. It only encodes and decodes — it can’t train:

import tiktoken
enc = tiktoken.get_encoding("gpt2")
print(enc.encode(" hello world!!!")) # [220, 220, 220, 23748, 995, 10185]
enc = tiktoken.get_encoding("cl100k_base")
print(enc.encode(" hello world!!!")) # [262, 24748, 1917, 12340]

cl100k_base is GPT-4’s tokenizer, with a vocabulary of 100,277 — twice GPT-2’s 50,257.

On this line the two patterns produce exactly the same chunks: ···, ·hello, ·world, !!!. The difference is inside a chunk: GPT-2’s 3 spaces stay three 220s, while GPT-4 merges them into a single token, 262. GPT-4’s vocabulary has 85 pure-space tokens (from 2 spaces up to 128), GPT-2’s has none — indents saving tokens is the result of training, not the regex’s doing.

GPT-4’s (cl100k_base) split pattern, as written in the video:

(?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+

Against GPT-2’s, four things changed:

  1. Contractions ignore case: (?i:…), so HOW'S becomes HOW and 'S
  2. Digits go at most 3 to a chunk, with no leading space any more: \p{N}{1,3}. 1234567 is one chunk in GPT-2 but 123, 456, 7 in GPT-4; in 127 + 677 = 804, GPT-4 splits ·677 into a lone space and 677. So in GPT-4 a number of up to three digits is always a whole chunk, and the space before a number is a token of its own
  3. Letters may be preceded by any one symbol, not only a space: [^\r\n\p{L}\p{N}]?\p{L}+, so .append and (y in code are chunks
  4. Punctuation may take the newlines after it, and whitespace running into newlines forms one chunk: [\r\n]*, \s*[\r\n]+

One line of code, with the changes working together:

x = self.append(y)\n\n\nreturn x
GPT-2 chunks: ['x', ' =', ' self', '.', 'append', '(', 'y', ')', '\n\n', '\n', 'return', ' x'] → 12 tokens
GPT-4 chunks: ['x', ' =', ' self', '.append', '(y', ')\n\n\n', 'return', ' x'] → 8 tokens

Every chunk in these two lines is exactly one token. With a coarser pattern and a vocabulary twice the size, GPT-4 uses a third fewer tokens on this line.

The pattern itself is public, but why it was changed is undocumented: claims like “digits in threes help arithmetic” or “whitespace running into newlines helps code” are what Karpathy and the community inferred from the changes themselves.


Hands-on: making part 28’s training merge inside chunks

Only two things change: chunk first, then count chunk by chunk into the same dictionary. Each chunk merges on its own and a chunk boundary never forms a pair, so a token like e· never even gets counted.

There are only two changes: cut into chunks before training, and when counting adjacent pairs go chunk by chunk, adding into the same dictionary. merge is identical to part 28’s.

def train(text, vocab_size, pattern=None):
if pattern is None:
chunks = [text] # no chunking: the whole text is one chunk, as in part 28
else:
chunks = re.findall(pattern, text) # cut into chunks with the regex first
ids = [list(ch.encode("utf-8")) for ch in chunks] # each chunk is its own list of bytes
merges = {}
vocab = {i: bytes([i]) for i in range(256)}
for i in range(vocab_size - 256):
stats = {}
for chunk_ids in ids: # count pairs only inside each chunk, into one dict
get_stats(chunk_ids, stats) # → a chunk boundary never forms a pair
pair = max(stats, key=stats.get)
idx = 256 + i
ids = [merge(chunk_ids, pair, idx) for chunk_ids in ids] # each chunk merges on its own
merges[pair] = idx
vocab[idx] = vocab[pair[0]] + vocab[pair[1]]
n_bytes = len(text.encode("utf-8"))
n_tokens = sum(len(chunk_ids) for chunk_ids in ids)
return merges, vocab, len(chunks), n_bytes / n_tokens

ids changes from one list of IDs into a list of lists, one per chunk.

get_stats gains a counts parameter

def get_stats(ids, counts=None):
counts = {} if counts is None else counts
for pair in zip(ids, ids[1:]):
counts[pair] = counts.get(pair, 0) + 1
return counts

Without counts it makes a new empty dictionary and is used exactly as in part 28; given one, it adds into that dictionary instead and hands it back.

Adding up is exactly what chunking needs: pairs can only be counted inside each chunk, but the counts from all chunks have to be summed to know which pair is most frequent in the whole text. "the the" is cut into 'the' and ' the':

stats = {}
get_stats([116, 104, 101], stats) # {(116, 104): 1, (104, 101): 1}
get_stats([32, 116, 104, 101], stats) # {(116, 104): 2, (104, 101): 2, (32, 116): 1}

(101, 32), which is e·, is never counted: the e ends chunk 1, the space starts chunk 2, and each call only looks inside one chunk.

Why the default is None and not {}: a default argument is created once, when the function is defined, and every call then shares that one object. With counts={}, every call that doesn’t pass the argument would get the same dictionary, and the counts would keep piling up. So None holds the place and a fresh dictionary is made inside the function — minbpe is written the same way.

The counts only pick the next pair

The counts in the dictionary have a single use: max(stats, key=stats.get) finds the most frequent pair, deciding which pair to merge next. The chunked version on Shakespeare:

round 1 (32, 116) ·t 23,837 times → 256
round 2 (104, 101) he 18,203 times → 257 counted afresh
…
round 12 (256, 257) ·the 8,684 times → 267 ·t and he merged again
  • Every round counts afresh: merging changes the sequence, so old pairs vanish and new ones appear — a pair like (256, 104) only exists once 256 does
  • The counts are thrown away after use: the merges table stores only which pair became which ID, and in what order. The counts survive only as that order: the more often a pair occurs, the earlier it merges and the smaller its ID
  • encode ignores the counts: encode also calls get_stats, but only to list the adjacent pairs present; which pair to take is decided by its ID in the merges table (part 28)

The same 20 merges, the result

no chunking (part 28's approach): 1 chunk, compression 1.26x
'e ' 'th' 't ' 's ' 'd ' ', ' 'ou' 'er' 'in' 'y ' 'an' ':\n' 'or' 'o ' 'en' '\n\n' 'ar' ' th' 'on' 'll'
chunked with the GPT-2 pattern first: 297,833 chunks, compression 1.22x
' t' 'he' ' a' 'ou' ' s' ' m' 'in' ' w' 're' 'ha' 'nd' ' the' ' b' 'is' 'or' ' f' 'er' 'll' 'it' 'on'
  • Cross-category tokens like e·, ,· and :\n all disappear, replaced by space-first ones like ·t, ·a and ·s; rule 12 already grows ·the (without chunking, ·th only arrives at rule 18)
  • Compression drops from 1.26 to 1.22: with no merging across chunks, compression gets a little worse, and in exchange every token stays within one character category (a leading space aside)

The figure walks all three rounds through the cat the hat (15 bytes): cut into 4 chunks, 3 rounds learn th (256), the (257) and at (258), and 15 bytes become 9 tokens. Without chunking, round 3’s most frequent pair is the· (257 plus a space, twice), which would merge into a cross-category token.


Does a trait come from the regex, or from training?

The same BPE algorithm throughout; only three things differ: whether to chunk before merging, which pattern chunks, and what data the merges were learned on and how many. Every example in ④ is tagged with the step its difference comes from — indentation is purely training, digits and contractions are the regex.

Tokenizing takes two steps: cut chunks with the regex, then merge inside each chunk following the merge rules. A token never crosses a chunk boundary; how many tokens a chunk finally becomes depends on which merges the vocabulary learned — the regex draws the boundaries, training decides what happens inside. Checking the earlier examples against this:

  • The 4 spaces of an indent: both patterns cut the same chunks, ··· plus ·hello. GPT-2’s vocabulary has no multi-space token, so they split into 3; GPT-4 learned the merge and makes 1 → decided by training
  • 1234567: GPT-4’s pattern first cuts it into 123, 456, 7, and each chunk is exactly one token in the vocabulary → decided by the regex; GPT-2’s pattern doesn’t cut it, so it’s one chunk that the learned merges cut into 123, 45, 67 — that lack of pattern is the result of training
  • HOW'S: three chunks in GPT-2, two in GPT-4, and the whole difference is whether the first rule accepts capitals → decided by the regex
  • This part’s own training row shows best how the two steps work together: the space at the start of a word is a boundary the regex set; that a ·the token grows at all is something training learned

🔑 Faced with a tokenization quirk, first work out whether it comes from chunking or from merging: for the former look at the regex, for the latter at the vocabulary. For GPT-2 and GPT-4 both are public and can be checked directly.

What’s published and what’s inferred

The chunking results and token IDs are hard facts: GPT-2’s split pattern is in the encoder.py OpenAI published, together with its vocabulary files; GPT-4’s cl100k_base (pattern and 100,000-token vocabulary) is right there in tiktoken. What isn’t published is how they were trained — neither the tokenizer training code nor its data. So:

  • “GPT-2’s vocabulary has no multi-space token” is a counted fact; why — whether an extra rule was added during training — can only be inferred
  • “Which four things GPT-4 changed” is a fact from comparing the two patterns; why they were changed is inference

This part adds just one step to part 28: before training, cut the text into chunks with a regex, and do all the pair counting and merging inside chunks. In exchange every token falls within one character category, at the price of a little compression. How a text finally gets cut: the regex sets the boundaries, training decides inside them.

🔮 The second half of 1.3: a line-by-line read of OpenAI’s encoder.py, special tokens (ones like <|endoftext|> that never go through BPE merging), and the minbpe exercise — writing a GPT-4 tokenizer of your own.