토큰

읽는 데 약 28분분 걸린다, 9절에 7개 예제이(가) 있음.

2026.11.16판 예제 통과 2026년 11월 19 86개 예제 중 86개 통과 변경 사항

AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식

영어판 2026.11.16판을 번역한 것이다. 원문 읽기

이 장을 마치면 바이트 쌍 인코딩(byte-pair encoding) 토크나이저를 처음부터 만들 수 있다. 어휘 크기마다 드는 비용을 측정해서 어휘 크기를 정할 수 있다. 공개 언어 모델의 토크나이저를 읽고 그 병합 규칙을 직접 손으로 적용할 수 있다. 이 책의 나머지 장에 나오는 모든 모델은 여기서 만드는 토크나이저를 거쳐 상점의 텍스트를 읽는다.

이 상점은 가구와 생활용품을 온라인으로 판매한다. 상품명과 설명은 어떤 모델이 읽기 전에 먼저 조각으로 잘라야 한다. 1장에서는 상품명을 단어 단위로 잘랐다. 텍스트에 이미 단어 사이와 문장 부호 주변에 공백이 있기 때문이다. 이 선택은 간단했지만 두 가지 점에서 부족했다. 첫째, 바이그램 모델은 학습 중에 본 적 없는 단어, 예를 들어 barstools에는 확률을 전혀 줄 수 없었고, 그 때문에 모델이 제대로 동작하지 못했다. 둘째, chair와 chairs, 또는 48와 49을 서로 관련 없는 단어로 취급했고, 한쪽에 대해 학습한 내용이 다른 쪽으로 전혀 전달되지 않았다.

토큰(token)은 언어 모델이 읽고 예측하는 단위, 곧 모델이 텍스트를 보기 전에 텍스트를 잘라 놓은 조각이다. 첫 번째 문제는 토큰을 어떻게 고르느냐에서 비롯되므로, 이 장에서는 토큰을 바로잡는다. 두 번째 문제는 토큰만으로는 해결할 수 없으며, 4장에서 다룬다. 이 장에서는 상점의 텍스트를 토큰으로 자르는 세 가지 방법을 측정한다. 단어, 문자, 그리고 대부분의 공개 생성 모델이 쓰는 중간 방식인 바이트 쌍 인코딩이다. 그다음 그런 모델 중 하나의 토크나이저를 열어 분해해 본다.

단어는 빈틈을 남긴다

마지막으로 변경된 판: 2026.11.11판

텍스트를 단어로 자르면 모델은 의미를 지닌 토큰을 얻는다. 1장이 여기서 출발한 이유가 그것이다. 그 대가는 어휘 집합이다. 모델은 어휘, 즉 학습 텍스트에서 익힌 토큰의 집합에 있는 토큰만 예측할 수 있다. 따라서 학습이 끝난 뒤에 처음 나타나는 단어는 모델이 다룰 수 없는 미등록어(out-of-vocabulary) 가 된다. 이름, 숫자, 신제품이 들어 있는 텍스트에는 미등록어가 언제나 어느 정도 있다.

검증용 이름은 어떤 모델도 학습에 쓰지 않는, 매장 제품의 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퍼센트보다 많은 수가 처음 보는 단어라면 단어를 토큰으로 쓰지 않는다. 고정된 명령어 집합처럼 어휘가 닫혀 있는 텍스트에서는 단어 토큰도 여전히 합리적이다.

문자는 모든 것을 포괄한다

마지막으로 변경된 판: 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에서는 모든 언어의 모든 문자가 1바이트에서 4바이트로 저장되고 가능한 바이트 값은 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은 같은 알고리즘을 실행하되, 쌍을 한 번만 세고 병합이 끝날 때마다 그 병합으로 바뀐 단어만 갱신한다. 또 횟수를 힙에 보관하므로 가장 빈번한 쌍이 항상 맨 위에 있다. 이 모듈은 수천 번의 병합을 몇 초 만에 학습하며, 단순한 버전과 같은 병합을 얻는다. 손으로 작성한 예제는 자신의 여덟 번의 병합이 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은 단어마다 하나씩 모두 세 개의 토큰이다. 1장의 바이그램 모델은 학습용 상품명에 barstools이 한 번도 나오지 않아서 이 단어를 처리하지 못했다. 이 단어는 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()를 통해 상점의 텍스트를 읽는다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Choose how many merges

마지막으로 변경된 판: 2026.11.16판

The previous section used 4,000 merges; this one shows why. The number of merges sets the vocabulary size, and it's the one real choice in a BPE tokenizer. More merges make sequences shorter, which saves computation. But each new token covers rarer text, and a token the training text shows only a few times gives a model too little to learn from: the same problem as rare words, in a new place.

Learning 16,000 merges once and reading the first 0, 1,000, 2,000, 4,000, 8,000 and 16,000 of them gives six tokenizers. The first k merges of a longer run are exactly the merges a k-merge run would learn. Each one gets three measures: the different tokens the training text uses, the tokens each validation word becomes, and the share of those different tokens that the training text shows fewer than 20 times. The different tokens a text uses are its token types. Before reading the table, decide what each end should show:

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%

The store's tokenizer sits where sequences are short and few tokens are rare. At 4,000 merges, a validation word takes 1.22 tokens on average, and 6% of the token types are rare, about as few as at 2,000.

With no merges, every token is a character, so tokens are frequent but words are long: a word takes more than five tokens, and 49% of the token types are rare, because the descriptions contain unusual characters. With many merges, words are short but rare types pile up: from 8,000 merges the rare share climbs, and at 16,000 it's 53%, because most of the extra merges cover words the training text barely contains.

The vocabulary size also sets part of the model's size. A neural language model, from chapter 5 on, stores a vector of numbers for every token in its vocabulary, and scores every token in the vocabulary at every step it predicts. A vocabulary four times as large means four times as many of those vectors to learn, and four times as many scores to compute at every step, whatever the text. For the small models this book trains on a laptop, that cost matters as much as sequence length.

So the store's tokenizer uses 4,000 merges: past that, each merge buys little length and adds a token that the book's small models can't learn well. Large open models use vocabularies of tens of thousands of tokens or more, SmolLM2's has 49,152, because they learn from far more text, so even their rarer tokens occur often enough.

Working rule: Choose the number of merges by measuring, on your training text, the share of rare token types, and on held-out text, the tokens per word; stop where tokens per word stops falling much and rare types start climbing. Scale the vocabulary with the training text; as a rule of thumb, a small model on a few million words wants thousands of merges, not tens of thousands.

공개 모델의 토크나이저 읽기

마지막으로 변경된 판: 2026.11.12판

공개 언어 모델은 가중치 옆에 토크나이저를 파일로 함께 배포한다. 이를 읽어 보면 같은 개념을 더 큰 규모에서 볼 수 있고, 매장용 토크나이저가 내릴 필요가 없었던 몇 가지 선택도 확인할 수 있다. 이 책은 Hugging Face가 만든 공개 언어 모델 SmolLM2를 사용한다. 이 모델의 가중치와 토크나이저는 누구나 내려받을 수 있으며, 라이선스는 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로 나뉜다. 또한 SmolLM2의 어휘에 하나의 단어로는 없는 barstools는 첫 줄들에서 보듯 bar, st, ools로 나뉜다.

자신의 텍스트로 학습한 토크나이저는 그 텍스트에서 조금 더 나은 결과를 낸다. 검증용 이름 하나당 토큰 수는 매장 토크나이저가 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

직접 만든 토큰은 세 이름 모두에서 라이브러리의 토큰과 일치하며, 예제가 이를 assert로 확인한다. 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판을 번역한 것이다.

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

11장 중 2장: 토큰

  1. 단어는 빈틈을 남긴다
  2. 문자는 모든 것을 포괄한다
  3. 가장 빈번한 쌍을 병합하기를 반복한다
  4. 상점의 토크나이저 학습하기
  5. Choose how many merges
  6. 공개 모델의 토크나이저 읽기
  7. SmolLM2의 병합을 직접 적용하기
  8. 운영 환경에서 무엇이 잘못되는가
  9. 이 장에서 결정한 것

맨 위로 돌아가기전체 장