Skip to content
AgenticAIWiki
  1. Learn
  2. Part 5
  3. 29. Fine-tuning
  4. 29.8

Lesson 29.8 · 8 of 9 · 6 min read · Reviewed 24 Nov 2026

Chat templates and dataset formatting

By the end, you can

  • Explain what a chat template does and why training and inference must use the same one.
  • Format a fine-tuning dataset so the loss falls only on the assistant's replies.

From messages to one string

A model sees one long sequence of tokensToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id., not a list of messages. A chat template converts this:

[{"role": "system", "content": "You write refund replies."},
 {"role": "user", "content": "Order 1182 arrived broken."},
 {"role": "assistant", "content": "I'm sorry it arrived damaged. I've started a full refund."}]

into something like this (one illustrative style; each family has its own tokens):

<|start|>system
You write refund replies.<|end|>
<|start|>user
Order 1182 arrived broken.<|end|>
<|start|>assistant
I'm sorry it arrived damaged. I've started a full refund.<|end|>

The special tokens tell the model where each turn starts, who is speaking and where it ends. An instruct model learned its template during tuning, so at inference you must use the same template, and when you fine-tuneFine-tuning: Continuing to train a model on your own examples to change its behaviour or specialise it. you must train on it too.

Let the tokenizer apply it

Open-model tokenizersTokenizer: The component that splits text into tokens and maps each token to an id the model can process. usually ship their template. In the Hugging Face libraries you call tokenizer.apply_chat_template(messages) rather than gluing strings yourself. Training libraries such as TRL apply it for you when your dataset has a messages column. Hand-written templates are a classic source of silent bugs: a missing newline or a wrong token is enough.

Dataset formats you will see

Format Shape Use
Conversational {"messages": [...]} per line Chat and instruction tuning; most common
Prompt and completion {"prompt": "...", "completion": "..."} Single-turn tasks
Preference {"prompt", "chosen", "rejected"} DPO and similar (29.4)
Plain text {"text": "..."} Continued pretraining on raw text

Pick one, validate every line against it, and keep the system promptSystem prompt: Instructions passed in the top-level system field that set the model’s role, rules and context for the whole conversation. identical to production (29.2).

Train on the replies

During supervised fine-tuningSupervised fine-tuning (SFT): Fine-tuning on pairs of inputs and ideal outputs. you usually want the model to learn to write the assistant turns, not to predict the user’s words. So the loss is masked: tokens from system and user turns get no loss, assistant tokens do. In TRL this is an option on the trainer config (for example, training only on completions or assistant turns); other libraries have their own switch.

Worked count for the example above, with made-up token counts: system 8, user 9, assistant 16, plus 2 template tokens around each turn. Total about 39 tokens; only the 16 reply tokens plus its end token count towards the loss.

The end token matters

Each assistant reply in training must end with the template’s end-of-turn token. That is how the model learns to stop. Leave it out and the tuned model rambles on, sometimes writing a fake user turn. Also check that the end token isn’t masked away along with the user turns.

Common mistakes

  • Training with one template and serving with another, for example after switching inference servers (30.3).
  • Tuning a base model on a chat template it has never seen, with too little data for it to learn the new tokens.
  • Leaving loss on the prompt, which wastes capacity on imitating users.
  • Truncating long examples so the reply is cut off before its end token.

Key points

  • A chat template turns a list of messages into one token string, with special tokens marking each turn.
  • Each model family has its own template, stored with its tokenizer; using the wrong one quietly degrades quality.
  • Store data as messages (JSONL) and let the tokenizer apply the template, rather than hand-writing token strings.
  • Mask the loss so the model learns from assistant tokens, and end each reply with the end-of-turn token.
Hands-on labRuns in the Playground

Render a chat template with a loss mask

Turn a messages list into a templated token sequence and build the labels so that loss falls only on the assistant's replies and their end tokens.

You will have: A render function that prints the templated text, a token count, the number of tokens with loss, and a check that every reply ends with the end token.

Steps

  1. Write render: wrap each message as <|start|>role, newline, content, <|end|>.
  2. Split the result into toy tokens (words and special tokens) and record which message each token came from.
  3. Build labels: the token itself for assistant content and its end token, None for everything else.
  4. Print the share of tokens with loss.
  5. Check that every assistant reply ends with <|end|>, and that the misspelt role in the second example is rejected.

Done when

  • The first example has 13 tokens with loss out of 31.
  • The end-token check prints ok for the first example.
  • The second example is rejected for an unknown role.

Open in the Playground No API key needed.

Starter code (Python)
import re

EXAMPLES = [
    [{"role": "system", "content": "You write refund replies."},
     {"role": "user", "content": "Order 1182 arrived broken."},
     {"role": "assistant", "content": "I'm sorry it arrived damaged. I've started a full refund."}],
    [{"role": "user", "content": "Can I get a cash refund?"},
     {"role": "assistent", "content": "I can't arrange cash refunds."}],
]
ROLES = {"system", "user", "assistant"}

def tokens(text):
    return re.findall(r"<\|\w+\|>|[\w']+|[^\w\s]", text)

def render(messages):
    # TODO: return a list of (token, trained) pairs; raise ValueError on an unknown role
    return []

for ex in EXAMPLES:
    try:
        toks = render(ex)
        print(len(toks), "tokens")
    except ValueError as e:
        print("rejected:", e)
Show a solution
import re

EXAMPLES = [
    [{"role": "system", "content": "You write refund replies."},
     {"role": "user", "content": "Order 1182 arrived broken."},
     {"role": "assistant", "content": "I'm sorry it arrived damaged. I've started a full refund."}],
    [{"role": "user", "content": "Can I get a cash refund?"},
     {"role": "assistent", "content": "I can't arrange cash refunds."}],
]
ROLES = {"system", "user", "assistant"}

def tokens(text):
    return re.findall(r"<\|\w+\|>|[\w']+|[^\w\s]", text)

def render(messages):
    out = []
    for m in messages:
        if m["role"] not in ROLES:
            raise ValueError(f"unknown role {m['role']!r}")
        trained = m["role"] == "assistant"
        out += [(t, False) for t in tokens(f"<|start|>{m['role']}")]
        out += [(t, trained) for t in tokens(m["content"])]
        out.append(("<|end|>", trained))
    return out

for i, ex in enumerate(EXAMPLES, start=1):
    try:
        toks = render(ex)
    except ValueError as e:
        print(f"example {i}: rejected: {e}")
        continue
    loss = sum(t for _, t in toks)
    print(f"example {i}: " + " ".join(tok if trained else f"[{tok}]" for tok, trained in toks))
    print(f"example {i}: {loss} of {len(toks)} tokens with loss ({loss / len(toks):.0%})")
    ends_ok = all(toks[j + 1][0] == "<|end|>" for j in range(len(toks) - 1) if toks[j][1] and toks[j + 1][0] == "<|start|>")
    last_ok = toks[-1] == ("<|end|>", True) if ex[-1]["role"] == "assistant" else True
    print(f"example {i}: end-token check {'ok' if ends_ok and last_ok else 'FAILED'}")
Quick checkA tuned model never stops: it writes its answer, then invents a new user turn and keeps going. What is the most likely data bug?
How sure are you?
Pick an answer and how sure you are