Token(词元)
阅读约需 33分钟 分钟,9节中含7个示例。
读完本章,你将能够从零构建一个字节对编码(byte-pair encoding)分词器,通过衡量每种词表大小的代价来选定词表规模,并读懂一个开源语言模型的分词器,达到能够手工应用其合并规则的程度。本书其余各章中的每个模型,都通过你在这里构建的分词器来读取商店的文本。
这家商店在线销售家具和家居用品,其商品名称和描述必须先切分成片段,模型才能读取。第 1 章把商品名称切分成了词,因为文本中的词与词之间、词与标点之间本来就有空格。这个选择做得很快,但在两个方面存在不足。其一,二元语法模型无法给训练中从未见过的词赋予任何概率,例如 barstools,这使模型失效。其二,它把 chair 和 chairs,或者 48 和 49,当作互不相关的词,对其中一个学到的内容也无法迁移到另一个上。
token 是语言模型读取和预测的单位,即文本在送入模型之前被切分成的片段。第一个问题源于 token 的选择,所以本章要解决的就是 token 的确定。第二个问题仅靠 token 无法解决,将在第 4 章中讨论。本章衡量三种把商店文本切分成 token 的方式:词、字符,以及大多数开源生成式模型采用的折中方案,即字节对编码。随后,本章会打开其中一个模型的分词器,并将它拆解开来。
单词留下的空缺
把文本切分成单词,能让模型得到带有语义的词元,这正是第 1 章从这里入手的原因。代价在于词表。模型只能预测其词表中的词元,词表是模型从训练文本中学到的词元集合,因此任何在训练之后才首次出现的单词都无法被预测,这样的单词称为词表外单词。在包含名称、数字和新产品的文本中,总会有一些这样的单词。
验证集名称是商店商品中占 10% 的部分,没有任何模型从中学习,留作检验模型如何处理未见过的文本。这些名称表明了单词级切分的不足有多大。统计训练名称从未用过的验证单词,并把它们分成罕见词和普通词:
1"""Counts the validation words that the training names never use, then sorts them into rare words and ordinary ones.2The share never seen in training is the line to read."""3from collections import Counter45from lib.store import is_ordinary, load_products, words67train_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 punctuation8validation = [w for name in load_products("validation")["name"] for w in words(name)]9unseen = [w for w in validation if w not in train_words]1011print("different words in training names:", f"{len(train_words):,}")12print("words seen once in training:", f"{sum(1 for n in train_words.values() if n == 1):,}")13print("validation words:", f"{len(validation):,}")14print("validation words never seen in training:", f"{len(unseen):,}")15print("share never seen in training:", f"{len(unseen) / len(validation):.1%}")16# 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 ordinary17print("share of them that are rare words, most often product lines' names:",18 f"{sum(not is_ordinary(w) for w in unseen) / len(unseen):.0%}")19print("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.pydifferent 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"""Compares the characters of the training names with those of the validation names, and counts the validation tokens2both ways. Its characters-per-word line is the one to read."""3import unicodedata45from lib.store import load_products, words67train_names, validation_names = load_products("train")["name"], load_products("validation")["name"]8characters = {c for name in train_names for c in name} # a set: each distinct character once910unseen = {c for name in validation_names for c in name} - characters11word_tokens = sum(len(words(name)) for name in validation_names) # a word is a token here, as in chapter 112character_tokens = sum(len(name) for name in validation_names) # len counts the spaces too, as characters1314print("different characters in training names:", len(characters))15print("validation characters never seen in training:", len(unseen))16print("they are:", ", ".join(unicodedata.name(c).lower() for c in sorted(unseen))) # printed by Unicode name, because a soft hyphen itself prints as nothing17print("validation tokens as words:", f"{word_tokens:,}")18print("validation tokens as characters:", f"{character_tokens:,}")19print("characters per word:", round(character_tokens / word_tokens, 1))
python character-tokens.pydifferent 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 倍,而对于后续各章的模型,成本的增长快于长度的增长,工作量还会更多。此外,本书中的每个模型都只能回看有限的词元窗口;以字符计,该窗口所覆盖的单词数就少了相应的倍数。
**工作准则:**只在小型实验中,或作为更大方案内部的后备手段时,才使用字符作为词元,后面几节就是这样做的。请检查文本中每个单词平均有多少个字符,因为这个系数会乘到每个序列长度和每一步训练上。
反复合并最频繁的字符对
词太粗,字符太细,所以包括 SmolLM2 在内的大多数开放生成模型所用的方法介于两者之间。字节对编码(byte-pair encoding,简称 BPE)从字符出发,用出现最频繁的字符对构建更大的词元。它最初是一种数据压缩方法,Sennrich、Haddow 和 Birch 将其改造后用于把单词切分成片段,供翻译模型使用(Sennrich et al., 2016)。算法很简短:
- 把训练文本中的每个词拆成字符,并在词尾标记
</w>,这样合并就不会把一个词与下一个词连起来。 - 统计每一对相邻符号出现的次数,每个词按其出现频率加权。
- 把最频繁的字符对在所有位置合并为一个新符号,并将其加入词表。
- 从第 2 步重复,次数取决于你想要的词表大小。
按学习顺序排列的合并列表就是分词器。编码一个词时,先把它拆成字符,再按相同的顺序应用这些合并。
在训练用的名称上手工运行八次合并,就足以展示每一个步骤。每次合并发生时都会打印出来,最后一行显示八次合并之后 table 的拼写:
1"""Runs the merge algorithm by hand on the training names for eight merges, printing each one and how table is spelled2afterwards. Those eight merges are the ones to read; the example asserts they match lib.bpe.train."""3from collections import Counter45from lib import bpe6from lib.store import load_products, words78word_counts = Counter(w for name in load_products("train")["name"] for w in words(name))9spelled = {w: list(w) + ["</w>"] for w in word_counts} # every word as characters, plus an end marker1011learned = []12for step in range(1, 9):13 pairs = Counter()14 for w, syms in spelled.items(): # count every adjacent pair of symbols15 for pair in zip(syms, syms[1:]):16 pairs[pair] += word_counts[w] # each pair weighted by how often its word occurs17 best = min(pairs, key=lambda p: (-pairs[p], p)) # the most frequent pair; ties go to the pair that sorts first18 for w, syms in spelled.items(): # replace it everywhere with one new symbol19 merged, i = [], 020 while i < len(syms):21 if syms[i:i + 2] == list(best): # the pair starting at position i is the one being merged22 merged.append(syms[i] + syms[i + 1]) # its two symbols, joined into the one new symbol23 i += 224 else:25 merged.append(syms[i])26 i += 127 spelled[w] = merged28 learned.append(best)29 print(f"merge {step}: {best[0]!r} + {best[1]!r} -> {best[0] + best[1]!r} ({pairs[best]:,} times)")30print("table spelled now:", spelled["table"])31assert learned == bpe.train(word_counts, 8) # lib.bpe.train, the fast version, learns the same eight merges
python merge-pairs-by-hand.pymerge 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 并没有解决第二个问题:正如下一节所示,一个常见词和它的复数形式可能各自成为一个完整的词元,彼此毫无共同之处。
工作准则: 与训练其他模型一样,只在训练划分上学习合并,并保留合并的顺序,因为编码依赖于该顺序。对频率相同的字符对,用固定规则决定先后,使同一段文本总是得到同一个分词器。
训练商店的分词器
上一节中的算法在每次合并之后都要重新统计所有词对,合并八次还可以,合并数千次就太慢了。本书的共享模块 lib.bpe 运行的是同一个算法,但它只统计一次词对,此后每次合并只更新被该次合并改动过的单词,并把计数保存在堆中,使出现频率最高的词对始终位于堆顶。它能在数秒内学会数千次合并,得到的合并结果与朴素版本相同:手写示例断言其八次合并与 lib.bpe.train 的结果一致。
商店的分词器同时在训练用的商品名称和商品描述上学习 4,000 次合并,因为本书的模型会同时从这两类文本中学习。下面用五段短文本来说明它如何处理未见过的单词和相近的单词,这五段文本包括两个商品名称和三组词对:
1"""Learns 4,000 merges from the training names and descriptions, then encodes five short texts with the resulting2tokenizer. Read the vocabulary size and the tokens of each text, which the prose cites."""3from collections import Counter45from lib import bpe6from lib.store import load_products, words78train = load_products("train")9word_counts = Counter(w for text in train["name"] + " " + train["description"] for w in words(text)) # names and descriptions, read as one text10tokenizer = bpe.Tokenizer(bpe.train(word_counts, merges=4000), bpe.alphabet(word_counts)) # the merges, then the characters they start from1112print("different words in training text:", f"{len(word_counts):,}")13print("characters and the end marker:", len(bpe.alphabet(word_counts)))14print("tokens in the vocabulary:", f"{len(tokenizer.vocabulary):,}")15# an unseen word, a word and its plural, digits, and a hyphenated word, in that order16for name in ["set of 2 barstools", "sled coffee table", "chair chairs", "48 49", "noise noise-free"]:17 print(name, "->", " ".join(tokenizer.encode(name)))
python store-tokenizer.pydifferent 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() 读取商店的文本。
选择合并次数
上一节使用了 4,000 次合并;本节说明原因。合并次数决定词表大小,是 BPE 分词器中唯一真正需要做的选择。合并越多,序列越短,计算量也就越小。但每个新增的词元覆盖的文本也越罕见,而训练文本中只出现寥寥几次的词元,又让模型缺少足够的学习材料:这与罕见词的问题相同,只是出现在了新的位置。
只学习一次 16,000 次合并,再分别取其中前 0、1,000、2,000、4,000、8,000 和 16,000 次,便得到六个分词器。较长一次运行的前 k 次合并,恰好就是 k 次合并的运行会学到的合并。每个分词器都有三项度量:训练文本用到的不同词元数,每个验证词被切成的词元数,以及这些不同词元中训练文本出现不足 20 次者所占的比例。一段文本用到的不同词元称为它的词元类型。在阅读下表之前,先判断两端各应呈现什么:
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.2Each row of the table measures one of them; the printed lines at the ends and at 4,000 merges are what the prose cites."""3from collections import Counter45from lib import bpe6from lib.store import load_products, words78training, validation = load_products("train"), load_products("validation")9counts = Counter(w for text in training["name"] + " " + training["description"] for w in words(text))10merges = bpe.train(counts, merges=16000) # the first k merges of a longer run are a k-merge tokenizer11validation_words = [w for text in validation["name"] + " " + validation["description"] for w in words(text)]1213results = {}14print(f"{'merges':>6} {'tokens used':>11} {'tokens per word':>15} {'rare types':>10}")15for k in [0, 1000, 2000, 4000, 8000, 16000]:16 tokenizer = bpe.Tokenizer(merges[:k], bpe.alphabet(counts)) if k else None # with no merges, a word is just its characters17 encode = tokenizer.encode_word if k else bpe.symbols18 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 occurs19 per_word = sum(len(encode(w)) for w in validation_words) / len(validation_words)20 rare = sum(1 for n in seen.values() if n < 20) / len(seen) # rare: seen fewer than 20 times in the training text21 print(f"{k:>6,} {len(seen):>11,} {per_word:>15.2f} {rare:>10.0%}")22 results[k] = per_word, rare23print("tokens per word at 4,000 merges:", f"{results[4000][0]:.2f}")24print("rare token types with characters only:", f"{results[0][1]:.0%}")25print("rare token types at 4,000 merges:", f"{results[4000][1]:.0%}")26print("rare token types at 16,000 merges:", f"{results[16000][1]:.0%}")
python vocabulary-size.pymerges 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 个,因为它们学习的文本多得多,即便较罕见的词元也出现得足够频繁。
工作准则: 通过度量来选择合并次数:在训练文本上度量罕见词元类型的比例,在留出文本上度量每词的词元数;当每词词元数不再明显下降、而罕见类型开始上升时停止。词表应随训练文本的规模而定;作为经验法则,在几百万词上训练的小模型适合数千次合并,而不是数万次。
读取开源模型的分词器
开源语言模型会把分词器作为文件与权重放在一起发布。读一读这个文件,能在更大的规模上看到同样的思路,也能看到商店分词器不必做出的几项选择。本书使用 SmolLM2,这是 Hugging Face 的一个开源语言模型,任何人都可以下载它的权重和分词器,许可证为 Apache 2.0(模型卡片)。本书在 examples/data/smollm2-tokenizer/ 中保存了一份它的分词器文件,由 prep/smollm2_tokenizer.py 按固定的修订版本获取,因此示例可以离线运行。示例使用 tokenizers 库读取该文件,版本为 0.23.3,这个文件正是为该库而生成的。
用两种分词器分别对三个产品名称编码,并统计每种分词器对每个验证名称平均产生的词元数:
1"""Encodes three product names with SmolLM2's tokenizer and with the store's, then counts the tokens per validation name2and per word each way. Read the tokens per validation name, which the prose cites."""3from tokenizers import Tokenizer45from lib import bpe6from lib.store import load_products78smollm2 = Tokenizer.from_file("data/smollm2-tokenizer/tokenizer.json") # the book's pinned copy of the file, read from examples/9store = bpe.store_tokenizer()1011print("SmolLM2 vocabulary:", f"{smollm2.get_vocab_size():,}")12for name in ["set of 2 barstools", "6.5 qt . slow cooker", "48 '' wide genuine leather wingback chair"]:13 print(name)14 print(" SmolLM2:", " ".join(smollm2.encode(name).tokens)) # .tokens gives the pieces as text; .ids would give their numbers15 print(" store: ", " ".join(store.encode(name)))1617names = load_products("validation")["name"]18print("tokens per validation name, SmolLM2:", round(sum(len(smollm2.encode(n).ids) for n in names) / len(names), 2))19print("tokens per validation name, store:", round(sum(len(store.encode(n)) for n in names) / len(names), 2))20print("tokens per validation name, words:", round(sum(len(n.split()) for n in names) / len(names), 2)) # split() on spaces: the store's words21print("sled at the start of a text:", " ".join(smollm2.encode("sled coffee table").tokens))22print("sled after a space:", " ".join(smollm2.encode(" sled coffee table").tokens)) # the same name, after a space23words_total = sum(len(n.split()) for n in names)24print("SmolLM2 tokens per word:", round(sum(len(smollm2.encode(n).ids) for n in names) / words_total, 2))
python smollm2-tokens.pySmolLM2 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 的合并规则
SmolLM2 的分词器文件乍看像一个黑箱,但只要弄清它保存的内容,就会发现它与商店的分词器并无二致:一份按顺序排列的合并列表。这个文件是 tokenizer.json,其中有三个部分与本节相关。第一部分是预分词器,它在任何合并之前先把文本切成片段:示例按名称打印出了它的各个步骤,先把数字逐位拆开,再把单词连同其前导空格切分出来,并把每个字节映射为可打印字符,Ġ 就是由此而来。这一映射就是 GPT-2 的 bytes_to_unicode(GPT-2 的编码器)。第二部分是合并列表,按学到的先后顺序排名。第三部分是词表,它为每个词元给出编号。
下面来检查该文件中的合并规则:对三个产品名称经库的预分词器切出的片段,像商店的分词器那样,每次先合并最早学到的词对,手工完成合并,再把结果与库给出的词元对照:
1"""Applies SmolLM2's learned merges by hand, earliest first, to the pieces its pre-tokenizer makes of three product names.2The example asserts that the tokens match the library's, which the prose cites."""3import json45from tokenizers import Tokenizer67smollm2 = Tokenizer.from_file("data/smollm2-tokenizer/tokenizer.json") # the book's pinned copy, read from examples/8spec = json.load(open("data/smollm2-tokenizer/tokenizer.json", encoding="utf-8"))9rank = {tuple(m.split(" ")): i for i, m in enumerate(spec["model"]["merges"])} # lower rank: learned earlier; the file stores each merge as "a b"101112def merge(piece): # apply the learned merges, earliest first, until none applies13 syms = list(piece)14 while len(syms) > 1:15 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 them16 best, i = min(pairs) # the earliest-learned pair; on a tie, the leftmost17 if best == len(rank):18 break19 syms[i:i + 2] = [syms[i] + syms[i + 1]] # the symbols at i and i + 1, joined into one20 return syms212223for name in ["set of 2 barstools", "sled coffee table", "6.5 qt . slow cooker"]:24 # pre_tokenize_str returns (piece, offsets) pairs; only the pieces are merged25 pieces = [p for p, _ in smollm2.pre_tokenizer.pre_tokenize_str(name)] # split into words, digits and bytes26 by_hand = [token for piece in pieces for token in merge(piece)]27 print(name, "->", " ".join(by_hand))28 assert by_hand == smollm2.encode(name).tokens # the library's tokens for the same name29steps = [step["type"] for step in spec["pre_tokenizer"]["pretokenizers"]]30assert spec["pre_tokenizer"]["pretokenizers"][0]["individual_digits"] # the Digits step comes first, and splits digits one at a time31print("pre-tokenizer steps:", ", ".join(steps))
python merges-by-hand.pyset 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.55 个词元;充满数字、编码或其他语言的文本占用的词元更多。请测量你自己的文本。
- 数字很难处理。 把数字逐位拆开的分词器,会让模型把
48当作两个词元来推理;不拆开的分词器,则会把48和49变成互不相关的词元。无论哪种情况,都应预期模型处理尺寸和数量的能力不如处理文字,并对它们单独检查。 - 特殊词元可以被键入。 开放模型用特殊词元来标记文本的开头或结尾,或对话中的一个轮次,这些特殊词元写成字符串,例如
<|endoftext|>。如果用户键入的文本中包含这类字符串,而分词器把它转换成了特殊词元,模型就会读到一个用户本不应能发送的控制信号。请检查你的分词器如何处理不可信文本中的特殊词元字符串。 - 新文本会逐渐偏离训练文本。 用去年的商品目录训练的分词器,会把今年的产品系列拆成更多片段。请不时测量新文本的每词词元数;如果它持续上升,说明分词器正在落后于它所处理的文本。
本章的决定
- 本书的模型将商店的文本读作字节对编码(BPE)词元。 词表外的单词占验证集单词的 7.3%,而字符级切分使序列长度达到单词级的 6.0 倍。BPE 避免了这两个问题:只要单词由训练文本中出现过的字符拼写而成,就能被编码,常见单词则是单个词元。它不会把单词彼此关联起来,例如
chair和chairs;那是第 4 章的任务。 - 商店的分词器从训练集划分的名称和描述中学习 4,000 次合并, 代码在
lib.bpe.store_tokenizer()中。在这个规模下,一个单词平均有 1.22 个词元,过于稀有而难以学习的词元类型很少。更多的合并只会略微缩短序列,却会增加许多稀有词元。 - 每个单词以
</w>结尾,因此合并不会跨越单词。 SmolLM2 等开放模型则把空格附在下一个单词上;两种做法都让模型能看清单词边界。 - 开放模型始终与其自带的分词器配合使用。 模型只理解它训练时所用的词元编号,因此第 10 章用本章剖析过的分词器来读取 SmolLM2 的模型,本书中每一次对开放模型的记录也都会注明所用的分词器。
- 不同分词器得到的困惑度不可比较。 预测更多、更小词元的模型需要更多步骤,在同一文本上的困惑度也不同,因此本书中所有模型之间的比较都使用商店的分词器,第 3 章在这些词元上重新开始这一比较。
本章,在本版次中
版次 2026.11.16示例于 2026年11月19日 通过本章 7个示例 个示例中有 7 个通过
译自英文版图书,版次 2026.11.16。