advanced28 min studyLesson 612 in Engineering

Freeze the tokenizer as part of the experiment

Balance vocabulary parameters, sequence lengths, normalization, corpus sampling, and held-out separation without mistaking token-level loss for a tokenizer-independent metric.

On this page

What you’ll understand

  • Define a tokenizer-training split and a versioned serialization contract.
  • Calculate embedding storage and a conditional sequence-length cost change.
  • Explain why held-out adaptation and cross-tokenizer perplexity need explicit treatment.

A tokenizer is learned preprocessing with a storage and evaluation contract. Its vocabulary, merge or segmentation model, normalization, special tokens, and byte fallback determine the sequences the network receives. Training two models on the same raw documents with different tokenizers can change the token budget, context coverage, and output-layer size simultaneously. Freeze that representation before interpreting a pretraining comparison. A smaller reported loss per token may reflect different prediction units rather than a better probability model for the same serialized text.

Separate fitting data from later evaluation

Train the tokenizer on a documented sample drawn from the permitted training partition, preserving the sample identities or reproducible selection rule. Do not fit vocabulary or normalization statistics on the final held-out evaluation text and then describe that evaluation as untouched by representation selection. Tokenizer fitting is not the same as updating language-model weights, but it still adapts the experiment to data. Development data may support declared design choices; reserve a separate final test when independent assessment is required.

SentencePiece's original paper and pinned v0.2.0 documentation describe trainable subword models and normalization as parts of a reusable tokenizer artifact. The BPE paper explains learning subword units from corpus statistics. Their existence does not prescribe a universally optimal vocabulary size or domain sample. Inspect coverage across scripts, code, whitespace, and malformed-input policy using permitted diagnostic material. Keep added special-token IDs and encode/decode behavior in fixtures, since changing those after training can reinterpret model embedding rows.

Nemb=Vd,Memb=VdbN_{\rm emb}=Vd,\qquad M_{\rm emb}=Vdb
V is vocabulary entries, d embedding width, and b bytes per stored parameter, giving bytes M_emb for one dense matrix. Tied input/output weights can share that matrix; untied weights require another appropriate matrix. Optimizer states, gradients, padding to hardware-friendly sizes, and all other parameters are excluded.↔ Scroll wide equations horizontally.

Vocabulary and sequence length change different costs

A larger vocabulary allocates more rows to input embeddings and often expands the output projection. It may shorten some serialized documents by representing frequent strings with fewer tokens, but the effect varies by language and domain. A smaller vocabulary can reduce those rows while increasing sequence length or fragmenting rare scripts. Measure the actual encoded lengths and unknown or fallback behavior on allowed diagnostic sets. The raw number of characters per token is an average, not an admission guarantee for every document.

Within a dense attention score calculation with fixed width and one sequence, reducing length from four thousand to three thousand changes its quadratic position-pair count. That calculation does not imply the entire training step becomes equally cheaper: feed-forward work, softmax over vocabulary, kernel choices, block packing, and memory overhead can change differently. Fixed token-budget comparisons also expose different amounts of raw text when tokenizers differ. State which resource is held fixed before crediting an improvement to representation quality.

Q(3000)Q(4000)=(30004000)2=916\frac{Q(3000)}{Q(4000)}=\left(\frac{3000}{4000}\right)^2=\frac9{16}
Q(n) is a hypothetical dense attention position-pair work term proportional to n² with all other factors fixed. The ratio is dimensionless and applies to that term only, not complete training time, memory use of every attention implementation, or a measured tokenizer speedup.↔ Scroll wide equations horizontally.

Version the full text-to-ID path

Save the tokenizer artifact, its training configuration, library version, corpus sample reference, normalization policy, vocabulary and special-token mapping, and a digest for integrity comparison. Include representative round-trip fixtures under the documented normalization contract; lossless recovery of every original byte should not be promised if normalization intentionally changes text. Changing a tokenizer after a model has trained usually requires a deliberate compatibility or retraining plan rather than merely replacing a filename. A familiar-looking token string can still map to a different row.

The cache lab isolates lookup reuse under a fixed, artificial identifier stream. Reset, set both capacity C=4 and stride s=4, predict twelve hits over the sixteen initial requests, then Play or Step. Reset and set both C=4,s=1 for a zero-hit comparison with more distinct identifiers. Playback caps at 4,096 requests. This can motivate inspecting embedding-access patterns, but the model has no learned vocabulary, token frequencies, merge rules, variable-sized embedding rows, or processor-cache hierarchy; it cannot choose a tokenizer for you.

Budget the extra embedding rows

Compare fictional vocabulary sizes 32,000 and 48,000 at width 1,024 with two bytes per parameter. Count one tied dense embedding/output matrix only, and use binary MiB equal to 1,048,576 bytes.

  1. The smaller matrix contains 32,000×1,024=32,768,000 parameters and occupies 65,536,000 bytes, or 62.5 MiB.

  2. The larger matrix contains 48,000×1,024=49,152,000 parameters and occupies 98,304,000 bytes, or 93.75 MiB.

  3. The increase is 16,384,000 parameters and 32,768,000 bytes, or 31.25 MiB. Any sequence-length saving must be measured separately before deciding whether the larger vocabulary improves the experiment's chosen resource budget.

The result

The larger vocabulary adds 31.25 MiB to this one stored matrix. The calculation excludes optimizer state and does not predict a complete training-speed or quality improvement.

Explore the model

Interactive lab

Interactive lab · cache

Inspect lookup diversity under a fixed capacity

Compare fresh Reset → set both C=4,s=4 and Reset → set both C=4,s=1. Predict twelve versus zero hits among the initial sixteen requests, then Play or Step. The LRU stream caps at 4,096 and is not a tokenizer or a physical embedding-cache benchmark.

Inspect lookup diversity under a fixed capacityA fully associative LRU cache starts empty and requests address (i·s) mod 16. Hits move an address to the newest position; misses evict the oldest when full. Playback starts with 16 requests and adds two per second, capped at 4096 explicitly simulated requests. This toy stream is not a processor-cache benchmark. Current readings: Hits / requests: 0 / 16; Hit rate: 0%; Address-stream period: 16 addresses. All parameters are adjustable with the labeled controls below.Fully associative LRU cache after 16 deterministic requests: 0 hits and 16 misses.Most recent 16 requestsaddress = i × 3 mod 160M3M6M9M12M15M2M5M8M11M14M1M4M7M10M13MCurrent cache order · oldest → newest471013Latest address 13 · miss: inserted as newestToy address stream · period 16 · starts empty
Cached addressMiss / evictionMost recent request
Hits / requests
0 / 16
Hit rate
0%
Address-stream period
16 addresses
t = 0 s

A fully associative LRU cache starts empty and requests address (i·s) mod 16. Hits move an address to the newest position; misses evict the oldest when full. Playback starts with 16 requests and adds two per second, capped at 4096 explicitly simulated requests. This toy stream is not a processor-cache benchmark. 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 forRepresentation size and access locality are distinct quantities that require separate evidence.

Check your understanding

A tokenizer is fitted on the final held-out evaluation documents before language-model training. What should the experiment report?

Try it yourself

Tokenizer A produces four thousand tokens for a document, and tokenizer B produces three thousand. If one dense attention work term is proportional to length squared, what relative work does B have, and why is that not a valid full-step speed claim?

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

Give me a hint

Compute the squared ratio, then list work terms whose size or implementation did not appear in that calculation.

Compare with the solution

The ratio is (3000/4000)²=0.5625, so that attention term is 43.75% smaller under the stated fixed factors. Full-step work also includes vocabulary projection, feed-forward computation, packing, memory movement, and other kernels; B may have a larger vocabulary or different block utilization. A synchronized measurement over equivalent declared raw-text or token exposure is needed for the actual speed comparison. The squared ratio alone measures neither language quality nor end-to-end throughput.

Take it with you

  • Tokenizer fitting, normalization, special IDs, and training samples belong to the experiment manifest.
  • Vocabulary rows and sequence lengths change different storage and compute terms.
  • Per-token metrics and fixed-token exposure depend on the frozen tokenizer.

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.