トークン

読了まで約36 分分、9 節 節の 7 例 例。

第2026.11.16版 2026年11月19日時点で例が通過 86 例中 86 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.16)から翻訳した。 原文を読む

この章を終えると、バイト対符号化(byte-pair encoding)のトークナイザをゼロから構築し、各語彙サイズに要するコストを測定して語彙サイズを選び、オープンな言語モデルのトークナイザを読んで、その統合規則を手作業で適用できるようになる。本書の以降のすべてのモデルは、ここで構築するトークナイザを通して、ストアのテキストを読む。

ストアは家具と家庭用品をオンラインで販売しており、商品名と商品説明は、どのモデルが読むよりも前に、いくつかの断片に切り分けなければならない。第1章では、商品名を単語に切り分けた。テキストには、単語の間と句読点の周りにすでに空白があるからである。この選択は手早く済んだが、二つの点で不十分であった。第一に、バイグラムモデルは、訓練中に一度も見なかった単語、たとえば barstools に確率を与えることができず、そのために破綻した。第二に、chair と chairs、あるいは 48 と 49 を無関係な単語として扱い、一方について学習した内容が他方に引き継がれなかった。

トークンとは、言語モデルが読み、予測する単位であり、モデルがテキストを目にする前に、そのテキストを切り分けたものを指す。第一の問題はトークンの選び方に由来するので、この章ではトークンを定める。第二の問題の解決にはトークンだけでは足りず、第4章で扱う。この章では、ストアのテキストをトークンに切り分ける三つの方法を測定する。単語、文字、そして、オープンな生成モデルの多くが用いる中間的な方法であるバイト対符号化である。そのうえで、それらのモデルのトークナイザの一つを開いて、分解して調べる。

単語は隙間を残す

最終変更:版2026.11.11

テキストを単語に区切ると、モデルは意味を担うトークンを得られる。第1章がそこから始まったのはこのためである。その代償が語彙である。モデルが予測できるのは語彙、すなわち学習テキストから得たトークンの集合に含まれるトークンだけである。そのため、学習後にはじめて現れる単語には手が届かない。これが語彙外の単語である。名前、数値、新製品を含むテキストには、語彙外の単語が必ずいくつか存在する。

検証用の名前とは、どのモデルも学習に用いない、ストアの商品の10%である。モデルが未知のテキストをどう扱うかを調べるために取り分けてある。この名前を見ると、単語単位の方式がどこまで不十分かが分かる。学習用の名前に一度も現れない検証用の単語を数え、珍しい単語と普通の単語に分類する。

unseen-words.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 合格
"""Counts the validation words that the training names never use, then sorts them into rare words and ordinary ones.The share never seen in training is the line to read."""from collections import Counterfrom lib.store import is_ordinary, load_products, wordstrain_words = Counter(w for name in load_products("train")["name"] for w in words(name))   # words() splits on spaces: the store's text is already spaced around punctuationvalidation = [w for name in load_products("validation")["name"] for w in words(name)]unseen = [w for w in validation if w not in train_words]print("different words in training names:", f"{len(train_words):,}")print("words seen once in training:", f"{sum(1 for n in train_words.values() if n == 1):,}")print("validation words:", f"{len(validation):,}")print("validation words never seen in training:", f"{len(unseen):,}")print("share never seen in training:", f"{len(unseen) / len(validation):.1%}")# is_ordinary, from lib.store: true for a word, or each part of a hyphenated one, used in at least 30 training descriptions; numbers and punctuation count as ordinaryprint("share of them that are rare words, most often product lines' names:",      f"{sum(not is_ordinary(w) for w in unseen) / len(unseen):.0%}")print("most frequent of the ordinary ones:", ", ".join(w for w, _ in Counter(w for w in unseen if is_ordinary(w)).most_common(6)))
出力python unseen-words.py
different words in training names: 25,907
words seen once in training: 17,242
validation words: 29,054
validation words never seen in training: 2,109
share never seen in training: 7.3%
share of them that are rare words, most often product lines' names: 92%
most frequent of the ordinary ones: neutral, noise-free, details, spacious, 52.4, houses

検証用の単語のうち、学習に一度も現れないものは7.3%であり、そのうち92%が珍しい単語である。その多くは製品ラインの名前であり、第1章では[name]と表示される。残りは、たまたま学習用の名前に含まれなかった普通の単語であり、たとえばneutralやnoise-freeがある。単語単位のモデルは、これらをどれも予測できない。これらを含むテキストは、特別な処理なしには採点できない。またnoise-freeを、モデルがよく知っているnoiseやfreeと関連づけることもできない。

学習データを増やせば隙間は小さくなるが、閉じることはない。カタログには製品ラインが追加され続けるからである。学習用の名前に含まれる25,907種類の単語のうち、17,242は一度しか現れない。これは製品ラインや型番ではよくあることであり、一度しか見ていない単語からモデルが学べることは、もともとほとんどない。

実践ルール: 単語をトークンに選ぶ前に、保持しておいたデータでテキストの語彙外率を測る。目安として、ストアの名前のように、保持データの単語の1、2パーセントを超えるものが未知であれば、単語をトークンに使ってはならない。コマンドの固定集合のように語彙が閉じているテキストには、単語トークンは引き続き妥当である。

この部分はまだ翻訳されていないため、英語で表示している。

Characters cover everything

最終変更:版2026.11.11

Going to the other extreme fixes the gap. If every character is a token, the vocabulary is tiny and almost nothing is out of it: a new product line is spelled with the same letters as an old one. The price is length. Each word becomes several tokens, so the model has more steps to predict, and the context it needs, such as the start of a product's name, is many more tokens back.

Test whether characters close the gap for the store's names. Compare the characters in training and validation names, and count the validation names' tokens both ways:

character-tokens.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 合格
"""Compares the characters of the training names with those of the validation names, and counts the validation tokensboth ways. Its characters-per-word line is the one to read."""import unicodedatafrom lib.store import load_products, wordstrain_names, validation_names = load_products("train")["name"], load_products("validation")["name"]characters = {c for name in train_names for c in name}     # a set: each distinct character onceunseen = {c for name in validation_names for c in name} - charactersword_tokens = sum(len(words(name)) for name in validation_names)   # a word is a token here, as in chapter 1character_tokens = sum(len(name) for name in validation_names)     # len counts the spaces too, as charactersprint("different characters in training names:", len(characters))print("validation characters never seen in training:", len(unseen))print("they are:", ", ".join(unicodedata.name(c).lower() for c in sorted(unseen)))   # printed by Unicode name, because a soft hyphen itself prints as nothingprint("validation tokens as words:", f"{word_tokens:,}")print("validation tokens as characters:", f"{character_tokens:,}")print("characters per word:", round(character_tokens / word_tokens, 1))
出力python character-tokens.py
different characters in training names: 86
validation characters never seen in training: 2
they are: soft hyphen, latin small letter t with cedilla
validation tokens as words: 29,054
validation tokens as characters: 174,142
characters per word: 6.0

Characters rarely miss, but they make the text long. Only 2 characters in the validation names never appear in the training names. As words, the validation names are 29,054 tokens; as characters, 174,142, or 6.0 characters for each word, counting the spaces. A model reading characters has to predict c, o, f, f, e, e before it gets to the point where a word model starts: knowing that table is likely next.

Characters also leave a last, small gap. The 2 unseen characters are a soft hyphen and a t with a cedilla, and a character tokenizer can't spell a word that contains one. Open models close that gap by working with bytes instead: in UTF-8, the usual text encoding, every character in every language is stored as one to four bytes, and there are only 256 possible byte values, so a vocabulary that starts from all 256 can represent any text at all (Radford et al., 2019, section 2.2). The tokenizer read later in this chapter does exactly that.

Longer sequences cost in two ways. Every step a model takes is computation, so 6.0 times as many steps means at least 6.0 times the work, and more for the models of later chapters, whose cost grows faster than the length. And every model in this book looks back over a limited window of tokens; in characters, that window covers that many times fewer words.

Working rule: Use characters as tokens only for small experiments, or as a fallback inside a larger scheme, as the next sections do. Check how many characters per word your text has, since that factor multiplies every sequence length and every training step.

最頻出のペアを繰り返し統合する

最終変更:版2026.11.11

単語は粗すぎ、文字は細かすぎる。そこで、SmolLM2 をはじめとする多くのオープンな生成モデルが使う手法は、その中間に位置する。バイトペア符号化(byte-pair encoding、BPE)は文字から出発し、最も頻繁に現れるペアからより大きなトークンを作り上げる。もとはデータ圧縮の手法であり、Sennrich、Haddow、Birch が、翻訳モデル向けに単語を断片へ分割する用途に応用した(Sennrich et al., 2016)。アルゴリズムは短い。

  1. 訓練テキストの各単語を文字に分けて表記し、末尾に </w> を付ける。これにより、統合がある単語と次の単語を結びつけることはない。
  2. 隣り合うシンボルのペアをすべて数える。このとき、各単語をその出現頻度で重み付けする。
  3. 最も頻繁なペアを、あらゆる箇所で 1 つの新しいシンボルに統合し、語彙に加える。
  4. 手順 2 に戻り、望む語彙サイズに達するまで繰り返す。

学習された順に並べた統合のリストが、そのままトークナイザである。単語を符号化するには、その単語を文字に分けて表記し、同じ順序で統合を適用する。

訓練用の名前に対して 8 回の統合を手作業で実行すれば、すべての手順を示すのに十分である。統合のたびに結果を出力し、最後の行に 8 回すべての後で table がどう表記されるかを示す。

merge-pairs-by-hand.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 合格
"""Runs the merge algorithm by hand on the training names for eight merges, printing each one and how table is spelledafterwards. Those eight merges are the ones to read; the example asserts they match lib.bpe.train."""from collections import Counterfrom lib import bpefrom lib.store import load_products, wordsword_counts = Counter(w for name in load_products("train")["name"] for w in words(name))spelled = {w: list(w) + ["</w>"] for w in word_counts}       # every word as characters, plus an end markerlearned = []for step in range(1, 9):    pairs = Counter()    for w, syms in spelled.items():                           # count every adjacent pair of symbols        for pair in zip(syms, syms[1:]):            pairs[pair] += word_counts[w]                     # each pair weighted by how often its word occurs    best = min(pairs, key=lambda p: (-pairs[p], p))           # the most frequent pair; ties go to the pair that sorts first    for w, syms in spelled.items():                           # replace it everywhere with one new symbol        merged, i = [], 0        while i < len(syms):            if syms[i:i + 2] == list(best):                   # the pair starting at position i is the one being merged                merged.append(syms[i] + syms[i + 1])          # its two symbols, joined into the one new symbol                i += 2            else:                merged.append(syms[i])                i += 1        spelled[w] = merged    learned.append(best)    print(f"merge {step}: {best[0]!r} + {best[1]!r} -> {best[0] + best[1]!r}  ({pairs[best]:,} times)")print("table spelled now:", spelled["table"])assert learned == bpe.train(word_counts, 8)                   # lib.bpe.train, the fast version, learns the same eight merges
出力python merge-pairs-by-hand.py
merge 1: 'e' + '</w>' -> 'e</w>'  (35,498 times)
merge 2: 'r' + '</w>' -> 'r</w>'  (24,635 times)
merge 3: 'i' + 'n' -> 'in'  (21,312 times)
merge 4: 'd' + '</w>' -> 'd</w>'  (20,216 times)
merge 5: 't' + '</w>' -> 't</w>'  (18,628 times)
merge 6: 'a' + 'n' -> 'an'  (15,697 times)
merge 7: 'e' + 'r</w>' -> 'er</w>'  (12,981 times)
merge 8: 's' + 't' -> 'st'  (12,781 times)
table spelled now: ['t', 'a', 'b', 'l', 'e</w>']

最初の統合では、末尾記号が一般的な語末の文字に結び付く。たとえば e と </w> である。店の語の多くが e、r、d で終わるためである。続いて、語の内部にある一般的な断片、たとえば in、an、st が現れる。8 回の統合の後、table は t a b l e</w> と表記される。まだ大半が文字のままである。統合が数千回に及べば、table のような一般的な単語は 1 つのトークンになり、まれな単語は、他の単語と共有される断片に分割されたままとなる。

これが第 1 章の最初の問題を解く考え方である。頻出する単語は専用のトークンを持つので、系列は短くなる。まれな単語や新しい単語は、モデルがすでに見た断片から綴られるため、訓練テキストに含まれる文字で書ける単語はすべて扱える。BPE は 2 つ目の問題を解決しない。次の節で示すように、頻出する単語とその複数形は、それぞれが共通点のない 1 つのトークンになりうる。

実践ルール: 統合は、他のモデルと同様に訓練分割だけから学習し、統合の順序を保持すること。符号化はその順序に依存するためである。同じ頻度のペアが並ぶ場合は固定の規則で決着をつけ、同じテキストからは常に同じトークナイザが得られるようにする。

店舗のトークナイザを学習する

最終変更:版2026.11.11

前の節のアルゴリズムは、マージのたびにすべてのペアを数え直す。マージが8回であれば問題ないが、数千回になると遅すぎる。本書の共有モジュール lib.bpe は同じアルゴリズムを実行するが、ペアの数え上げは1回だけで済ませ、各マージの後にはそのマージで変化した単語だけを更新する。さらに、カウントをヒープに保持し、最も頻度の高いペアが常に先頭にくるようにしている。このため、数千回のマージを数秒で学習でき、得られるマージは単純な版と同じである。手書きの例では、8回のマージが lib.bpe.train のものと一致することをアサートしている。

店舗のトークナイザは、学習用の商品名と説明文をまとめて使い、4,000回のマージを学習する。本書のモデルが両方から学習するためである。短いテキストを5つ用意した。2つは商品名、3つは単語の組である。これらを使って、未知の単語や似た単語をどう扱うかを示す。

store-tokenizer.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 合格
"""Learns 4,000 merges from the training names and descriptions, then encodes five short texts with the resultingtokenizer. Read the vocabulary size and the tokens of each text, which the prose cites."""from collections import Counterfrom lib import bpefrom lib.store import load_products, wordstrain = load_products("train")word_counts = Counter(w for text in train["name"] + " " + train["description"] for w in words(text))   # names and descriptions, read as one texttokenizer = bpe.Tokenizer(bpe.train(word_counts, merges=4000), bpe.alphabet(word_counts))   # the merges, then the characters they start fromprint("different words in training text:", f"{len(word_counts):,}")print("characters and the end marker:", len(bpe.alphabet(word_counts)))print("tokens in the vocabulary:", f"{len(tokenizer.vocabulary):,}")# an unseen word, a word and its plural, digits, and a hyphenated word, in that orderfor name in ["set of 2 barstools", "sled coffee table", "chair chairs", "48 49", "noise noise-free"]:    print(name, "->", " ".join(tokenizer.encode(name)))
出力python store-tokenizer.py
different words in training text: 49,315
characters and the end marker: 137
tokens in the vocabulary: 4,138
set of 2 barstools -> set</w> of</w> 2</w> bar stools</w>
sled coffee table -> sled</w> coffee</w> table</w>
chair chairs -> chair</w> chairs</w>
48 49 -> 48</w> 4 9</w>
noise noise-free -> noise</w> no i se -free</w>

一般的な単語はそのまま1つのトークンになり、未知の単語にも綴りが与えられる。sled coffee table は単語ごとに1つずつ、計3つのトークンになる。barstools という語は、学習用の商品名に含まれないため、第1章のバイグラムモデルでは扱えなかった。これは bar と stools</w> に分かれる。どちらもトークナイザがよく知っている断片である。学習テキストには異なる単語が 49,315 個あり、トークナイザの語彙には 4,138 個のトークンがある。その内訳は、学習テキストの 137 個の文字と終端記号、4,000回のマージそれぞれに対応する新しいトークン1個ずつ、そして学習テキストに一度も現れなかった任意の文字を表す <unk> である。

出力の最後の3行は、BPEが行わないことを示している。chair と chairs はどちらも一般的な語なので、それぞれが丸ごと1つのトークンになり、2つのトークンには共通部分がない。48 は1つのトークンであり、49 は 4 と 9</w> の2つである。また、noise-free は noise と共通部分をもたない断片に分かれる。トークンが与えるのはすべての単語の綴りであり、意味ではない。トークンどうしを関連づけるのは第4章の役割である。

モデルは、新しい商品ラインとは何かを学習しなければならない。それでも、少なくともそれを予測し、確率を与えることはできる。

実践ルール: トークナイザは、モデルが学習するのと同じテキストで学習する。ここでは商品名と説明文をまとめて用いる。そうすれば、そのテキストで頻出する単語が単一のトークンになる。トークナイザは1度だけ構築し、比較するすべてのモデルで使う。本書のモデルはすべて、lib.bpe.store_tokenizer() を通して店舗のテキストを読む。

マージ回数を選ぶ

最終変更:版2026.11.16

前の節では4,000回のマージを用いた。本節ではその理由を示す。マージ回数は語彙サイズを決めるものであり、BPEトークナイザーにおける実質的に唯一の選択である。マージを増やすと系列は短くなり、計算量が減る。しかし、新しいトークンはそれぞれより稀なテキストを担うことになる。学習テキストに数回しか現れないトークンは、モデルが学ぶための材料が少なすぎる。これは稀な単語の問題と同じものが、別の場所に現れたものにほかならない。

16,000回のマージを一度だけ学習し、そのうち最初の0回、1,000回、2,000回、4,000回、8,000回、16,000回を取り出すと、六つのトークナイザーが得られる。長い学習の最初のk回のマージは、kマージの学習で得られるマージと完全に一致する。それぞれに三つの指標を求める。学習テキストで使われる異なるトークンの数、検証用の各単語が何トークンになるか、そして、それらの異なるトークンのうち学習テキストでの出現が20回未満のものの割合である。テキストが使う異なるトークンを、そのテキストのトークン型と呼ぶ。表を読む前に、両端でそれぞれ何が見えるはずかを考えておく。

vocabulary-size.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 合格
"""Learns 16,000 merges once, then reads the first 0, 1,000, 2,000, 4,000, 8,000 and 16,000 of them as six tokenizers.Each row of the table measures one of them; the printed lines at the ends and at 4,000 merges are what the prose cites."""from collections import Counterfrom lib import bpefrom lib.store import load_products, wordstraining, validation = load_products("train"), load_products("validation")counts = Counter(w for text in training["name"] + " " + training["description"] for w in words(text))merges = bpe.train(counts, merges=16000)             # the first k merges of a longer run are a k-merge tokenizervalidation_words = [w for text in validation["name"] + " " + validation["description"] for w in words(text)]results = {}print(f"{'merges':>6}  {'tokens used':>11}  {'tokens per word':>15}  {'rare types':>10}")for k in [0, 1000, 2000, 4000, 8000, 16000]:    tokenizer = bpe.Tokenizer(merges[:k], bpe.alphabet(counts)) if k else None   # with no merges, a word is just its characters    encode = tokenizer.encode_word if k else bpe.symbols    seen = Counter(t for w, n in counts.items() for t in encode(w) for _ in range(n))   # each word's tokens, counted as often as the word occurs    per_word = sum(len(encode(w)) for w in validation_words) / len(validation_words)    rare = sum(1 for n in seen.values() if n < 20) / len(seen)   # rare: seen fewer than 20 times in the training text    print(f"{k:>6,}  {len(seen):>11,}  {per_word:>15.2f}  {rare:>10.0%}")    results[k] = per_word, rareprint("tokens per word at 4,000 merges:", f"{results[4000][0]:.2f}")print("rare token types with characters only:", f"{results[0][1]:.0%}")print("rare token types at 4,000 merges:", f"{results[4000][1]:.0%}")print("rare token types at 16,000 merges:", f"{results[16000][1]:.0%}")
出力python vocabulary-size.py
merges  tokens used  tokens per word  rare types
     0          137             5.61         49%
 1,000        1,130             1.71          7%
 2,000        2,123             1.42          5%
 4,000        4,099             1.22          6%
 8,000        8,007             1.10         13%
16,000       15,517             1.05         53%
tokens per word at 4,000 merges: 1.22
rare token types with characters only: 49%
rare token types at 4,000 merges: 6%
rare token types at 16,000 merges: 53%

ストアのトークナイザーは、系列が短く、稀なトークンが少ない位置にある。4,000回のマージでは、検証用の単語は平均で1.22トークンになり、トークン型のうち稀なものは6%であって、2,000回のときとほぼ同程度に少ない。

マージがない場合、すべてのトークンは1文字であるから、トークンは高頻度だが単語は長くなる。1単語が平均で5トークンを超え、トークン型のうち稀なものは49%である。これは説明文に珍しい文字が含まれているためである。マージが多い場合は、単語は短くなるが稀な型が積み上がる。8,000回のマージから稀なものの割合は上昇し、16,000回では53%となる。追加されたマージの大半が、学習テキストにほとんど含まれない単語を対象にしているためである。

語彙サイズは、モデルの大きさの一部も決める。第5章以降のニューラル言語モデルは、語彙中のすべてのトークンについて数値のベクトルを保持し、予測の各ステップで語彙中のすべてのトークンのスコアを計算する。語彙が4倍になれば、学習すべきベクトルも、各ステップで計算すべきスコアも、テキストによらず4倍になる。本書でノートパソコン上で学習させる小さなモデルにとって、このコストは系列の長さと同じくらい重要である。

そこでストアのトークナイザーは4,000回のマージを用いる。それを超えると、マージ1回あたりに得られる系列の短縮はわずかになる一方で、本書の小さなモデルでは十分に学習できないトークンが加わる。大規模なオープンモデルは数万以上のトークンからなる語彙を用いており、SmolLM2の語彙は49,152である。これらのモデルははるかに多くのテキストから学習するため、より稀なトークンでも十分な頻度で現れる。

実践ルール: マージ回数は、学習テキストでの稀なトークン型の割合と、保持したテキストでの単語あたりのトークン数を測定して選ぶ。単語あたりのトークン数があまり下がらなくなり、稀な型が増え始める地点で止める。語彙は学習テキストの量に合わせて調整する。経験則として、数百万語程度の小さなモデルには、数万ではなく数千回のマージが適している。

オープンモデルのトークナイザを読む

最終変更:版2026.11.12

オープンな言語モデルは、重みの隣にトークナイザをファイルとして添えて配布される。それを読むと、同じ考え方をより大きな規模で見ることができ、さらにストアのトークナイザでは選ぶ必要のなかった選択もいくつか見られる。本書では SmolLM2 を用いる。SmolLM2 は Hugging Face が公開しているオープンな言語モデルであり、重みもトークナイザも Apache 2.0 ライセンスの下で誰でもダウンロードできる(モデルカード)。本書はそのトークナイザファイルの写しを examples/data/smollm2-tokenizer/ に置いている。このファイルは prep/smollm2_tokenizer.py により固定したリビジョンで取得されるので、例はオフラインで実行できる。例では、このファイルの作成に用いられたライブラリである tokenizers(0.23.3)を使って読み込む。

3 つの商品名を両方のトークナイザでエンコードし、検証用の名前 1 件あたりのトークン数をそれぞれ数える。

smollm2-tokens.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 · tokenizers 0.23.3 合格
"""Encodes three product names with SmolLM2's tokenizer and with the store's, then counts the tokens per validation nameand per word each way. Read the tokens per validation name, which the prose cites."""from tokenizers import Tokenizerfrom lib import bpefrom lib.store import load_productssmollm2 = Tokenizer.from_file("data/smollm2-tokenizer/tokenizer.json")   # the book's pinned copy of the file, read from examples/store = bpe.store_tokenizer()print("SmolLM2 vocabulary:", f"{smollm2.get_vocab_size():,}")for name in ["set of 2 barstools", "6.5 qt . slow cooker", "48 '' wide genuine leather wingback chair"]:    print(name)    print("  SmolLM2:", " ".join(smollm2.encode(name).tokens))   # .tokens gives the pieces as text; .ids would give their numbers    print("  store:  ", " ".join(store.encode(name)))names = load_products("validation")["name"]print("tokens per validation name, SmolLM2:", round(sum(len(smollm2.encode(n).ids) for n in names) / len(names), 2))print("tokens per validation name, store:", round(sum(len(store.encode(n)) for n in names) / len(names), 2))print("tokens per validation name, words:", round(sum(len(n.split()) for n in names) / len(names), 2))   # split() on spaces: the store's wordsprint("sled at the start of a text:", " ".join(smollm2.encode("sled coffee table").tokens))print("sled after a space:", " ".join(smollm2.encode(" sled coffee table").tokens))   # the same name, after a spacewords_total = sum(len(n.split()) for n in names)print("SmolLM2 tokens per word:", round(sum(len(smollm2.encode(n).ids) for n in names) / words_total, 2))
出力python smollm2-tokens.py
SmolLM2 vocabulary: 49,152
set of 2 barstools
  SmolLM2: set Ġof Ġ 2 Ġbar st ools
  store:   set</w> of</w> 2</w> bar stools</w>
6.5 qt . slow cooker
  SmolLM2: 6 . 5 Ġq t Ġ. Ġslow Ġcooker
  store:   6.5</w> qt</w> .</w> slow</w> cooker</w>
48 '' wide genuine leather wingback chair
  SmolLM2: 4 8 Ġ'' Ġwide Ġgenuine Ġleather Ġwing back Ġchair
  store:   48</w> ''</w> wide</w> genuine</w> leather</w> wingback</w> chair</w>
tokens per validation name, SmolLM2: 10.53
tokens per validation name, store: 9.91
tokens per validation name, words: 6.79
sled at the start of a text: s led Ġcoffee Ġtable
sled after a space: Ġsled Ġcoffee Ġtable
SmolLM2 tokens per word: 1.55

SmolLM2 の語彙は 49,152 トークンであり、ストアのトークナイザの 4,138 トークンと比べて大きい。これは、家具の名前よりはるかに多くのテキストで学習されたためである。出力には、特に挙げておくべき違いが 3 つある。

  • 空白がトークンの一部になる。 Ġ は空白を表す。Ġtable は、直前に空白を伴う "table" である。ストアのトークナイザの </w> のように単語の終わりを印で示す代わりに、このトークナイザは各単語の先頭の空白を保持する。そのため、空白も含めてテキストを正確に復元できる。
  • 数字は 1 桁ごとに別のトークンになる。 48 は 4 と 8 になり、6.5 は 6、.、5 になる。数字を分割すると、各々が数回しか現れない数値で語彙が埋まるのを防げ、すべての数を同じ方法で扱える。
  • テキストの先頭にある単語は前に空白がないため、別のトークンになる。 SmolLM2 の語彙には Ġsled が 1 つのトークンとして含まれるが、空白のない sled は含まれない。そのため、sled で始まる名前は s と led になる。これは出力の最後の数行に示されている。また、barstools は SmolLM2 の語彙に単語全体としては含まれず、bar、st、ools に分割される。これは出力の最初の数行に示されている。

自分のテキストで学習したトークナイザは、そのテキストに対してわずかに優れた結果を出す。検証用の名前 1 件あたりのトークン数は、ストアのトークナイザでは 9.91、SmolLM2 では 10.53 であり、単語数は 6.79 である。この差が生じるのは、一つには、ストアのトークナイザが数を桁に分割しないためである。もう一つには、SmolLM2 が、空白の後に続くすべての数の前に独立した Ġ トークンを使い、さらに、前に空白のない各名前の最初の単語を分割するためである。

実践ルール: オープンモデルのトークナイザを使うときは、常に配布されたとおりに使うこと。モデルは、学習したトークンしか理解できない。コンテキスト長やコストの予算を見積もるときは、単語ではなく、そのトークナイザでトークンを数えること。限られた種類のテキストで自分のモデルを学習するときは、そのテキストで自分のトークナイザも学習すること。

SmolLM2 のマージを手作業で適用する

最終変更:版2026.11.11

SmolLM2 のトークナイザファイルは、一見するとブラックボックスのようである。しかし、そこに収められているのは、ストアのトークナイザと同じもの、つまり順序付きのマージのリストであることがわかれば、見通しがよくなる。このファイルである tokenizer.json には、ここで重要な部分が三つある。一つ目はプリトークナイザである。これは、マージを行う前にテキストを断片に分割する。例が名前を挙げて出力するその処理手順では、まず数字を一桁ずつ分割し、次に先頭の空白を付けたまま単語を分割し、さらにすべてのバイトを表示可能な文字に対応付ける。Ġ はこの対応付けに由来する。この対応付けは GPT-2 の bytes_to_unicode である(GPT-2 のエンコーダ)。二つ目は、学習された順にランク付けされたマージのリストである。三つ目は語彙であり、各トークンに番号を与える。

このファイルのマージを確かめよう。三つの商品名について、ライブラリのプリトークナイザが出力した断片を手作業でマージする。このとき、ストアのトークナイザと同じく、最も早く学習されたペアから先にマージする。その結果をライブラリのトークンと比較する。

merges-by-hand.py Python 3.12.15 · tokenizers 0.23.3 合格
"""Applies SmolLM2's learned merges by hand, earliest first, to the pieces its pre-tokenizer makes of three product names.The example asserts that the tokens match the library's, which the prose cites."""import jsonfrom tokenizers import Tokenizersmollm2 = Tokenizer.from_file("data/smollm2-tokenizer/tokenizer.json")   # the book's pinned copy, read from examples/spec = json.load(open("data/smollm2-tokenizer/tokenizer.json", encoding="utf-8"))rank = {tuple(m.split(" ")): i for i, m in enumerate(spec["model"]["merges"])}   # lower rank: learned earlier; the file stores each merge as "a b"def merge(piece):                                    # apply the learned merges, earliest first, until none applies    syms = list(piece)    while len(syms) > 1:        pairs = [(rank.get(p, len(rank)), i) for i, p in enumerate(zip(syms, syms[1:]))]   # a pair with no merge ranks after all of them        best, i = min(pairs)                         # the earliest-learned pair; on a tie, the leftmost        if best == len(rank):            break        syms[i:i + 2] = [syms[i] + syms[i + 1]]      # the symbols at i and i + 1, joined into one    return symsfor name in ["set of 2 barstools", "sled coffee table", "6.5 qt . slow cooker"]:    # pre_tokenize_str returns (piece, offsets) pairs; only the pieces are merged    pieces = [p for p, _ in smollm2.pre_tokenizer.pre_tokenize_str(name)]       # split into words, digits and bytes    by_hand = [token for piece in pieces for token in merge(piece)]    print(name, "->", " ".join(by_hand))    assert by_hand == smollm2.encode(name).tokens    # the library's tokens for the same namesteps = [step["type"] for step in spec["pre_tokenizer"]["pretokenizers"]]assert spec["pre_tokenizer"]["pretokenizers"][0]["individual_digits"]   # the Digits step comes first, and splits digits one at a timeprint("pre-tokenizer steps:", ", ".join(steps))
出力python merges-by-hand.py
set of 2 barstools -> set Ġof Ġ 2 Ġbar st ools
sled coffee table -> s led Ġcoffee Ġtable
6.5 qt . slow cooker -> 6 . 5 Ġq t Ġ. Ġslow Ġcooker
pre-tokenizer steps: Digits, ByteLevel

手作業で作ったトークンは、三つの名前のすべてでライブラリのものと一致する。例では、この一致をアサートで確認している。SmolLM2 のトークナイザがこれらの名前に対して行う処理は、これですべてである。このトークナイザは特殊トークンも定義しており、特殊トークンはこれらの処理より前に照合される。プリトークナイザと学習用テキストはストアのものと異なるが、最も早く学習されたペアを繰り返しマージしてテキストを符号化する点は、ストアのトークナイザと同じである。

一致を確認する価値があるのは、テキストの分割方法に生じるわずかな違いが、後段の処理に影響するためである。あるトークナイザで学習したモデルに別のトークナイザのトークンを与えても、すべてのトークン番号は有効なので、エラーは出ないまま、モデルは意味をなさない入力を読むことになる。トークナイザのあるバージョンが別のバージョンと、空白や数字の扱いで異なる場合にも同じことが起こり、しかも気づきにくい。

実践ルール: トークナイザはモデルの一部として扱う。モデルと同じバージョンで管理し、モデル自身のファイルから読み込み、どちらかをアップグレードするたびに自分のテキストでテストする。同じテキストに対して二つのトークナイザが一つのトークンでも食い違う場合は、それらのトークナイザに基づいて作られたモデルの出力を信頼する前に、原因を突き止める。

本番環境で何が問題になるか

トークンはモデルが何を見ることができるかを決めるものであり、トークナイザーに起因する問題の多くは、トークナイザーから遠く離れた場所で表面化する。

  • トークナイザーの不一致は、エラーを出さずに失敗する。 別のトークナイザーのトークン番号を与えられたモデルは、有効な番号を読み取るものの、その意味を取り違え、自信ありげな無意味な出力を生成する。トークナイザーのファイルをモデルとともに配布し、両者を組み合わせてテストすること。
  • コストはトークン単位で計算される。 コンテキストの上限もトークン単位の価格も、単語ではなくトークンに対して適用される。ストアの商品名は、SmolLM2 のトークナイザーでは1単語あたり 1.55 トークンになる。数字、コード、他の言語を多く含むテキストでは、これより多くなる。自分のテキストで計測すること。
  • 数値の扱いは難しい。 数字を1桁ずつ分割するトークナイザーでは、モデルは 48 を2つのトークンとして扱って推論する。分割しないトークナイザーでは、48 と 49 は互いに無関係なトークンになる。どちらの場合も、モデルは寸法や数量を単語より扱いにくいと想定し、それらを別に検査すること。
  • 特殊トークンは入力できてしまう。 オープンなモデルは、テキストの開始や終了、会話のターンを、<|endoftext|> のような文字列で書かれた特殊トークンで示す。ユーザーが入力したテキストにこうした文字列が含まれ、トークナイザーがそれを特殊トークンに変換すると、モデルはユーザーが送れるはずのない制御信号を読み取ってしまう。信頼できないテキストに含まれる特殊トークンの文字列を、トークナイザーがどう扱うかを確認すること。
  • 新しいテキストは学習時のテキストから乖離する。 昨年のカタログで学習したトークナイザーは、今年の商品ラインをより多くの断片に分割する。新しいテキストについて、1単語あたりのトークン数を随時計測すること。数値が着実に上昇していれば、トークナイザーがテキストの変化に追いつけなくなっている。

この章で決めたこと

  • 本書のモデルは、店舗のテキストをバイトペア符号化のトークンとして読む。 単語を用いた場合は、検証用の単語のうち 7.3% が語彙に含まれず、文字を用いた場合は、系列の長さが単語の 6.0 倍になった。BPE はこの両方を避けられる。訓練テキストに含まれる文字で綴られた単語であれば、どれでも符号化でき、よく使われる単語は 1 個のトークンになる。ただし、chair と chairs のように、単語どうしの関係を捉えることはしない。それは第 4 章の役割である。
  • 店舗のトークナイザーは、訓練用分割の名称と説明から 4,000 回のマージを学習する。 この処理は lib.bpe.store_tokenizer() で行う。この規模では、1 単語あたりの平均は 1.22 トークンであり、出現が少なすぎて学習できないトークン種はほとんどない。マージ回数をさらに増やしても、系列はわずかにしか短くならず、まれなトークンが多数加わる。
  • 各単語の末尾に </w> を付けるため、マージが単語をまたぐことはない。 SmolLM2 などの公開モデルでは、代わりに空白を次の単語に付ける。どちらの方式も、単語の境界をモデルから見える状態に保つ。
  • 公開モデルは、常にそのモデル自身のトークナイザーとともに使う。 モデルが理解できるのは、訓練で用いられたトークン番号だけである。そのため、第 10 章では、この章で詳しく調べたトークナイザーを使って SmolLM2 のモデルを読み込む。本書における公開モデルの記録には、いずれも使用したトークナイザーを明記してある。
  • 異なるトークナイザー間のパープレキシティは比較できない。 より小さなトークンをより多く予測するモデルは、ステップ数が増え、同じテキストでもパープレキシティが異なる。そのため、本書のモデルの比較にはすべて店舗のトークナイザーを使う。第 3 章では、そのトークンを用いて比較を最初からやり直す。

この版における本章

第2026.11.16版2026年11月19日時点で例が通過この章の7 例件のうち7件が合格

英語版の書籍(版2026.11.16)から翻訳した。

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全11章中の第2章: トークン

  1. 単語は隙間を残す
  2. Characters cover everything
  3. 最頻出のペアを繰り返し統合する
  4. 店舗のトークナイザを学習する
  5. マージ回数を選ぶ
  6. オープンモデルのトークナイザを読む
  7. SmolLM2 のマージを手作業で適用する
  8. 本番環境で何が問題になるか
  9. この章で決めたこと

ページの先頭に戻るすべての章