advanced29 min studyLesson 61 in Engineering

Tokenization and vocabulary design

Connect subword representations to context use, embedding memory, language coverage, and reproducible model inputs.

On this page

What you’ll understand

  • Explain how learned subword vocabularies trade sequence length against vocabulary size.
  • Calculate embedding storage and usable context from explicit tokenizer assumptions.
  • Version normalization, special tokens, and chat formatting with the model.

A language model consumes identifiers, not words as people perceive them. The string delivered by an application passes through normalization, segmentation, vocabulary lookup, and often a conversation template before reaching the model. Changing any stage changes the numerical input. Tokenization therefore belongs in the model artifact and capacity plan: it affects which text fits in context, how much attention work is needed, and whose language receives an efficient representation.

A vocabulary is a representation contract

Word vocabularies make frequent words compact but struggle with unseen names and productive morphology. Character or byte representations cover a smaller alphabet while producing longer sequences. Subword methods occupy the middle: common fragments can have their own identifiers, while less common text decomposes into smaller pieces. Byte-pair encoding repeatedly merges frequent adjacent units during vocabulary construction. Applying a learned tokenizer uses its fixed vocabulary and rules; it does not relearn merges from every incoming request.

SentencePiece describes tokenization directly from raw text without requiring a language-specific word splitter. Its implementation supports different segmentation models; the library name is not synonymous with one algorithm. Distinguish vocabulary coverage from preservation of the original input. A normalizer can merge visually similar or canonically related strings, and a tokenizer without an appropriate fallback may emit an unknown symbol. Test round trips under the declared normalization policy, including whitespace, combining marks, code, and unusual scripts.

x→Nx~→EV(t1,…,tT),DV(EV(x~))=x~x\xrightarrow{N}\widetilde{x}\xrightarrow{E_V}(t_1,\ldots,t_T),\qquad D_V(E_V(\widetilde{x}))=\widetilde{x}
N is the declared normalization and E and D are tokenizer encoding and decoding. The round-trip identity is a requirement to test for the supported representation; it does not imply recovery of information deliberately removed by N.↔ Scroll wide equations horizontally.

Sequence length has a systems cost

A larger vocabulary can shorten common sequences but enlarges the input embedding and often the output projection. With tied input and output weights, one matrix can serve both roles; with untied weights, account for both. Vocabulary size also affects the logits produced at each decoding step. Shorter sequences reduce cache growth, but they do not establish an unconditional speedup because kernels, batching, and model dimensions influence the actual bottleneck. Measure complete requests rather than advertising one compression ratio.

Compare token counts on representative languages and domains, not only English prose. The same semantic task may require very different token budgets across scripts, source code, or technical notation. A context limit counts all serialized input, including instructions, tool definitions, retrieved passages, and conversation delimiters. Reserve output space explicitly. A character-per-token average is useful for rough planning, but admission control must encode the actual request with the exact tokenizer to avoid truncation or rejection.

Membed=Vdb,Tinput+Treserved output≤CM_{\mathrm{embed}}=Vdb,\qquad T_{\mathrm{input}}+T_{\mathrm{reserved\ output}}\leq C
V is vocabulary size, d embedding width, and b bytes per stored parameter for one embedding matrix. C is the model's supported token context; extra implementation limits may be smaller.↔ Scroll wide equations horizontally.

Version the entire serialization path

Store tokenizer files, normalization settings, special-token identifiers, and conversation-template revision alongside weights. A token identifier has meaning only relative to that vocabulary. Adding a new token also requires a compatible embedding row and a training or initialization policy; simply changing the text mapping cannot teach a pretrained model the new symbol's meaning. During deployment, compare golden input strings and exact token identifiers between training, offline evaluation, and serving implementations.

Treat truncation as a product decision. Removing the oldest conversation turn can erase a constraint; cutting a document can remove the evidence needed to answer. Apply a deliberate retention policy, count tokens after final formatting, and report when evidence is omitted. Benchmark segmentation length by language and task while also measuring output quality. A tokenizer that saves memory but systematically loses required distinctions is a representation regression, even if aggregate throughput improves.

Budget a vocabulary and a document

A tied embedding has 64,000 entries, width 4,096, and two bytes per parameter. A 24,000-character document averages three characters per token in this illustrative corpus. Context capacity is 12,000 tokens; instructions and formatting consume 1,200, and output reserves 2,000.

  1. Embedding storage is 64,000 × 4,096 × 2 = 524,288,000 bytes, exactly 500 MiB. Tied weights avoid a second separate output matrix of the same shape.

  2. Estimate document length as 24,000/3 = 8,000 tokens. Total context reservation is 8,000 + 1,200 + 2,000 = 11,200 tokens, leaving 800 tokens.

  3. If another tokenizer produces 10,000 document tokens, the total is 13,200 and exceeds capacity by 1,200. Run actual encoding before admission; the character ratio alone cannot certify a fit.

The result

The first estimate fits the token budget, but only exact serialization and encoding can approve the request. Memory figures cover one embedding matrix, excluding every other model tensor.

Explore the model

Interactive lab

Interactive lab · vectors

Representations have coordinates

Change the angle and magnitude of one two-dimensional vector and inspect its coordinate projections. This is a small analogy for numerical representations, not a tokenizer, a learned embedding space, or evidence that semantic similarity has two dimensions.

Representations have coordinatesPlayback traces a fixed vector and its projections. Angle and magnitude set the geometry; the moving marker does not change them. Current readings: x component: 1.393; y component: 0.975; Magnitude: 1.7. All parameters are adjustable with the labeled controls below.−7.46−3.7303.737.46−3.5−1.7501.753.5xyvvₓ = 1.39
Vectorx / y projectionsTrace marker
x component
1.393
y component
0.975
Magnitude
1.7
t = 0 s

Playback traces a fixed vector and its projections. Angle and magnitude set the geometry; the moving marker does not change them. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forA representation needs an explicit coordinate convention; identifiers alone do not carry a model-independent meaning.

Check your understanding

Which change can alter model inputs even when the visible user message is unchanged?

Try it yourself

An untied model uses separate input and output matrices, each with 32,000 tokens, width 2,048, and two-byte parameters. Calculate their combined storage and explain what doubling vocabulary changes.

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Count both matrices, and distinguish vocabulary growth from sequence length changes.

Compare with the solution

One matrix occupies 32,000 × 2,048 × 2 = 131,072,000 bytes, or 125 MiB. Two occupy 250 MiB. Doubling vocabulary doubles those matrices to 500 MiB if width and precision stay fixed. It may shorten some tokenized sequences, but the size and quality of that improvement require corpus-specific measurement.

Take it with you

  • Tokenization is a versioned part of the model, including normalization and formatting.
  • Vocabulary size and sequence length impose different memory and compute costs.
  • Use exact final token counts for admission and representative language coverage for evaluation.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.