Token

閱讀約需 34 分鐘 分鐘,9 節 中共有 7 個範例。

版次 2026.11.16 範例於 2026年11 月 19 通過測試 86 個範例中有 86 個通過 變更內容

由 AI 翻譯。經人工以英文驗證。 我們如何製作書籍

譯自英文書,版次 2026.11.16。 閱讀原文

讀完本章後,你將能從零開始建構一個位元組對編碼(byte-pair encoding)的 tokenizer,透過衡量各種詞彙表大小所付出的代價來選定詞彙表大小,並且能讀懂一個開放語言模型的 tokenizer,讀到足以用手動方式套用它的合併規則。本書其餘各章中的每一個模型,都是透過你在此建構的 tokenizer 來讀取商店的文字。

這家商店在線上販售家具與家居用品,它的商品名稱與商品描述必須先切成片段,模型才能讀取。第 1 章把商品名稱切成單字,因為文字中的單字之間與標點符號周圍原本就有空格。這個選擇很快速,但在兩方面有所不足。其一,二元語法模型無法為訓練時從未見過的單字(例如 barstools)給出任何機率,因而失效。其二,它把 chair 與 chairs,或 48 與 49,視為互不相關的單字,對其中一個學到的內容無法帶到另一個。

token 是語言模型讀取與預測的單位:也就是文字在模型看到之前被切成的片段。第一個問題源自 token 的選擇,因此本章要處理的就是 token。第二個問題需要的不只是 token 所能提供的,將在第 4 章討論。本章衡量三種把商店文字切成 token 的方式:單字、字元,以及大多數開放生成式模型採用的折衷做法,也就是位元組對編碼。接著,本章會打開其中一個模型的 tokenizer,並將它拆解開來。

以詞為單位會留下缺口

最近一次變動於第 2026.11.11 版

將文字切成詞,能讓模型得到帶有意義的詞元,這也是第 1 章從這裡開始的原因。代價在於詞彙表。模型只能預測其詞彙表(vocabulary,即模型從訓練文字中學到的詞元集合)內的詞元,因此任何在訓練之後才首次出現的詞都無法處理,這種詞稱為詞彙表外詞(out-of-vocabulary word)。在包含名稱、數字與新產品的文字中,這類詞總是存在。

驗證用的名稱,是商店商品中保留下來的 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 個只出現一次,這在產品系列與型號中很常見,而只見過一次的詞,本來就幾乎無法讓模型從中學到什麼。

實用原則: 在選擇以詞作為詞元之前,先用保留資料量測你的文字的詞彙表外詞比率。經驗法則是,如果保留資料中未見過的詞超過百分之一或二,如同這家商店的名稱,就不要以詞作為詞元。對於詞彙封閉的文字,例如一組固定的指令,以詞作為詞元仍然合理。

字元涵蓋一切

最近一次變動於第 2026.11.11 版

走向另一個極端可以補上這個缺口。如果每個字元都是一個詞元,詞彙表就會很小,幾乎沒有任何內容會落在詞彙表之外:新的產品線與舊的產品線使用相同的字母拼寫。代價是長度。每個單字會變成數個詞元,因此模型要預測的步數更多,而它所需要的上下文,例如產品名稱的開頭,也在更多個詞元之前。

測試字元是否能補上商店名稱的缺口。比較訓練名稱與驗證名稱中的字元,並以兩種方式計算驗證名稱的詞元數:

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

字元很少遺漏,但會讓文字變長。驗證名稱中只有 2 個字元從未出現在訓練名稱中。以單字計,驗證名稱有 29,054 個詞元;以字元計,則有 174,142 個,也就是每個單字 6.0 個字元(包含空格)。讀取字元的模型必須先預測 c、o、f、f、e、e,才能到達單字模型開始的位置:得知接下來很可能是 table。

字元還留下最後一個小缺口。這 2 個未見過的字元是軟連字號,以及帶有下加符的 t,字元分詞器無法拼出含有它們的單字。開放模型改用位元組來彌補這個缺口:在常用的文字編碼 UTF-8 中,每種語言的每個字元都以一到四個位元組儲存,而位元組的可能值只有 256 種,因此從全部 256 個值出發的詞彙表可以表示任何文字(Radford et al., 2019,第 2.2 節)。本章稍後讀到的分詞器正是這樣做的。

較長的序列會在兩方面付出代價。模型的每一步都是運算,所以步數變成 6.0 倍,運算量至少就是 6.0 倍;對於後續各章的模型,成本的成長快於長度,增加的幅度更大。此外,本書中的每個模型回看的詞元視窗都有限;以字元計算時,這個視窗涵蓋的單字數會少那麼多倍。

實用原則: 只在小型實驗中,或作為較大方案中的後備手段時,才以字元作為詞元,如接下來幾節所做的那樣。請檢查你的文字平均每個單字有多少字元,因為這個倍數會乘上每個序列的長度與每一個訓練步驟。

一再合併最常出現的字元對

最近一次變動於第 2026.11.11 版

以詞為單位太粗,以字元為單位又太細,因此多數開放生成式模型(包括 SmolLM2)採用的方法介於兩者之間。位元組對編碼(byte-pair encoding,BPE)從字元出發,把最常一起出現的字元對逐步合併成更大的詞元。它原本是一種資料壓縮方法,Sennrich、Haddow 與 Birch 將它改造成把詞切成片段的方法,用於翻譯模型(Sennrich et al., 2016)。這個演算法很簡短:

  1. 把訓練文字中的每個詞拆成字元,並在詞尾標上 </w>,如此合併就不會把一個詞與下一個詞接在一起。
  2. 計算每一組相鄰符號對的次數,每個詞依其出現頻率加權。
  3. 把最常出現的字元對在各處合併為一個新符號,並加入詞彙表。
  4. 從步驟 2 重複,次數等於你想要的詞彙表大小。

依學得的順序排列的合併清單,就是分詞器。要編碼一個詞,就先把它拆成字元,再依相同順序套用這些合併。

在訓練用的名稱上以手動方式執行八次合併,就足以展示每一個步驟。每次合併發生時都會印出,最後一行顯示八次合併後 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。八次合併之後,table 被拼成 t a b l e</w>:大部分仍是字元。若合併數千次,像 table 這樣的常見詞會成為單一詞元,而罕見詞則仍被切成與其他詞共用的片段。

這個想法解決了第 1 章的第一個問題。常見的詞有自己的詞元,所以序列保持簡短。罕見詞與新詞則由模型見過的片段拼成,因此只要詞中的字元出現在訓練文字裡,任何詞都能處理。BPE 沒有解決第二個問題:如下一節所示,一個常見詞與它的複數形式可能各自成為完整的詞元,彼此毫無共通之處。

**實用原則:**只用訓練切分來學習合併,如同對待其他任何模型一樣,並保留合併的順序,因為編碼取決於這個順序。對於頻率相同的字元對,以固定規則決定先後,讓相同的文字永遠得到相同的分詞器。

訓練商店的分詞器

最近一次變動於第 2026.11.11 版

上一節的演算法在每次合併之後都會重新計算所有字元對的次數,合併八次還可以,合併數千次就太慢了。本書的共用模組 lib.bpe 執行相同的演算法,但只計算一次字元對,之後每次合併只更新被該次合併改變的單字,並把次數存放在堆積(heap)中,使最常見的字元對始終位於最上方。它能在數秒內學會數千次合併,而且得到的合併結果與單純版本相同:手寫的範例斷言其八次合併與 lib.bpe.train 一致。

商店的分詞器從訓練用的名稱與描述中一併學習 4,000 次合併,因為本書的模型會同時從兩者學習。以下五段短文字包含兩個產品名稱和三組詞語,用來顯示分詞器如何處理未見過的單字與相似的單字:

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>

常見的單字會完整輸出,而未見過的單字仍然會得到一種拼寫方式。sled coffee table 是三個詞元,每個單字一個。單字 barstools 是第 1 章的二元語法模型無法處理的,因為訓練用的名稱中從未出現過它;它被拆成 bar 與 stools</w>,這兩個片段都是分詞器熟悉的。訓練文字中有 49,315 個不同的單字,而分詞器的詞彙表有 4,138 個詞元:包括訓練文字的 137 個字元與結尾標記、每次合併各新增的一個詞元(共 4,000 次),以及 <unk>,它代表訓練文字中從未出現過的任何字元。

輸出的最後三行顯示 BPE 做不到的事。chair 與 chairs 都很常見,因此各自成為一個完整的詞元,而這兩個詞元之間沒有任何共通之處。48 是一個詞元,49 則是兩個,即 4 與 9</w>。而 noise-free 被拆成的片段,與 noise 沒有任何共通之處。詞元只給每個單字一種拼寫,並不給它意義;建立詞元之間的關聯是第 4 章的工作。

模型仍然必須學會什麼是新的產品系列,但它至少能夠預測這樣的產品系列,並給出機率。

**實用原則:**以模型將要學習的相同文字來訓練分詞器,此處是名稱與描述合併,使該文字中的常見單字成為單一詞元。只建立一次,並用於你所比較的每個模型;本書的模型都透過 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 次合併時差不多。

完全不合併時,每個詞元都是一個字元,因此詞元很常見,但詞很長:一個詞需要超過五個詞元,而稀有詞元型別的比例為 49%,這是因為描述文字中含有不常見的字元。合併很多時,詞很短,但稀有型別大量堆積:從 8,000 次合併起,稀有比例開始攀升,到 16,000 次時為 53%,這是因為多出來的合併大多涵蓋了訓練文字中幾乎不存在的詞。

詞彙表大小也決定了模型的一部分規模。神經語言模型(從第 5 章起)會為詞彙表中的每個詞元儲存一個數值向量,並在每一步預測時為詞彙表中的每個詞元計算分數。詞彙表大四倍,要學習的向量就多四倍,每一步要計算的分數也多四倍,與文字內容無關。對於本書在筆記型電腦上訓練的小型模型,這項成本和序列長度同樣重要。

因此商店的分詞器採用 4,000 次合併:超過這個數目,每次合併換來的長度縮減有限,卻會增加一個本書的小型模型學不好的詞元。大型開放模型使用數萬個詞元甚至更多的詞彙表,SmolLM2 的詞彙表有 49,152 個,這是因為它們學習的文字多得多,即使是較稀有的詞元也出現得夠頻繁。

**實用原則:**以測量來決定合併次數:在訓練文字上測量稀有詞元型別的比例,在保留的文字上測量每詞的詞元數;當每詞的詞元數不再明顯下降、而稀有型別開始攀升時就停下來。詞彙表的大小要隨訓練文字的多寡調整;經驗上,在幾百萬個詞上訓練的小型模型,適合數千次合併,而不是數萬次。

讀取開放模型的分詞器

最近一次變動於第 2026.11.12 版

開放語言模型會把分詞器做成檔案,與權重一同發布。讀取這類檔案,能在更大的規模上看到相同的概念,也能看到商店分詞器不必做的幾項選擇。本書使用 SmolLM2,這是 Hugging Face 的開放語言模型,任何人都能下載它的權重與分詞器,授權為 Apache 2.0(模型卡)。本書在 examples/data/smollm2-tokenizer/ 保存了它的分詞器檔案副本,由 prep/smollm2_tokenizer.py 以固定的修訂版本取得,因此範例可以離線執行。範例以 tokenizers 函式庫讀取該檔案,版本為 0.23.3,這也是該檔案原本所針對的函式庫。

以兩種分詞器分別編碼三個產品名稱,並計算每個分詞器在每個驗證名稱上的詞元數:

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 個,這是因為它訓練所用的文字遠多於家具名稱。它的輸出有三項差異值得說明:

  • 空格屬於詞元的一部分。Ġ 代表空格:Ġtable 是前面帶有空格的「table」。商店的分詞器以 </w> 標記單字的結尾,這個分詞器則是保留每個單字前面的空格,因此文字可以完整還原,包括空格在內。
  • 每個數字各自成為一個詞元。48 會變成 4 與 8,6.5 會變成 6、. 與 5。拆開數字可避免詞彙表被各只出現數次的數字塞滿,也讓所有數字以相同方式處理。
  • **文字開頭的單字前面沒有空格,所以會是不同的詞元。**SmolLM2 的詞彙表中有 Ġsled 這個單一詞元,卻沒有不帶空格的 sled,所以以 sled 開頭的名稱會得到 s 與 led,如輸出的最後幾行所示。至於 barstools,SmolLM2 的詞彙表中沒有收錄這個完整單字,因此拆成 bar、st 與 ools,如最前面幾行所示。

以自己的文字訓練的分詞器,在該文字上的表現會稍好一些。商店分詞器每個驗證名稱使用 9.91 個詞元,SmolLM2 則使用 10.53 個,而單字數為 6.79。這個差距一部分來自商店的分詞器不會把數字拆成個別數字,另一部分則是因為 SmolLM2 在每個接在空格後的數字前,都要多用一個獨立的 Ġ 詞元,而且會拆開每個名稱的第一個單字,因為它前面沒有空格。

**實用原則:**只要使用開放模型的分詞器,就要完全照原樣使用;模型只能理解它訓練時見過的詞元。只要要規劃上下文長度或成本預算,就用該分詞器計算詞元數,而不是計算單字數。當你以狹窄領域的文字訓練自己的模型時,也要以該文字訓練自己的分詞器。

手動套用 SmolLM2 的合併規則

最近一次變動於第 2026.11.11 版

SmolLM2 的分詞器檔案看起來就像一個黑箱,直到你發現它和商店的分詞器所含的東西相同:一份依序排列的合併規則清單。這個檔案 tokenizer.json 有三個與此處相關的部分。第一部分是前置分詞器(pre-tokenizer),它會在進行任何合併之前先把文字切成片段:它的各個步驟(範例會以名稱列印出來)先把數字逐位拆開,再把單字連同其前面的空格切開,並將每個位元組對應到一個可列印字元,Ġ 就是由此而來。這個對應就是 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 的分詞器對這些名稱所做的就只有這些;它另外定義了特殊詞元,這些詞元會在上述所有步驟之前先被比對。它與商店的分詞器不同之處在於前置分詞器與訓練文字,但它編碼文字的方式與商店的相同,都是反覆合併最早學到的配對。

這項比對值得檢查,因為文字切分方式的細微差異會影響後續的結果。以某個分詞器訓練的模型,若被餵入另一個分詞器產生的詞元,不會引發任何錯誤,卻會讀到毫無意義的內容,因為每個詞元編號都是有效的。當某個版本的分詞器與另一個版本在處理空格或數字的方式上不同時,同樣的情況也會發生,而且更難察覺。

實用原則: 把分詞器視為模型的一部分:與模型一同控管版本,從模型本身的檔案載入,並且在升級其中任何一者時,用你自己的文字進行測試。當兩個分詞器對同一段文字即使只有一個詞元不一致,在你信任以它們為基礎的模型所產生的任何結果之前,請先查明原因。

在正式環境中會出什麼問題

詞元(token)決定模型能看見什麼,而大多數斷詞器的問題,都是在遠離斷詞器的地方才顯現出來:

  • 斷詞器不一致會無聲地失敗。 若模型收到的是另一個斷詞器的詞元編號,它讀到的是有效但意義錯誤的編號,並產生看似有把握的胡言亂語。請將斷詞器檔案與模型一併發布,並且一起測試。
  • 成本以詞元計算。 上下文長度上限與每詞元的價格,都是針對詞元,而不是單字。商店的名稱在 SmolLM2 的斷詞器中,每個單字為 1.55 個詞元;充滿數字、代碼或其他語言的文字則會更多。請實際測量你自己的文字。
  • 數字很難處理。 若斷詞器把數字逐位拆開,模型會把 48 當成兩個詞元來推理;若不拆開,則 48 與 49 會是兩個互不相關的詞元。無論是哪一種,都應預期模型處理尺寸與數量的表現不如處理文字,並且要分開檢查。
  • 特殊詞元可以被輸入。 開放模型以特殊詞元標示文字的開頭或結尾,或對話中的一個回合,這些特殊詞元寫成字串,例如 <|endoftext|>。如果使用者輸入的文字包含這類字串,而斷詞器將其轉成特殊詞元,模型就會讀到一個使用者本不應能送出的控制訊號。請檢查你的斷詞器如何處理不受信任文字中的特殊詞元字串。
  • 新文字會逐漸偏離訓練文字。 以去年的商品目錄訓練出來的斷詞器,會把今年的產品線切成更多片段。請定期在新文字上測量每個單字的詞元數;若數值持續上升,表示斷詞器已逐漸跟不上它所處理的文字。

本章的決定

  • 本書的模型以位元組對編碼(byte-pair encoding,BPE)的詞元來讀取商店的文字。 詞彙表外的單字佔了驗證單字的 7.3%,而以字元切分所得的序列長度是以單字切分的 6.0 倍。BPE 可以避開這兩個問題:只要單字是由訓練文字中出現過的字元拼成,就能被編碼,而常見的單字則是單一詞元。它不會建立單字之間的關係,例如 chair 與 chairs;那是第 4 章的工作。
  • 商店的分詞器從訓練切分的名稱與描述中學得 4,000 次合併,程式在 lib.bpe.store_tokenizer()。在這個規模下,一個單字平均為 1.22 個詞元,而且很少有詞元類型稀少到無法學習。更多的合併只會稍微縮短序列,卻會增加許多罕見的詞元。
  • 每個單字都以 </w> 結尾,因此合併不會跨越單字。 SmolLM2 等開放模型則是把空格附在下一個單字上;兩種做法都讓模型看得見單字的邊界。
  • 開放模型一律搭配其自有的分詞器使用。 模型只看得懂它訓練時所用的詞元編號,因此第 10 章會用本章拆解過的分詞器來讀取 SmolLM2 的模型,而本書中每一次開放模型的記錄,都會註明所用的分詞器。
  • 不同分詞器所得的困惑度(perplexity)無法比較。 模型若預測的詞元較多、較小,在同一段文字上所需的步數就較多,困惑度也不同,因此本書中所有模型的比較都使用商店的分詞器,而第 3 章會以該分詞器的詞元重新開始這項比較。

本章,於本版次中

版次 2026.11.16範例於 2026年11 月 19 通過測試本章 7 個範例 個範例中有 7 個通過

譯自英文書,版次 2026.11.16。

引用本節

格式

各種格式皆引用英文原書,本譯本即依循該原書。

每種格式都會標示本版。其連結會開啟目前版次,節標題會說明該節內文最後一次變動的時間。存取日期與擷取日期即為你開啟此頁的當日。

本頁內容

第 2 章,共 11 章: Token

  1. 以詞為單位會留下缺口
  2. 字元涵蓋一切
  3. 一再合併最常出現的字元對
  4. 訓練商店的分詞器
  5. 選擇合併次數
  6. 讀取開放模型的分詞器
  7. 手動套用 SmolLM2 的合併規則
  8. 在正式環境中會出什麼問題
  9. 本章的決定

返回頂端所有章節