MAX guide 16 min read

SentencePiece Tutorial: Train a Tokenizer in Python and Compare It With tiktoken

Max unrolls paper tape over his open palm beside a bar cut in three and one whole bar: "it shows how your text gets cut"

How do you train a SentencePiece tokenizer and check how it splits your text?

Run SentencePiece, Google’s tokenizer library, on one plain-text file to train a tokenizer: the program that cuts text into tokens, the pieces a language model reads. Then encode a test sentence and count tokens per word.

It shows how your text gets cut: in “How many r’s are in strawberry?”, our 8k tokenizers split strawberry into three pieces, OpenAI’s keep it whole. On a MacBook Air M4 each training took under 1.1 seconds; the English-trained 8k ones needed 2.16 to 2.28 times as many tokens for Slovak as for English.

A tokenizer is trained on a large text before the model. It fixes the vocabulary, every token it knows, and each token’s id (its number). The model sees only ids and learns an embedding, a list of numbers, for each. This first stage is tokenizer architecture; the rest is transformer architecture.

The tokenizer is why one prompt counts differently on different models. See also: more limits of tokenizers.

Step 1: Install the three libraries

SentencePiece and Hugging Face Tokenizers both train tokenizers. tiktoken trains nothing for production: it encodes with OpenAI’s ready-made tokenizers, called encodings, and is our yardstick. Install them in a virtual environment, Python 3.10 or newer:

# Install (macOS, Python 3.13.14; any Python >= 3.10):
#   python3 -m venv venv
#   ./venv/bin/pip install -r requirements.txt
# Direct dependencies (what the scripts import):
sentencepiece==0.2.3
tokenizers==0.23.3
tiktoken==0.14.0

Keep the pins: the live Tokenizers docs describe a newer release candidate.

Step 2: Get the training and test texts

Train on Shakespeare’s complete works (Project Gutenberg #100, public domain): save https://gutenberg.pglaf.org/1/0/100/100-0.txt as dl/gutenberg/pg100.txt. Compare languages on FLORES-200, the same sentences in many languages (CC-BY-SA 4.0): unpack https://dl.fbaipublicfiles.com/nllb/flores200_dataset.tar.gz inside dl/flores/.

prep_corpus.py (scripts at the end) writes both into corpus/.

Step 3: Train SentencePiece BPE and Unigram

Byte pair encoding (BPE) starts from characters and repeats a merge: the two neighbouring pieces seen together most often become one. Unigram starts from many candidate pieces and prunes them down to vocab_size. More: how BPE and Unigram build a vocabulary; WordPiece, a third way, is not in SentencePiece.

def train(model_type, vocab_size, hard_vocab_limit=True):
    prefix = MODELS / f"spm_{model_type}_{vocab_size}"
    t0 = time.perf_counter()
    spm.SentencePieceTrainer.train(
        input=str(CORPUS),
        model_prefix=str(prefix),
        model_type=model_type,      # "bpe" or "unigram"
        vocab_size=vocab_size,
        byte_fallback=True,         # unseen characters become UTF-8 bytes, not <unk>
        minloglevel=1,              # print warnings and errors only
        hard_vocab_limit=hard_vocab_limit,  # False: vocab_size becomes an upper bound
    )
    return time.perf_counter() - t0, prefix

The script’s loop trains both at a small and a large size. Against the defaults:

  • model_type: default unigram, so ask for "bpe".
  • byte_fallback: off by default; on, a character outside the vocabulary becomes one piece per byte.
  • hard_vocab_limit: on by default; the large Unigram fails with it (see Mistakes).

SentencePiece marks spaces with ▁. Output (real_vocab: vocabulary built; runs_s: seconds per run):

spm bpe     vocab= 8000 hard_limit=True real_vocab=8000 runs_s=[0.15, 0.15, 0.16] median_s=0.15 model_bytes=366768
spm unigram vocab= 8000 hard_limit=True real_vocab=8000 runs_s=[1.07, 1.04, 1.04] median_s=1.04 model_bytes=379199
spm bpe     vocab=32000 hard_limit=True real_vocab=32000 runs_s=[0.17, 0.17, 0.17] median_s=0.17 model_bytes=779233
spm unigram vocab=32000 hard_limit=False real_vocab=24611 runs_s=[0.78, 0.78, 0.77] median_s=0.78 model_bytes=665699

Step 4: Train byte-level BPE in HF Tokenizers

Byte-level BPE, the method GPT-2 introduced, starts from byte values, not characters, so no character is unknown. Step 5 compares yours with GPT-2’s.

def train(vocab_size):
    tok = Tokenizer(models.BPE())
    tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)  # GPT-2 style: bytes, space glued to the next word
    tok.decoder = decoders.ByteLevel()
    trainer = trainers.BpeTrainer(vocab_size=vocab_size, show_progress=False,
                                  initial_alphabet=pre_tokenizers.ByteLevel.alphabet())  # all 256 bytes in the vocab
    t0 = time.perf_counter()
    tok.train([str(CORPUS)], trainer)
    return time.perf_counter() - t0, tok

Ġ marks the space before a word. It prints:

hf  bpe-bytelevel vocab= 8000 real_vocab=8000 runs_s=[0.44, 0.4, 0.4] median_s=0.40 json_bytes=528579
hf  bpe-bytelevel vocab=32000 real_vocab=32000 runs_s=[0.58, 0.62, 0.58] median_s=0.58 json_bytes=2252881

Step 5: Encode the strawberry question

encode.py (it downloads GPT-2’s tokenizer, so it needs internet) runs How many r's are in strawberry?, a question about letters, through your six tokenizers, GPT-2’s, and the encodings cl100k_base (GPT-4) and o200k_base (GPT-4o).

for name in ("cl100k_base", "o200k_base"):
    enc = tiktoken.get_encoding(name)
    print(f"tiktoken {name} n_vocab={enc.n_vocab}")
    tokenizers[f"tiktoken-{name}"] = tt_tok(enc)
Tokenizer (vocabulary)strawberry in the question
SentencePiece BPE 8k▁straw ber ry
SentencePiece Unigram 8k▁straw be rry
HF byte-level BPE 8kĠstraw ber ry
SentencePiece BPE 32k▁straw berry
SentencePiece Unigram (24,611)▁strawberr y
HF byte-level BPE 32kĠstraw berry
GPT-2Ġstrawberry
cl100k_base (100,277)strawberry
o200k_base (200,019)strawberry

In this question, the ready-made tokenizers keep strawberry, together with the space before it, as one token, so the model receives one id for it, not its letters.

In this run, the larger vocabularies cut strawberry into fewer pieces.

Step 6: Count tokens per word in five languages

per_language.py counts tokens per word on the same sentences:

words = {l: sum(len(s.split()) for s in lines[l]) for l in LANGS}  # words = whitespace-separated pieces
print("sentences per language:", len(lines["eng"]), "| words:", words)
print(f"{'tokenizer':26}" + "".join(f"{l:>16}" for l in LANGS))
for name, count in counters.items():
    tokens = {l: sum(count(s) for s in lines[l]) for l in LANGS}
    cells = [f"{tokens[l] / words[l]:5.2f} ({tokens[l] / tokens['eng']:4.2f}x)" for l in LANGS]
    print(f"{name:26}" + "".join(f"{c:>16}" for c in cells))
Tokens per word, 405 sentencesEnglishGermanSpanishSlovakHindiSlovak ÷ English, total tokens (not per word)
SentencePiece BPE 8k1.883.502.784.5213.172.16
SentencePiece Unigram 8k1.974.013.205.0013.172.28
HF byte-level BPE 8k1.863.492.754.4813.102.16
cl100k_base1.271.991.632.945.072.08
o200k_base1.251.631.382.291.681.66

Trained on English, our tokenizers need more tokens elsewhere: on the same sentences the three 8k ones took 2.16 to 2.28 times as many tokens for Slovak as for English. Shakespeare has no Hindi script, so almost every Hindi character becomes several byte tokens. One small set of sentences shows only the direction.

Mistakes to avoid

  • The apostrophe became the byte piece <0x27>. The text has tens of thousands of curly ’ and a single straight ', so the default character_coverage dropped it; the docs advise 1.0 for English.
  • Unigram failed at the large size. Set hard_vocab_limit=False; vocab_size becomes a ceiling:
RuntimeError: INTERNAL: /Users/runner/work/sentencepiece/sentencepiece/src/trainer_interface.cc(744) [(trainer_spec_.vocab_size()) == (model_proto->pieces_size())] Vocabulary size too high (32000). Please set it to a value <= 24611.
  • Publishing a tokenizer trained on private text. Its .model and .vocab files may leak information about the training data (the SentencePiece docs warn that someone could test whether a given text was in the training data).

If you only wanted to train a SentencePiece tokenizer and check it, you can stop here.

How long each training took

Median of three runs on the MacBook Air M4, CPU only, on the 5.4 MB Shakespeare text. Another text or machine gives other times. The sentences-per-second figure in the SentencePiece README is segmentation speed, how fast a trained model cuts text, not training speed.

TokenizerRequested vocabularyReal vocabularyMedian (s)Model file (bytes)
SentencePiece BPE8,0008,0000.15366,768
SentencePiece Unigram8,0008,0001.04379,199
HF byte-level BPE8,0008,0000.40528,579 (JSON)
SentencePiece BPE32,00032,0000.17779,233
SentencePiece Unigram32,00024,6110.78665,699
HF byte-level BPE32,00032,0000.582,252,881 (JSON)

Unigram took longest at the small size. We did not measure why; its training scores and prunes candidates over several rounds, while BPE only adds merges.

Check BPE by hand: ten merges in pure Python

toy_bpe.py checks that Hugging Face BPE does what Step 3 describes. A plain-Python trainer learns ten merges on a toy text of twelve words built from straw, berry, raw and draw; Hugging Face BPE trains on the same text. Both learn the same ten merges in the same order, ending with strawberry as one piece:

alphabet: abderstwy (9 letters)
 1  pure=a+w        hf=a+w        same
 2  pure=r+aw       hf=r+aw       same
 3  pure=e+r        hf=e+r        same
 4  pure=b+er       hf=b+er       same
 5  pure=r+y        hf=r+y        same
 6  pure=s+t        hf=s+t        same
 7  pure=ber+ry       hf=ber+ry       same
 8  pure=st+raw      hf=st+raw      same
 9  pure=d+raw      hf=d+raw      same
10  pure=straw+berry    hf=straw+berry    same
hf merges learned: 10 | hf encodes 'strawberry' as ['strawberry']

In steps 1, 4 to 7 and 9 several pairs are equally frequent. Our first version picked the alphabetically first pair and differed from Hugging Face in steps 5 to 7.

Hugging Face picked the pair whose pieces have the lower ids: letters are numbered alphabetically, new pieces in the order they appear. Its documentation does not state this rule; we observed it on one toy text.

SentencePiece and tiktoken in real models

The papers behind Meta’s Llama 2 and Google’s Gemma 3 both name SentencePiece as the tokenizer; Gemma 3 shares its tokenizer with Gemini 2.0.

tiktoken encodes and decodes with OpenAI’s encodings; encoding_for_model picks the right one by model name. Training exists only as an educational helper, train_simple_encoding() in tiktoken._educational, says the tiktoken README.

You can wrap your own byte-level BPE in tiktoken.Encoding. No documented converter turns a SentencePiece .model file into one. Meta’s Llama 3 reference code uses the tiktoken library and loads its tokenizer file from a path with load_tiktoken_bpe; it does not call cl100k_base or o200k_base by name.

What comes after the tokenizer has its own topic pages: attention, decoder-only models and encoder-decoder models.

The full scripts

Save the files in one folder, create the dl/ downloads from Step 2 next to them, and run them with the venv’s Python in this order: prep_corpus.py, train_spm.py, train_hf.py, encode.py, per_language.py, toy_bpe.py. The scripts write corpus/ and models/ into the same folder.

# Install (macOS, Python 3.13.14; any Python >= 3.10):
#   python3 -m venv venv
#   ./venv/bin/pip install -r requirements.txt
# Direct dependencies (what the scripts import):
sentencepiece==0.2.3
tokenizers==0.23.3
tiktoken==0.14.0
# Full pip freeze of the venv the run used (transitive dependencies):
# anyio==4.16.0
# certifi==2026.11.20
# charset-normalizer==3.5.3
# click==8.5.1
# filelock==4.3.2
# fsspec==2026.9.0
# h11==0.16.0
# hf-xet==1.8.0
# httpcore2==2.17.0
# httpx2==2.17.0
# huggingface_hub==2.5.0
# idna==3.20
# packaging==26.4
# PyYAML==6.0.4
# regex==2026.12.2
# requests==2.34.2
# tqdm==4.70.1
# truststore==0.10.5
# typing_extensions==4.16.0
# urllib3==2.8.0
"""Prepare the two corpora: Shakespeare (training) and a filtered FLORES-200 devtest slice (tokens per word)."""
import csv, hashlib, re
from pathlib import Path

WORK = Path(".")
DL = WORK / "dl"
CORPUS = WORK / "corpus"
CORPUS.mkdir(exist_ok=True)

def sha(p):
    return hashlib.sha256(p.read_bytes()).hexdigest()

# 1. Shakespeare: keep only the text between the Gutenberg START and END markers.
raw = (DL / "gutenberg/pg100.txt").read_text(encoding="utf-8")
body = raw.split("*** START OF THE PROJECT GUTENBERG EBOOK 100 ***")[1].split("*** END OF THE PROJECT GUTENBERG EBOOK 100 ***")[0]
train = CORPUS / "shakespeare.txt"
train.write_text(body.strip() + "\n", encoding="utf-8")
print(f"shakespeare.txt bytes={train.stat().st_size} lines={body.count(chr(10))} sha256={sha(train)}")

# 2. FLORES-200 devtest: keep a sentence only if its topic is on the allow list
#    AND its English text has no word from the block list (content boundary: no health, law, money, crime...).
ALLOW = re.compile(r"travel|touris|sport|geograph|sailing|nature|wildlife|big cats|music|entertainment|food|weather|"
                   r"animal|dinosaur|solar|moon|rocket|astronom|photograph|violin|pencil|how things work|rail|transport", re.I)
BLOCK = re.compile(r"health|disease|medic|doctor|hospital|drug|virus|vaccin|patient|illness|injur|death|died|dead|kill|"
                   r"law|legal|court|police|crime|criminal|arrest|prison|bank|money|financ|insur|payment|tax|employ|"
                   r"hiring|surveil|murder|war\b|weapon|bomb|attack|abuse|victim|assault|sexual|survivor|investigat|gymnast|harass|credit|checkpoint|\bpa(y|id)\b|price|cost", re.I)
FL = DL / "flores/flores200_dataset"
meta = list(csv.DictReader(open(FL / "metadata_devtest.tsv", encoding="utf-8"), delimiter="\t"))
langs = {"eng": "eng_Latn", "deu": "deu_Latn", "spa": "spa_Latn", "slk": "slk_Latn", "hin": "hin_Deva"}
text = {k: (FL / f"devtest/{v}.devtest").read_text(encoding="utf-8").splitlines() for k, v in langs.items()}
keep = [i for i, m in enumerate(meta) if ALLOW.search(m["topic"]) and not BLOCK.search(text["eng"][i])]
print(f"flores devtest sentences={len(meta)} kept={len(keep)}")
for k in langs:
    out = CORPUS / f"flores_{k}.txt"
    out.write_text("\n".join(text[k][i] for i in keep) + "\n", encoding="utf-8")
    print(f"flores_{k}.txt bytes={out.stat().st_size} sha256={sha(out)}")
for name in ["gutenberg/pg100.txt", "flores/flores200_dataset.tar.gz"]:
    p = DL / name
    print(f"source {name} bytes={p.stat().st_size} sha256={sha(p)}")
"""Train SentencePiece BPE and Unigram tokenizers on one English corpus; time each run (median of 3 when under 10 s)."""
import statistics, time
from pathlib import Path
import sentencepiece as spm

WORK = Path(".")
CORPUS = WORK / "corpus/shakespeare.txt"
MODELS = WORK / "models"
MODELS.mkdir(exist_ok=True)

def train(model_type, vocab_size, hard_vocab_limit=True):
    prefix = MODELS / f"spm_{model_type}_{vocab_size}"
    t0 = time.perf_counter()
    spm.SentencePieceTrainer.train(
        input=str(CORPUS),
        model_prefix=str(prefix),
        model_type=model_type,      # "bpe" or "unigram"
        vocab_size=vocab_size,
        byte_fallback=True,         # unseen characters become UTF-8 bytes, not <unk>
        minloglevel=1,              # print warnings and errors only
        hard_vocab_limit=hard_vocab_limit,  # False: vocab_size becomes an upper bound
    )
    return time.perf_counter() - t0, prefix

for vocab_size in (8000, 32000):
    for model_type in ("bpe", "unigram"):
        # Unigram 32 000 on this corpus fails with hard_vocab_limit=True ("Vocabulary size too high ... <= 24611").
        hard = not (model_type == "unigram" and vocab_size == 32000)
        secs, prefix = train(model_type, vocab_size, hard)
        runs = [secs]
        if secs < 10:
            runs += [train(model_type, vocab_size, hard)[0] for _ in range(2)]
        size = Path(f"{prefix}.model").stat().st_size
        real = spm.SentencePieceProcessor(model_file=f"{prefix}.model").get_piece_size()
        print(f"spm {model_type:7} vocab={vocab_size:5} hard_limit={hard} real_vocab={real} runs_s={[round(r, 2) for r in runs]} "
              f"median_s={statistics.median(runs):.2f} model_bytes={size}")
"""Train a byte-level BPE tokenizer with Hugging Face Tokenizers on the same English corpus; median of 3 runs."""
import statistics, time
from pathlib import Path
from tokenizers import Tokenizer, decoders, models, pre_tokenizers, trainers

WORK = Path(".")
CORPUS = WORK / "corpus/shakespeare.txt"
MODELS = WORK / "models"
MODELS.mkdir(exist_ok=True)

def train(vocab_size):
    tok = Tokenizer(models.BPE())
    tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)  # GPT-2 style: bytes, space glued to the next word
    tok.decoder = decoders.ByteLevel()
    trainer = trainers.BpeTrainer(vocab_size=vocab_size, show_progress=False,
                                  initial_alphabet=pre_tokenizers.ByteLevel.alphabet())  # all 256 bytes in the vocab
    t0 = time.perf_counter()
    tok.train([str(CORPUS)], trainer)
    return time.perf_counter() - t0, tok

for vocab_size in (8000, 32000):
    runs, tok = [], None
    for _ in range(3):
        secs, tok = train(vocab_size)
        runs.append(secs)
    path = MODELS / f"hf_bpe_{vocab_size}.json"
    tok.save(str(path))
    print(f"hf  bpe-bytelevel vocab={vocab_size:5} real_vocab={tok.get_vocab_size()} runs_s={[round(r, 2) for r in runs]} "
          f"median_s={statistics.median(runs):.2f} json_bytes={path.stat().st_size}")
"""Encode one sentence with every tokenizer; print pieces, ids, count, and the pieces that cover two target words."""
from pathlib import Path
import sentencepiece as spm
import tiktoken
from tokenizers import Tokenizer

WORK = Path(".")
MODELS = WORK / "models"
TEXT = "How many r's are in strawberry?"
TARGETS = ["strawberry", "r's"]

def spm_tok(path):
    sp = spm.SentencePieceProcessor(model_file=str(path))
    def run(text):
        m = sp.encode(text, return_type="offset_mapping")  # dict: ids, pieces, (start, end) character offsets
        return [(p, i, a, b) for p, i, (a, b) in zip(m["pieces"], m["ids"], m["offsets"])]
    return run

def hf_tok(tok):
    def run(text):
        enc = tok.encode(text)
        return [(t, i, a, b) for t, i, (a, b) in zip(enc.tokens, enc.ids, enc.offsets)]
    return run

def tt_tok(enc):
    def run(text):
        ids = enc.encode(text)
        _, starts = enc.decode_with_offsets(ids)
        ends = starts[1:] + [len(text)]
        return [(enc.decode_single_token_bytes(i), i, a, b) for i, a, b in zip(ids, starts, ends)]
    return run

tokenizers = {}
for kind in ("bpe", "unigram"):
    for v in (8000, 32000):
        tokenizers[f"spm-{kind}-{v}"] = spm_tok(MODELS / f"spm_{kind}_{v}.model")
for v in (8000, 32000):
    tokenizers[f"hf-bpe-bytelevel-{v}"] = hf_tok(Tokenizer.from_file(str(MODELS / f"hf_bpe_{v}.json")))
tokenizers["hf-gpt2 (from_pretrained 'gpt2')"] = hf_tok(Tokenizer.from_pretrained("gpt2"))
for name in ("cl100k_base", "o200k_base"):
    enc = tiktoken.get_encoding(name)
    print(f"tiktoken {name} n_vocab={enc.n_vocab}")
    tokenizers[f"tiktoken-{name}"] = tt_tok(enc)

print(f"TEXT = {TEXT!r}\n")
for name, run in tokenizers.items():
    pieces = run(TEXT)
    print(f"== {name}  count={len(pieces)}")
    print("   pieces:", [p for p, _, _, _ in pieces])
    print("   ids:   ", [i for _, i, _, _ in pieces])
    for word in TARGETS:
        s = TEXT.index(word); e = s + len(word)
        cover = [p for p, _, a, b in pieces if a < e and b > s]  # every piece that overlaps the word
        print(f"   {word!r:13} -> {cover}")
    print()

# The same word without the leading space, as it appears at the start of a text or after a quote mark.
for word in ("strawberry", "Strawberry"):
    print(f"== {word!r} alone")
    for name, run in tokenizers.items():
        print(f"   {name:34} {[p for p, _, _, _ in run(word)]}")
"""Tokens per word on the same sentences in five languages (FLORES-200 devtest slice), per tokenizer."""
from pathlib import Path
import sentencepiece as spm
import tiktoken
from tokenizers import Tokenizer

WORK = Path(".")
LANGS = ["eng", "deu", "spa", "slk", "hin"]
lines = {l: (WORK / f"corpus/flores_{l}.txt").read_text(encoding="utf-8").splitlines() for l in LANGS}

counters = {}
for kind in ("bpe", "unigram"):
    for v in (8000, 32000):
        sp = spm.SentencePieceProcessor(model_file=str(WORK / f"models/spm_{kind}_{v}.model"))
        counters[f"spm-{kind}-{v}"] = lambda s, sp=sp: len(sp.encode(s))
for v in (8000, 32000):
    hf = Tokenizer.from_file(str(WORK / f"models/hf_bpe_{v}.json"))
    counters[f"hf-bpe-bytelevel-{v}"] = lambda s, hf=hf: len(hf.encode(s).ids)
for name in ("cl100k_base", "o200k_base"):
    enc = tiktoken.get_encoding(name)
    counters[f"tiktoken-{name}"] = lambda s, enc=enc: len(enc.encode(s))

words = {l: sum(len(s.split()) for s in lines[l]) for l in LANGS}  # words = whitespace-separated pieces
print("sentences per language:", len(lines["eng"]), "| words:", words)
print(f"{'tokenizer':26}" + "".join(f"{l:>16}" for l in LANGS))
for name, count in counters.items():
    tokens = {l: sum(count(s) for s in lines[l]) for l in LANGS}
    cells = [f"{tokens[l] / words[l]:5.2f} ({tokens[l] / tokens['eng']:4.2f}x)" for l in LANGS]
    print(f"{name:26}" + "".join(f"{c:>16}" for c in cells))
print("cell = tokens per word (total tokens of this language / total tokens of English, same sentences)")
"""Minimal BPE trainer in pure Python on a toy corpus, then the same corpus through Hugging Face Tokenizers."""
import json
from collections import Counter

CORPUS = "strawberry straw berry raw straw draw berry strawberry raw drawer straw berry"
STEPS = 10

# ---- pure Python BPE (no end-of-word marker; a merge never crosses a space) ----
words = Counter(CORPUS.split())                       # word -> frequency
splits = {w: list(w) for w in words}                  # word -> current pieces
token_id = {c: i for i, c in enumerate(sorted(set(CORPUS) - {" "}))}  # letters first, new tokens get the next id

def pair_counts():
    counts = Counter()
    for w, freq in words.items():
        p = splits[w]
        for a, b in zip(p, p[1:]):
            counts[(a, b)] += freq
    return counts

def show():
    return " ".join("·".join(splits[w]) for w in CORPUS.split())

print("start:   ", show())
merges = []
for step in range(1, STEPS + 1):
    counts = pair_counts()
    # most frequent pair; on a tie, the pair with the lower token ids (observed HF behaviour, not documented)
    best = min(counts, key=lambda pair: (-counts[pair], token_id[pair[0]], token_id[pair[1]]))
    merges.append(best)
    token_id[best[0] + best[1]] = len(token_id)
    for w, p in splits.items():                        # replace every (a, b) with "ab", left to right
        i, out = 0, []
        while i < len(p):
            if i + 1 < len(p) and (p[i], p[i + 1]) == best:
                out.append(p[i] + p[i + 1]); i += 2
            else:
                out.append(p[i]); i += 1
        splits[w] = out
    print(f"merge {step:2}: {best[0]} + {best[1]} (count {counts[best]})  ->  {show()}")

# ---- the same corpus through Hugging Face Tokenizers BPE ----
from tokenizers import Tokenizer, models, pre_tokenizers, trainers
tok = Tokenizer(models.BPE())
tok.pre_tokenizer = pre_tokenizers.Whitespace()
alphabet = sorted(set(CORPUS.replace(" ", "")))
tok.train_from_iterator([CORPUS], trainers.BpeTrainer(vocab_size=len(alphabet) + STEPS, show_progress=False))
hf_merges = [tuple(m.split(" ")) if isinstance(m, str) else tuple(m) for m in json.loads(tok.to_str())["model"]["merges"]]
print("\nalphabet:", "".join(alphabet), f"({len(alphabet)} letters)")
for i, (ours, hf) in enumerate(zip(merges, hf_merges), 1):
    print(f"{i:2}  pure={ours[0]}+{ours[1]:8} hf={hf[0]}+{hf[1]:8} {'same' if ours == hf else 'DIFFERENT'}")
print("hf merges learned:", len(hf_merges), "| hf encodes 'strawberry' as", tok.encode("strawberry").tokens)

Cheat sheet

The article on one page: open it full size, save it or share it.

Tokenizer cheat sheet: pinned install, SentencePiece and HF training code, strawberry splits, M4 times, tokens/word, mistakes
PNG

AI-assisted content, human-reviewed. Images AI-generated. Editorial Standards · Our Editors