Pidoku

Tokenization and Its Consequences

Module 12 Lesson 12.b 1h Difficulty 2/5

Prerequisites 10.f (embeddings), 12.a


Before you start#

TermPlain meaning
TokenOne piece of text the model treats as a unit, stored as an integer ID.
VocabularyThe fixed list of every token a model knows. Its size is fixed at training time.
TokenizerThe program that turns text into token IDs (encoding) and back (decoding).
Embedding tableA table with one row of numbers per vocabulary entry; the model’s first step looks up each token’s row (10.f).
Special tokenA token that marks structure, not text: start of a message, end of a turn, a tool call.
Chat templateThe exact layout of special tokens and text a chat model was trained on.

1. What is it?#

Tokenization converts text into integers the model can process, and converts the model’s output integers back into text.

"Hello, world!"  →  [9906, 11, 1917, 0]  →  model  →  [2028, 374, ...]  →  "This is..."

Every modern language model uses subword tokenization: common words are one token, rarer words are split into pieces, and any string at all — any language, code, emoji, raw bytes — can be represented. There is no “unknown word”.


2. Why does it exist?#

The two obvious alternatives both fail:

Characters:  a vocabulary of ~256, but text becomes ~4x more tokens
             → 4x more decode steps, 4x more KV cache. Far too slow.
Words:       a vocabulary of millions, a gigantic embedding table,
             and any new word (a name, a typo, a URL) cannot be represented.

Subword tokenization sits in between: a vocabulary of roughly 100,000–200,000 entries, about four characters per token in English, and complete coverage.

For inference engineering the key point is this: tokens are the unit of work, the unit of cost and the unit of memory. Prefill time, decode steps, KV cache size and the price users pay are all counted in tokens (12.a). How text turns into tokens directly decides how much capacity you need.


3. Simple analogy#

Shorthand. A stenographer has short symbols for common phrases and spells unusual words out letter by letter. That is efficient for the language the shorthand was designed for and wasteful for anything else — which is exactly why a tokenizer trained mostly on English text needs more tokens for Thai, Telugu or minified JSON.


4. Tiny example#

Counting by hand#

Take the sentence The cats sat. A typical tokenizer splits it as:

"The" | " cats" | " sat" | "."      → 4 tokens, 13 characters → 3.25 characters per token

Notice that the space usually belongs to the following word (" cats"), and that "cats" may be one token or " cat" + "s" depending on the vocabulary.

Counting with a real server#

This program asks a running vLLM server how it tokenizes some strings (llama.cpp’s server works the same way with {"content": s}):

Go
// tokens.go — ask a running server how it tokenizes text.
// Works with vLLM (POST /tokenize); for llama.cpp's server send {"content": s} instead.
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"unicode/utf8"
)

func countTokens(base, model, s string) (int, error) {
	body, _ := json.Marshal(map[string]any{"model": model, "prompt": s, "add_special_tokens": false})
	resp, err := http.Post(base+"/tokenize", "application/json", bytes.NewReader(body))
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()
	var out struct {
		Tokens []int `json:"tokens"`
	}
	err = json.NewDecoder(resp.Body).Decode(&out)
	return len(out.Tokens), err
}

func main() {
	base, model := "http://localhost:8000", "Qwen/Qwen3-0.6B"
	if len(os.Args) > 2 {
		base, model = os.Args[1], os.Args[2]
	}
	for _, s := range []string{
		"Hello world",
		"supercalifragilisticexpialidocious",
		"def fibonacci(n):",
		"こんにちは世界",
		"🎉🎊🎈",
		"1234567890",
	} {
		n, err := countTokens(base, model, s)
		if err != nil || n == 0 {
			fmt.Println("tokenize failed:", err)
			return
		}
		chars := utf8.RuneCountInString(s)
		fmt.Printf("%3d chars → %3d tokens  (%.1f c/t)  %s\n", chars, n, float64(chars)/float64(n), s)
	}
}

Typical output (exact numbers differ by tokenizer):

 11 chars →   2 tokens  (5.5 c/t)  Hello world
 34 chars →   9 tokens  (3.8 c/t)  supercalifragilisticexpialidocious
 17 chars →   6 tokens  (2.8 c/t)  def fibonacci(n):
  7 chars →   5 tokens  (1.4 c/t)  こんにちは世界
  3 chars →   9 tokens  (0.3 c/t)  🎉🎊🎈
 10 chars →   4 tokens  (2.5 c/t)  1234567890

Look at the spread: 5.5 down to 0.3 characters per token. The same meaning in Japanese costs several times more tokens than in English, and an emoji can cost three tokens. That is a real cost and fairness issue: identical messages in different languages cost users different amounts and use different amounts of your GPU.


5. Technical explanation#

BPE (byte-pair encoding), the dominant algorithm#

Training a tokenizer:

1. Start with a vocabulary of the 256 possible bytes.
2. Count every pair of adjacent tokens in a large training text.
3. Merge the most frequent pair into a new token.
4. Repeat until the vocabulary reaches its target size.

Encoding new text applies the learned merges in the order they were learned:

"lower"  →  l o w e r
merge (e,r)  → er:   l o w er
merge (l,o)  → lo:   lo w er
merge (lo,w) → low:  low er
→ ["low", "er"]

Variants you will meet: byte-level BPE (GPT-2 onward, and nearly every 2026 model) works on raw bytes, so nothing is unrepresentable; SentencePiece with the Unigram method (T5, Llama 1 and 2, some multilingual models) chooses splits with a probability model instead of greedy merges; WordPiece (BERT) is BPE with a different merge rule.

Vocabulary sizes of current models#

Checked on 11 November 2026 against each model’s published configuration:

Model familyVocabulary (embedding rows)
Llama 3.x128,256
DeepSeek-V3 / V3.2129,280
Qwen3 (dense, MoE and Next)151,936
Kimi K2163,840
gpt-oss (o200k_harmony)201,088

The trend since 2023 (when 32,000 was common) is toward larger vocabularies: more text per token means fewer decode steps and a smaller KV cache for the same content, at the price of a bigger embedding table and a bigger final layer that scores every vocabulary entry on every step.

Special tokens and chat templates#

Chat models are trained on text laid out in an exact format, marked with special tokens. A Llama-3-style template looks like this:

<|begin_of_text|><|start_header_id|>system<|end_header_id|>

You are helpful.<|eot_id|><|start_header_id|>user<|end_header_id|>

Hello<|eot_id|><|start_header_id|>assistant<|end_header_id|>

Templates in 2026 carry more than roles:

  • Reasoning sections. Models such as Qwen3 and DeepSeek-R1 write their thinking between markers like <think> … </think>; gpt-oss uses the harmony format with separate channels for analysis and the final answer. The server must know where reasoning ends to return it separately (17.i).
  • Tool calls and tool results have their own tokens or formats, and the server parses them back into structured JSON (17.i).
  • The template ships with the model as a Jinja file (chat_template.jinja or inside tokenizer_config.json), and engines apply it for you on the chat endpoint.

A wrong template degrades quality badly and raises no error. The model was trained on one exact layout; anything else puts it outside what it learned. Always use the model’s own template (the server’s chat endpoint, or apply_chat_template in the tokenizer library); never assemble the string by hand.

Incremental detokenization — a common bug#

When streaming, you cannot decode each new token on its own and print it:

Go
// WRONG
for _, id := range generated {
	send(string(vocab[id])) // a token is BYTES, not a string: this splits multi-byte characters
}

Two problems:

  1. One character can span several tokens. A Japanese character or an emoji is 3–4 bytes in UTF-8, and byte-level BPE may split those bytes across tokens. Decoding a partial character produces the replacement character �.
  2. Leading spaces. Many tokenizers store " world" as one token; decoding it alone may or may not keep the space, depending on settings.

The fix is to keep state and only emit complete characters:

Go
// Correct pattern: buffer bytes, emit only complete UTF-8 characters.
var pending []byte
for _, id := range generated {
	pending = append(pending, vocab[id]...) // vocab[id] is the token's raw bytes
	n := 0
	for n < len(pending) && utf8.FullRune(pending[n:]) { // is a whole character available?
		_, size := utf8.DecodeRune(pending[n:])
		n += size
	}
	if n > 0 {
		send(string(pending[:n]))
		pending = pending[n:] // an incomplete tail (if any) waits for the next token
	}
}

Engines use a faster incremental decoder (16.f shows vLLM’s), but the rule is the same: decode what has accumulated, emit only the new complete part, hold back incomplete characters.

Stop sequences#

Users can ask generation to stop at strings like "\n\n" or "</answer>". The model emits tokens, and a stop string can span token boundaries or end in the middle of a token. Correct handling:

1. Accumulate decoded text.
2. Look for the stop string in the accumulated text.
3. When found, cut the output at that position — possibly in the middle of a token.
4. If the text ends with the *start* of a stop string, hold it back; it may complete next step.

Point 4 is subtle: with stop string "END" and output ending in "EN", you must not stream "EN" yet, because the next token may complete the stop string, which should never be shown.


6. Under the hood#

Tokenization is CPU work on the critical path of time to first token:

Pure-Python BPE:                    ~0.1–1 MB/s     ← unusable at scale
Hugging Face `tokenizers` (Rust):   ~10–100 MB/s
tiktoken (Rust):                    ~50–200 MB/s

A 100,000-token prompt is about 400 KB of text: seconds in pure Python, milliseconds in Rust. Engines always use the fast tokenizers, run them in parallel worker threads or processes, and increasingly move the whole frontend out of Python — vLLM has an optional Rust frontend (19.h). At high request rates with long prompts, tokenization alone can need several CPU cores; starving it leaves the GPU idle (3.e).


7. Performance implications#

  • Token count drives everything: prefill work, KV memory, decode steps, cost.
  • Language changes cost 2–5x for the same meaning.
  • Code and structured data tokenize poorly: punctuation-heavy JSON can be ~2 characters per token.
  • Vocabulary size is a trade-off: a bigger vocabulary means fewer tokens per text, but the final layer that scores all vocabulary entries does more work and uses more memory every step. With a 200,000-entry vocabulary and a hidden size of a few thousand, that layer is around a billion parameters — noticeable in small models.

8. Production implications#

  • Bill and rate-limit in tokens, counted on the server. Never trust client counts.
  • Offer a token-counting endpoint so clients can estimate cost before sending.
  • Cap input length and max_tokens in tokens, and remember reasoning tokens count toward output.
  • Use the model’s chat template. Never build prompts by hand.
  • Test streaming with non-Latin scripts and emoji in CI. Detokenization bugs ship constantly.
  • Handle partial stop strings or they leak into user output.
  • Consider the language cost gap in pricing if you serve users worldwide.

9. Common mistakes#

  1. Decoding tokens one by one. Garbled text for non-English output.
  2. Hand-building chat prompts. Silent quality loss.
  3. Estimating tokens as characters ÷ 4. Wrong by 2–5x for non-English text and code.
  4. Using a slow pure-Python tokenizer. Seconds added to time to first token.
  5. Forgetting template overhead in length limits. System prompt, roles and tool definitions can add hundreds or thousands of tokens.
  6. Streaming a partial stop string. The user sees “END” flash and disappear.
  7. Using a tokenizer from a different model. Valid-looking garbage.

10. Hands-on exercise#

A. The language tax. Tokenize the same paragraph in eight languages with one model’s tokenizer. Build a table of characters per token. What is the ratio between the most and least efficient language? Repeat with a model that has a different vocabulary size.

B. Break detokenization. Stream text containing emoji and Japanese, decoding each token independently, and observe the garbling. Then implement the incremental decoder above and confirm the fix.

C. Tokenizer speed. Time tokenization of a 100,000-character document with a fast (Rust) and a slow (pure Python) tokenizer.

D. Template cost. Print the rendered chat template for a 10-turn conversation with two tool definitions. How many tokens are template overhead?

E. Stop strings. Implement stop-string handling and test a stop string split across two tokens and a partial match at the end of generation.


11. Interview questions#

  1. Why do language models use subword tokens rather than characters or words?
  2. Explain how BPE is trained and how it encodes text.
  3. Why can’t you decode generated tokens one at a time and concatenate them?
  4. Why does the same content cost more in Japanese than in English?
  5. What is a chat template, what does it contain in a reasoning model, and what happens if you get it wrong?
  6. How do you handle a stop sequence that spans token boundaries?
  7. What are the trade-offs of a larger vocabulary?

12. Further reading#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in