advanced25 min studyLesson 621 in Engineering

Conversation schemas become exact token sequences

Preserve roles, turn boundaries, and tokenizer/template identity before treating an example as training data.

On this page

What you’ll understand

  • Distinguish structured messages from their serialized model input.
  • Version a tokenizer and chat template with the base checkpoint.
  • Validate roles and boundaries without assuming all model families share a format.

An instruction example is more than a prompt and a good-looking answer. A conversational model sees token IDs produced from a particular message schema, chat template, and tokenizer. Role markers and end-of-turn tokens influence what it learns to continue. A dataset that looks correct in a JSON viewer can train the wrong behavior if its serialization differs from deployment. Start by inspecting the exact sequence and its intended prediction targets.

A message record is not yet a model input

Represent conversations with explicit roles and content under a supported schema. Decide whether system instructions, user turns, assistant responses, and tool interactions are part of the task, and reject records whose roles or ordering violate that contract. A plain concatenation can erase who said what. Conversely, copying one model family's literal control tokens into another family's content can introduce unintended markers. The correct structure follows the selected model and template rather than a universal conversation spelling.

Preserve provenance and quality criteria for the desired assistant responses. Supervised instruction tuning teaches the supplied continuation, including its mistakes, format, and omissions; it does not automatically establish truthfulness or broad instruction-following ability. A synthetic or human-authored example still needs validation against the actual task. Distinguish supervised demonstrations from preference optimization or reinforcement learning stages instead of calling all post-training methods the same objective.

x=Tokenize⁡τ ⁣(Template⁡c(m1,…,mk))x=\operatorname{Tokenize}_{\tau}\!\left(\operatorname{Template}_{c}(m_1,\ldots,m_k)\right)
Messages m are serialized by template c and tokenizer τ into token-ID sequence x. τ and c are versioned artifacts tied to the model; the expression does not imply equivalent text produces identical IDs under different tokenizers.↔ Scroll wide equations horizontally.

Special tokens and generation prefixes have a contract

Transformers 4.57.1 documents chat templates as model-specific formatting and warns that separately adding special tokens after a template can duplicate them. In that version, template-and-tokenize together is a supported route; if formatting text first, subsequent tokenization must follow the documented special-token setting. A training example containing a completed assistant answer differs from an inference prompt that opens a new assistant turn. Do not append a generation prefix to completed targets blindly.

An end-of-turn token and an end-of-sequence token can coincide in one model family and differ in another. Their identity and placement affect stopping behavior and later loss masks. Preserve tokenizer files, added-token IDs, template revision, and base checkpoint identity together. A tokenizer with the same vocabulary size can still assign different IDs or use different normalization. Testing decoded text alone may conceal duplicated boundary tokens or changed control-token placement.

Ntotal=Ncontent+Nrole+Nboundary+NprefixN_{\rm total}=N_{\rm content}+N_{\rm role}+N_{\rm boundary}+N_{\rm prefix}
All terms count tokens in one explicitly inspected serialization, with nonoverlapping categories. This is an accounting identity, not a prediction from character count or a universal formula for a named model's template.↔ Scroll wide equations horizontally.

Inspect examples after the complete pipeline

Render representative single-turn, multi-turn, empty, and tool-bearing records through the exact preprocessing path. Inspect token IDs, decoded boundaries, attention masks, and target masks. Include content containing strings resembling control markers and follow the template's supported handling; a structured role field does not guarantee the model is immune to adversarial instructions inside content. Confirm deployment uses the same intended conversation format and stopping rules before comparing generations across checkpoints.

The cache lab is only an identity-version contrast. Reset and set both C=4, s=4, predict twelve hits among the initial sixteen address requests, then Step to add one hit. The empty-start fully associative LRU trace caps at 4096 requests and has no tokenizer or chat template. A matching abstract key does not prove two serialized examples are interchangeable. Explain which base, tokenizer, template, and schema revisions a real preprocessing-cache key would need to preserve.

Count a declared toy serialization

A toy tokenizer yields four system-content tokens, six user-content tokens, and five assistant-content tokens. Its template adds two role tokens per message, one end token per message, and one initial prefix token. These are declared toy counts, not a real model's tokenizer output.

  1. Content contributes 4+6+5=15 tokens. Three messages add 3×2=6 role tokens and three boundary tokens.

  2. Including the one-token prefix gives 15+6+3+1=25 total tokens. Counting only the visible assistant answer would miss twenty tokens of context and formatting.

  3. If another stage adds a duplicate prefix and end token, total length becomes 27 and the token sequence changes. Remove duplication according to the actual template contract rather than assuming those extra IDs are harmless.

The result

Exact token accounting requires the complete template and tokenizer. Raw message text or vocabulary size cannot substitute for that artifact identity.

Explore the model

Interactive lab

Interactive lab · cache

Preprocessing reuse needs artifact identity

Reset, set C=4, s=4;predict 12 hits in 16 requests, then Step adds one hit. This capped 4096-request LRU model has no conversations, tokenizer IDs, templates, or role semantics.

Preprocessing reuse needs artifact identityA 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 forA preprocessing cache must preserve the identities that determine the actual serialized token sequence.

Check your understanding

Two tokenizers have the same vocabulary size. What follows about the same formatted conversation?

Try it yourself

A dataset stores user and assistant fields but deployment uses an additional system message and a different chat template. Name the comparison needed before attributing generation changes to adapter quality.

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

Give me a hint

Inspect the exact token sequence and inference prefix produced by both paths.

Compare with the solution

Run representative examples through the training and deployment serializers using pinned tokenizer/template revisions, then compare IDs, roles, boundaries, truncation, and stopping behavior. An apparent model-quality regression can come from formatting mismatch. Align the intended input contract or evaluate that difference explicitly before claiming the adapter itself caused the change.

Take it with you

  • Structured messages become model-specific token sequences.
  • Role and boundary tokens belong to the training and serving contract.
  • Pin and inspect base, tokenizer, template, schema, and stopping behavior together.

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.