Track III · LLM Fundamentals · 02/07

토크나이저Tokenizers

왜 LLM이 글자도 단어도 아닌 subword를 쓰는지, byte-level BPE가 어떻게 학습·인코딩·디코딩되는지 직접 돌려 보고, 숫자·공백·한국어·glitch token 같은 토큰화 부작용이 어디서 오는지 설명한다.Why LLMs use subwords rather than characters or words, how byte-level BPE is trained, encodes and decodes (you run it yourself), and where tokenization side effects such as numbers, whitespace, Korean text and glitch tokens come from.

35 분min tokenizer · BPE · byte-level · vocabulary · special tokens · unicode 먼저 볼 것:Before this: 언어 모델링Language modeling

In the previous lesson we used the word “token” without defining it. A language model operates on a sequence of integers, and the thing that turns text into that sequence is the tokenizer. The tokenizer is usually trained separately from the model, and once chosen it does not change for the model’s whole life. Yet a good share of an LLM’s strange behaviour comes from it: getting arithmetic wrong, failing to spell a word backwards, Korean being more expensive than English and the context feeling shorter, the model babbling when fed certain strings.

Why neither characters nor words

Consider the two extremes.

  • Characters (or bytes): the vocabulary is small (256 for bytes) and there are no unseen words. The price is long sequences. If the same text becomes several times longer in tokens, attention cost grows with the square of the length and the rest of the computation grows linearly, and the content that fits in a given context window shrinks by the same factor. The model also has to assemble the unit “word” by itself.
  • Words: sequences are short but the vocabulary grows without bound. Inflected forms (run, runs, running), compounds, typos, proper nouns and code identifiers all become separate entries, and words not in the vocabulary collapse into <UNK>. It is even worse for languages like Korean, where particles and endings attach to word stems.

Subwords sit in between. Frequent strings (“the”, ” model”, “ing”) are one token; rare strings are represented in several pieces. It is a kind of variable-length code whose lengths are set by frequency. The most widely used way to build such a vocabulary automatically from data is BPE (byte pair encoding).

Byte-level BPE

BPE started as a compression algorithm (Gage, 1994). Sennrich et al. (2016) used it to build the vocabulary of a translation model, and GPT-2 (Radford et al., 2019) changed it to run on bytes. The algorithm:

  1. Convert the training text to a UTF-8 byte sequence. The initial vocabulary is the 256 bytes.
  2. Count the frequency of adjacent token pairs.
  3. Merge the most frequent pair (a,b)(a, b) into a new token zz. Record the merge rule (a,b)→z(a, b) \to z and replace every (a,b)(a, b) in the text with zz.
  4. Repeat 2–3 until the vocabulary reaches the desired size.

The result of training is an ordered list of merges. Encoding converts new text to bytes and applies the merges in the order they were learned (their rank); decoding concatenates the bytes each token stands for and interprets them as UTF-8. Since every string can be represented as bytes, no <UNK> is needed. An emoji or a never-seen character is, at worst, split into bytes.

Real tokenizers first cut the text with pre-tokenization rules before merging. GPT-2 used a regular expression to split into chunks such as “leading space + letters”, “digits” and “punctuation”, and forbade merges across those boundaries. Without it the vocabulary is wasted on entries like “dog.”, “dog!” and “dog?” each becoming a token. As a result, English words usually become tokens that include the leading space (” the”, ” model”).

지난 레슨에서 “토큰”을 정의 없이 썼다. 언어 모델은 정수열 위에서 동작하고, 글을 그 정수열로 바꾸는 것이 토크나이저(tokenizer) 다. 토크나이저는 보통 모델과 따로 학습되고, 한 번 정해지면 모델의 일생 동안 바뀌지 않는다. 그런데도 LLM의 이상한 행동 상당수가 여기서 나온다. 산수를 틀리는 것, 단어 철자를 거꾸로 못 쓰는 것, 한국어가 영어보다 비싸고 문맥이 짧게 느껴지는 것, 특정 문자열을 넣으면 모델이 횡설수설하는 것.

글자도 단어도 아닌 이유

두 극단을 생각해 보자.

  • 문자(또는 바이트) 단위: 어휘가 작고(바이트면 256개) 처음 보는 단어가 없다. 대신 시퀀스가 길다. 같은 글이 토큰 수로 몇 배 길어지면 attention 비용은 길이의 제곱으로, 나머지 연산은 길이에 비례해 늘고, 같은 문맥 창(context window)에 담기는 내용은 그만큼 줄어든다. 모델이 “단어”라는 단위를 스스로 조립해야 하는 부담도 생긴다.
  • 단어 단위: 시퀀스는 짧지만 어휘가 끝없이 커진다. 활용형(run, runs, running), 복합어, 오타, 고유명사, 코드 식별자가 전부 별개 항목이 되고, 어휘에 없는 단어는 <UNK>로 뭉개진다. 한국어처럼 조사·어미가 붙는 언어에서는 더 심하다.

subword는 그 사이다. 자주 나오는 문자열(“the”, ” model”, “ing”)은 한 토큰, 드문 문자열은 여러 조각으로 표현한다. 빈도에 따라 길이가 정해지는 일종의 가변 길이 부호다. 이 어휘를 데이터에서 자동으로 만드는 가장 널리 쓰이는 방법이 BPE(byte pair encoding) 다.

바이트 수준 BPE(Byte-level BPE)

BPE는 원래 압축 알고리즘이었다(Gage, 1994). Sennrich et al.(2016)이 이것을 번역 모델의 어휘 구성에 썼고, GPT-2(Radford et al., 2019)가 바이트 위에서 돌리는 형태로 바꿨다. 알고리즘은 이렇다.

  1. 학습 텍스트를 UTF-8 바이트열로 바꾼다. 초기 어휘는 바이트 256개다.
  2. 인접한 토큰 쌍의 빈도를 센다.
  3. 가장 많이 나온 쌍 (a,b)(a, b)를 새 토큰 zz로 합친다. merge 규칙 (a,b)→z(a, b) \to z를 기록하고, 텍스트의 모든 (a,b)(a, b)를 zz로 바꾼다.
  4. 원하는 어휘 크기가 될 때까지 2–3을 반복한다.

학습 결과는 순서가 있는 merge 목록이다. 인코딩은 새 텍스트를 바이트로 바꾼 뒤 merge를 학습된 순서(rank)대로 적용하는 것이고, 디코딩은 각 토큰이 가리키는 바이트를 이어 붙여 UTF-8로 해석하는 것이다. 모든 문자열이 바이트로 표현되므로 <UNK>가 필요 없다. 이모지든 처음 보는 문자든 최악의 경우 바이트 단위로 쪼개질 뿐이다.

실전 토크나이저는 merge 전에 텍스트를 pre-tokenization 규칙으로 먼저 자른다. GPT-2는 정규식으로 “앞 공백 + 글자 덩어리”, “숫자 덩어리”, “구두점 덩어리” 등으로 나누고 그 경계를 넘는 merge를 금지했다. 그러지 않으면 “dog.”, “dog!”, “dog?”가 각각 토큰이 되는 식으로 어휘가 낭비된다. 그 결과 영어 단어는 보통 앞 공백을 포함한 토큰(” the”, ” model”)이 된다.

학습 텍스트Training text
merge 표 (최근 것이 위)merge table (newest on top)
    바이트bytes – 토큰tokens – 압축률compression – 바이트/토큰bytes/token vocab – = 256 + merge 깨진 UTF-8 토큰broken UTF-8 tokens –
    Press merge +1 and the byte pair that occurs together most often is merged into one new token, and the text below is re-segmented (same token, same colour). At first every token is 1 byte, so the compression ratio is 1. Switch to Korean: a syllable is 3 bytes in UTF-8, so early merges produce broken byte-fragment tokens like ec 95. Turn pre-tokenization off and merges cross word boundaries, producing tokens like " the cat". merge +1을 눌러 보면 가장 자주 붙어 나오는 바이트 쌍이 새 토큰 하나로 합쳐지고, 아래 텍스트가 다시 쪼개진다(같은 토큰은 같은 색). 처음엔 모든 토큰이 1바이트라 압축률이 1이다. 한국어로 바꾸면 한 음절이 UTF-8 3바이트라서 merge 초반에는 ec 95 같은 깨진 바이트 조각 토큰이 생긴다. pre-tokenization을 끄면 merge가 단어 경계를 넘어 " the cat" 같은 토큰이 생긴다.

    Things to check in the figure:

    1. On English text the first few merges start from short, common pieces, like “␣t” → “␣th” → “␣the” (␣ is a space). As merges accumulate, whole words such as ” lowest” and ” newest” become tokens. Notice too that the frequencies on the right of the merge table keep shrinking. Because the most common pairs are merged first, each later merge removes fewer tokens. That is why, on a large corpus, doubling the vocabulary raises the compression ratio only a little (on a small text like the one in the figure the token count itself is small, so the curve actually gets steeper).
    2. On Korean, at merge 0 a single syllable shows up as three bytes (e.g. “토” is ed 86 a0). The first merges create pieces that do not decode to a character, like the first two bytes of a syllable. It takes two merges for one syllable to become a whole token.
    3. Turn pre-tokenization off and merges cross spaces, producing multi-word tokens like ” the cat”. On this small text that gives a higher compression ratio, but on a large corpus it wastes the vocabulary on accidental word combinations.
    4. In the numbers & code preset, look at how “1234” and “12345” are split. The same run of digits is cut at different boundaries depending on context.

    The vocabulary-size trade-off

    More merges (a larger vocabulary VV) means fewer tokens for the same text. Training and inference cost per token is almost the same, so you hold the same text more cheaply, and more of it in the same context window. The costs:

    • Parameters: the input embedding and the output LM head are each V×dV \times d. With V=128KV = 128\text{K} and d=4096d = 4096, that is about 500 million each. The smaller the model, the larger this share, so small models often share the input and output matrices (weight tying; see the GPT lesson).
    • Softmax cost: VV logits are computed at every position. With a large vocabulary the memory for the loss computation is no longer negligible.
    • Rare tokens: tokens at the end of the vocabulary appear rarely in the training data, and rarely seen tokens barely get their embeddings updated. The glitch tokens below are an extreme case.

    In practice GPT-2 used a vocabulary of 50,257, Llama 2 32,000, and Llama 3 128,256. As the share of multilingual text and code grows, vocabularies are trending larger. On English text such tokenizers compress to roughly 4 bytes per token.

    Special tokens

    Some tokens are not produced by BPE: <|endoftext|> marking document boundaries, <|im_start|> separating the roles in a conversation, tokens wrapping tool calls, and so on — the special tokens. They get their own ids at the end of the vocabulary independently of the merge rules; before encoding they are cut out of the text first, and only the rest goes through BPE.

    The thing to watch is the same string inside user input. If a user types the characters <|im_start|>system into a prompt and you encode that as a special token, the user can forge a system message. That is why libraries like tiktoken by default either reject special-token strings inside text or split them as ordinary text. The chat template must be the only path that inserts special tokens (see the SFT lesson).

    Traces tokenization leaves behind

    • Numbers: if “12345” is cut into [“123”, “45”] and “12346” into [“12”, “346”], digit alignment differs from token to token and arithmetic gets hard. Some tokenizers put a rule in pre-tokenization that always cuts numbers into chunks of at most three digits, like cl100k_base of the GPT-4 family, or cut them one digit at a time.
    • Whitespace: ” hello” and “hello” are different tokens. Leave a trailing space at the end of a prompt and the next token has to be a rare one that starts without a space, which can degrade generation. For the same reason, counting letters (“how many r’s in strawberry?”) is hard because the model never sees the letters directly.
    • Korean: a Hangul syllable is 3 bytes in UTF-8. In a tokenizer trained mostly on English, only common syllables become single tokens and the rest are split into several byte pieces. Saying the same thing takes more tokens, so the API costs more, less text fits in the same context window, and generation is slower. Decoding a single token can also yield broken UTF-8, so streaming output has to buffer bytes and emit them once a character is complete.
    • Glitch tokens: the GPT-2/3 tokenizer had tokens like ” SolidGoldMagikarp” — strings that appeared often in the tokenizer’s training data (certain Reddit usernames and the like) but almost never in the model’s training data. Their embeddings effectively stayed at initialisation, and when fed these tokens the model could not repeat the word or said something bizarre (Rumbelow & Watkins, 2023). Land & Bartolo (2024) found such under-trained tokens automatically across many open models. The lesson: the tokenizer’s and the model’s training-data distributions must not diverge.

    Implementing it

    Below is a byte-level BPE with the same structure as minbpe. Training (train), encoding (encode) and decoding (decode) take 40 lines using only the standard library.

    Python Byte-level BPE: train · encode · decode · round-trip check
    def get_stats(ids, counts=None):
        counts = {} if counts is None else counts
        for pair in zip(ids, ids[1:]):
            counts[pair] = counts.get(pair, 0) + 1
        return counts
    
    def merge(ids, pair, idx):
        out, i = [], 0
        while i < len(ids):
            if i < len(ids) - 1 and (ids[i], ids[i + 1]) == pair:
                out.append(idx); i += 2
            else:
                out.append(ids[i]); i += 1
        return out
    
    def train(text, vocab_size):
        ids = list(text.encode("utf-8"))
        merges, vocab = {}, {i: bytes([i]) for i in range(256)}
        for idx in range(256, vocab_size):
            stats = get_stats(ids)
            pair = max(stats, key=stats.get)           # the most frequent adjacent pair
            if stats[pair] < 2:
                break
            ids = merge(ids, pair, idx)
            merges[pair] = idx
            vocab[idx] = vocab[pair[0]] + vocab[pair[1]]
        return merges, vocab
    
    def encode(text, merges):
        ids = list(text.encode("utf-8"))
        while len(ids) >= 2:
            stats = get_stats(ids)
            pair = min(stats, key=lambda p: merges.get(p, float("inf")))  # the earliest-learned merge
            if pair not in merges:
                break
            ids = merge(ids, pair, merges[pair])
        return ids
    
    def decode(ids, vocab):
        return b"".join(vocab[i] for i in ids).decode("utf-8", errors="replace")
    
    corpus = (
        "the model predicts the next token. the tokenizer turns text into tokens. "
        "a lower loss means the model predicts the next token better. "
        "언어 모델은 다음 토큰을 예측한다. 토크나이저는 글을 토큰으로 바꾼다. "
        "토큰이 짧으면 시퀀스가 길어지고, 토큰이 길면 어휘가 커진다. "
    ) * 4
    merges, vocab = train(corpus, 256 + 120)
    print(f"learned {len(merges)} merges, vocab = {len(vocab)}")
    show = lambda b: "[" + b.decode("utf-8", errors="backslashreplace").replace(" ", "␣") + "]"
    for (a, b), z in list(merges.items())[:8]:
        print(f"  #{z - 255:>3}: {show(vocab[a]):>14} + {show(vocab[b]):<10} -> {show(vocab[z])}")
    
    for s in ["the next token", "다음 토큰을 예측한다", "unseen words 🤖 처음 보는 글자"]:
        ids = encode(s, merges)
        assert decode(ids, vocab) == s                 # round-trip check
        nb = len(s.encode("utf-8"))
        print(f"\n{s!r}: {nb} bytes -> {len(ids)} tokens ({nb / len(ids):.2f} bytes/token)")
        print("  ", "".join(show(vocab[i]) for i in ids))
    print("\nround-trip OK")
     

    In English, words that appear often in the training data, like ” token”, become whole tokens. In Korean, with the same amount of data, syllables stay as byte pieces except for very frequent words like “토큰” (“token”). Things that look like [\xec\x9d] are byte-piece tokens that do not line up with character boundaries. Characters absent from the training data, like the emoji in the last sentence, stay as bytes, but the round trip is exact in every case. The next block looks at special tokens, pre-tokenization, and the number problem.

    Python Special tokens, pre-tokenization, numbers
    import re
    
    SPECIAL = {"<|endoftext|>": 1000, "<|im_start|>": 1001, "<|im_end|>": 1002}
    inv_special = {v: k for k, v in SPECIAL.items()}
    
    def encode_chat(text, merges, allow_special=True):
        if not allow_special:
            return encode(text, merges)                # user input: special strings become plain bytes too
        parts = re.split("(" + "|".join(re.escape(s) for s in SPECIAL) + ")", text)
        ids = []
        for p in parts:
            ids += [SPECIAL[p]] if p in SPECIAL else encode(p, merges)
        return ids
    
    def decode_chat(ids):
        return "".join(inv_special[i] if i in inv_special else decode([i], vocab) for i in ids)
    
    msg = "<|im_start|>user\nthe model<|im_end|>"
    a = encode_chat(msg, merges, allow_special=True)
    b = encode_chat(msg, merges, allow_special=False)
    print(f"special tokens inserted by the template: {len(a)} tokens -> {a}")
    print(f"same string inside user text          : {len(b)} tokens (no special id: {not set(b) & set(SPECIAL.values())})")
    
    # GPT-2-style pre-tokenization (simplified): leading space + letters / digits / other runs
    PAT = re.compile(r" ?[A-Za-z가-힣]+| ?\d+| ?[^\sA-Za-z가-힣\d]+|\s+")
    print("\npre-tokenize:", PAT.findall("the model's loss: 1234, 다음 토큰!"))
    
    # numbers: even a BPE trained only on numbers cuts similar numbers at different boundaries
    import random
    r = random.Random(0)
    nums = " ".join(str(int(10 ** r.uniform(1, 5))) for _ in range(400)) + " "
    m_num, v_num = train(nums, 256 + 80)
    print()
    for s in [" 1234", " 12345", " 12346", " 2024", " 999"]:
        print(f"{s!r:>9} -> {'|'.join(v_num[i].decode() for i in encode(s, m_num))}")
     

    In the number results, ” 12345” is cut as 12|34|5, while ” 12346”, differing in one digit, is cut as 12|3|46. Digits of the same place value land in different positions within tokens, so to compute something like “12345 + 1” the model has to realign place values regardless of token boundaries. Pre-tokenization that always cuts numbers into fixed three-digit chunks mitigates this.

    확인 문제Check yourself

    What happens when a byte-level BPE tokenizer receives a character it never saw in training (e.g. a new emoji)?

    The initial vocabulary contains all 256 bytes, so any string can be represented as a byte sequence. An unseen character simply gets no merges and stays long; decoding concatenates bytes, so nothing is lost. This is why GPT-2 went byte-level.

    확인 문제Check yourself

    Which of these does NOT generally happen when you grow the vocabulary from 32K to 128K?

    Byte-level BPE contains every byte regardless of vocabulary size, so its expressiveness is unchanged. A larger vocabulary shortens sequences (the larger VV, the more bytes per token), grows the matrices as V×dV \times d, and makes the tokens at the end of the vocabulary rarer.

    Summary

    • Subword tokenization is a compromise between characters (long sequences) and words (a huge vocabulary, OOV).
    • Byte-level BPE: start from 256 bytes and repeatedly merge the most frequent adjacent pair. Encoding applies merges in learned order; decoding concatenates bytes. There is no <UNK>.
    • Vocabulary size trades sequence length (compute, context) against matrix size and rare tokens.
    • Special tokens are handled outside BPE and must be kept distinct from the same strings inside user input.
    • Number splitting, whitespace, Korean byte pieces and glitch tokens are all side effects of tokenizer design.

    그림에서 확인할 것:

    1. 영어 텍스트에서 처음 몇 merge는 “␣t” → “␣th” → “␣the”처럼 짧고 흔한 조각에서 시작한다(␣는 공백). merge가 쌓이면 ” lowest”, ” newest” 같은 단어 전체가 토큰이 된다. merge 표 오른쪽의 빈도가 점점 작아지는 것도 보자. 흔한 쌍부터 합치니 뒤로 갈수록 한 번의 merge가 줄이는 토큰 수가 작다. 큰 말뭉치에서는 그래서 어휘를 두 배로 늘려도 압축률은 조금씩만 오른다(이 그림처럼 작은 텍스트에서는 토큰 수 자체가 작아서 곡선이 오히려 가팔라진다).
    2. 한국어에서는 merge 0일 때 한 음절이 바이트 3개로 보인다(예: “토”는 ed 86 a0). 첫 merge들은 음절의 앞 두 바이트처럼 글자로 디코딩되지 않는 조각을 만든다. 음절 하나가 온전한 토큰이 되려면 merge가 두 번 필요하다.
    3. pre-tokenization을 끄면 merge가 공백을 넘어 ” the cat” 같은 여러 단어짜리 토큰을 만든다. 이 작은 텍스트에서는 압축률이 더 높아지지만, 큰 말뭉치에서는 어휘가 우연한 단어 조합에 낭비된다.
    4. 숫자·코드 프리셋에서 “1234”와 “12345”가 어떻게 쪼개지는지 보자. 같은 숫자 조각이 문맥에 따라 다른 경계로 잘린다.

    어휘 크기의 트레이드오프

    merge를 더 하면(어휘 VV가 커지면) 같은 글의 토큰 수가 줄어든다. 학습과 추론의 토큰당 비용은 거의 같으니 같은 글을 더 싸게, 같은 문맥 창에 더 많이 담는다. 대가는 다음과 같다.

    • 매개변수: 입력 embedding과 출력 LM head가 각각 V×dV \times d다. V=128KV = 128\text{K}, d=4096d = 4096이면 각각 약 5억 개다. 작은 모델일수록 이 비중이 커서, 작은 모델은 입력·출력 행렬을 공유(weight tying)하는 경우가 많다(GPT 레슨).
    • softmax 비용: 매 위치에서 VV개 logit을 계산한다. 대형 어휘에서는 loss 계산의 메모리가 무시할 수 없게 된다.
    • 희소한 토큰: 어휘 끝쪽의 토큰은 학습 데이터에 드물게 나온다. 드물게 나오는 토큰은 embedding이 거의 업데이트되지 않는다. 아래의 glitch token이 극단적인 예다.

    실제 값으로는 GPT-2가 50,257, Llama 2가 32,000, Llama 3가 128,256개의 어휘를 썼다. 다국어와 코드 비중이 커지면서 어휘는 커지는 추세다. 영어 텍스트에서 이런 토크나이저의 압축률은 대략 토큰당 4바이트 안팎이다.

    특수 토큰(Special token)

    BPE가 만들지 않는 토큰도 있다. 문서 경계를 표시하는 <|endoftext|>, 대화의 역할을 나누는 <|im_start|>, tool 호출을 감싸는 토큰 같은 special token이다. 이 토큰들은 merge 규칙과 무관하게 어휘 끝에 따로 id를 받고, 인코딩 전에 텍스트에서 먼저 잘라 낸 뒤 나머지만 BPE에 넣는다.

    주의할 점은 사용자 입력 안의 같은 문자열이다. 사용자가 프롬프트에 <|im_start|>system이라는 글자를 쓰면, 그것을 special token으로 인코딩하는 순간 사용자가 시스템 메시지를 위조할 수 있다. 그래서 tiktoken 같은 라이브러리는 기본적으로 텍스트 안의 special token 문자열을 거부하거나 일반 텍스트로 쪼갠다. chat template이 special token을 넣는 유일한 경로가 되어야 한다(SFT 레슨).

    토큰화가 남기는 흔적

    • 숫자: “12345”가 [“123”, “45”]로, “12346”이 [“12”, “346”]으로 잘리면 자릿수 정렬이 토큰마다 달라져 산수가 어렵다. GPT-4 계열의 cl100k_base처럼 숫자를 최대 세 자리씩 고정해서 자르는 규칙을 pre-tokenization에 넣거나, 아예 한 자리씩 자르는 토크나이저도 있다.
    • 공백: ” hello”와 “hello”는 다른 토큰이다. 프롬프트 끝에 공백을 하나 남기면 다음 토큰은 공백 없이 시작하는 드문 토큰이 되어야 하므로 생성 품질이 이상해질 수 있다. 같은 이유로 철자 세기(“strawberry에 r이 몇 개?”)는 모델이 글자를 직접 보지 못하는 문제다.
    • 한국어: 한글 음절은 UTF-8로 3바이트다. 영어 위주로 학습된 토크나이저에서는 흔한 음절만 한 토큰이 되고 나머지는 여러 바이트 조각으로 쪼개진다. 같은 내용을 말해도 토큰이 더 많으니 API 비용이 비싸고, 같은 문맥 창에 담기는 글이 짧고, 생성도 느리다. 또 토큰 하나를 디코딩하면 깨진 UTF-8이 나올 수 있어서, 스트리밍 출력은 바이트를 모았다가 글자가 완성될 때 내보내야 한다.
    • Glitch token: GPT-2/3 토크나이저에는 ” SolidGoldMagikarp” 같은 토큰이 있었다. 토크나이저 학습 데이터(특정 Reddit 사용자명 등)에는 많이 나왔지만 모델 학습 데이터에는 거의 없던 문자열이다. embedding이 사실상 초기값에 머문 이 토큰들을 입력하면 모델이 그 단어를 반복하지 못하거나 엉뚱한 말을 했다(Rumbelow & Watkins, 2023). Land & Bartolo(2024)는 여러 공개 모델에서 이런 under-trained 토큰을 자동으로 찾아냈다. 교훈은 토크나이저와 모델의 학습 데이터 분포가 어긋나면 안 된다는 것이다.

    직접 구현하기

    아래는 minbpe와 같은 구조의 byte-level BPE다. 학습(train), 인코딩(encode), 디코딩(decode)이 전부 표준 라이브러리만으로 40줄이다.

    Python byte-level BPE: 학습 · 인코딩 · 디코딩 · 왕복 확인
    def get_stats(ids, counts=None):
        counts = {} if counts is None else counts
        for pair in zip(ids, ids[1:]):
            counts[pair] = counts.get(pair, 0) + 1
        return counts
    
    def merge(ids, pair, idx):
        out, i = [], 0
        while i < len(ids):
            if i < len(ids) - 1 and (ids[i], ids[i + 1]) == pair:
                out.append(idx); i += 2
            else:
                out.append(ids[i]); i += 1
        return out
    
    def train(text, vocab_size):
        ids = list(text.encode("utf-8"))
        merges, vocab = {}, {i: bytes([i]) for i in range(256)}
        for idx in range(256, vocab_size):
            stats = get_stats(ids)
            pair = max(stats, key=stats.get)           # 가장 자주 붙어 나오는 쌍
            if stats[pair] < 2:
                break
            ids = merge(ids, pair, idx)
            merges[pair] = idx
            vocab[idx] = vocab[pair[0]] + vocab[pair[1]]
        return merges, vocab
    
    def encode(text, merges):
        ids = list(text.encode("utf-8"))
        while len(ids) >= 2:
            stats = get_stats(ids)
            pair = min(stats, key=lambda p: merges.get(p, float("inf")))  # 가장 먼저 배운 merge
            if pair not in merges:
                break
            ids = merge(ids, pair, merges[pair])
        return ids
    
    def decode(ids, vocab):
        return b"".join(vocab[i] for i in ids).decode("utf-8", errors="replace")
    
    corpus = (
        "the model predicts the next token. the tokenizer turns text into tokens. "
        "a lower loss means the model predicts the next token better. "
        "언어 모델은 다음 토큰을 예측한다. 토크나이저는 글을 토큰으로 바꾼다. "
        "토큰이 짧으면 시퀀스가 길어지고, 토큰이 길면 어휘가 커진다. "
    ) * 4
    merges, vocab = train(corpus, 256 + 120)
    print(f"merge {len(merges)}개 학습, vocab = {len(vocab)}")
    show = lambda b: "[" + b.decode("utf-8", errors="backslashreplace").replace(" ", "␣") + "]"
    for (a, b), z in list(merges.items())[:8]:
        print(f"  #{z - 255:>3}: {show(vocab[a]):>14} + {show(vocab[b]):<10} -> {show(vocab[z])}")
    
    for s in ["the next token", "다음 토큰을 예측한다", "unseen words 🤖 처음 보는 글자"]:
        ids = encode(s, merges)
        assert decode(ids, vocab) == s                 # 왕복(round-trip) 확인
        nb = len(s.encode("utf-8"))
        print(f"\n{s!r}: {nb} bytes -> {len(ids)} tokens ({nb / len(ids):.2f} bytes/token)")
        print("  ", "".join(show(vocab[i]) for i in ids))
    print("\nround-trip OK")
     

    영어는 학습 데이터에 자주 나온 ” token” 같은 단어가 통째로 한 토큰이 된다. 한국어는 같은 양의 데이터에서도 “토큰”처럼 아주 자주 나온 말 말고는 음절이 바이트 조각으로 남는다. [\xec\x9d]처럼 보이는 것이 글자 경계에 맞지 않는 바이트 조각 토큰이다. 마지막 문장의 이모지처럼 학습 데이터에 없던 문자는 바이트 단위로 남지만, 왕복은 어느 경우에도 정확하다. 다음 블록은 special token과 pre-tokenization, 그리고 숫자 문제를 본다.

    Python special token, pre-tokenization, 숫자
    import re
    
    SPECIAL = {"<|endoftext|>": 1000, "<|im_start|>": 1001, "<|im_end|>": 1002}
    inv_special = {v: k for k, v in SPECIAL.items()}
    
    def encode_chat(text, merges, allow_special=True):
        if not allow_special:
            return encode(text, merges)                # 사용자 입력: 특수 문자열도 평범한 바이트로
        parts = re.split("(" + "|".join(re.escape(s) for s in SPECIAL) + ")", text)
        ids = []
        for p in parts:
            ids += [SPECIAL[p]] if p in SPECIAL else encode(p, merges)
        return ids
    
    def decode_chat(ids):
        return "".join(inv_special[i] if i in inv_special else decode([i], vocab) for i in ids)
    
    msg = "<|im_start|>user\nthe model<|im_end|>"
    a = encode_chat(msg, merges, allow_special=True)
    b = encode_chat(msg, merges, allow_special=False)
    print(f"template이 넣은 special token: {len(a)} 토큰 -> {a}")
    print(f"사용자 글 안의 같은 문자열 : {len(b)} 토큰 (special id 없음: {not set(b) & set(SPECIAL.values())})")
    
    # GPT-2식 pre-tokenization (단순화): 앞 공백 + 글자 / 숫자 / 기타 덩어리
    PAT = re.compile(r" ?[A-Za-z가-힣]+| ?\d+| ?[^\sA-Za-z가-힣\d]+|\s+")
    print("\npre-tokenize:", PAT.findall("the model's loss: 1234, 다음 토큰!"))
    
    # 숫자: 숫자로만 학습한 BPE도 비슷한 숫자를 서로 다른 경계로 자른다
    import random
    r = random.Random(0)
    nums = " ".join(str(int(10 ** r.uniform(1, 5))) for _ in range(400)) + " "
    m_num, v_num = train(nums, 256 + 80)
    print()
    for s in [" 1234", " 12345", " 12346", " 2024", " 999"]:
        print(f"{s!r:>9} -> {'|'.join(v_num[i].decode() for i in encode(s, m_num))}")
     

    숫자 결과를 보면 ” 12345”는 12|34|5로, 한 자리만 다른 ” 12346”은 12|3|46으로 잘린다. 같은 자리의 숫자가 토큰마다 다른 위치에 들어가니, 모델은 “12345 + 1” 같은 계산을 하려면 자릿값을 토큰 경계와 무관하게 다시 맞춰야 한다. 숫자를 세 자리씩 고정해서 자르는 pre-tokenization이 이 문제를 완화한다.

    확인 문제Check yourself

    byte-level BPE 토크나이저에 학습 데이터에서 한 번도 본 적 없는 문자(예: 새로운 이모지)가 들어오면?

    초기 어휘가 바이트 256개 전부이므로 어떤 문자열도 바이트열로는 표현된다. 처음 보는 문자는 merge가 적용되지 않아 길어질 뿐이고, 디코딩은 바이트를 이어 붙이므로 손실이 없다. 이것이 GPT-2가 byte-level로 간 이유다.

    확인 문제Check yourself

    vocab을 32K에서 128K로 키울 때 일반적으로 일어나는 일이 아닌 것은?

    byte-level BPE는 어휘 크기와 무관하게 모든 바이트를 포함하므로 표현력은 그대로다. 어휘를 키우면 시퀀스는 짧아지고(VV가 클수록 토큰당 바이트 수 증가), 행렬은 V×dV \times d로 커지며, 어휘 끝쪽 토큰은 드물어진다.

    정리

    • subword 토큰화는 문자 단위(긴 시퀀스)와 단어 단위(거대한 어휘, OOV) 사이의 절충이다.
    • Byte-level BPE: 바이트 256개에서 시작해 가장 잦은 인접 쌍을 반복해서 합친다. 인코딩은 merge를 학습 순서대로 적용, 디코딩은 바이트 이어 붙이기. <UNK>가 없다.
    • 어휘 크기는 시퀀스 길이(계산·문맥) ↔ 행렬 크기·희소 토큰의 트레이드오프다.
    • Special token은 BPE 밖에서 따로 처리하고, 사용자 입력 안의 같은 문자열과 구분해야 한다.
    • 숫자 분할, 공백, 한국어 바이트 조각, glitch token은 모두 토크나이저 설계에서 나오는 부작용이다.

    더 읽을거리Further reading