Module 2 · Training data

Conversational formats and chat templates

6 min read

An "Instruct" model has never seen a conversation as a list of messages: it has seen text, formatted by a precise template — the chat template — with role tags and special tokens. Fine-tuning with a format different from the original training, forgetting the end-of-turn token, or computing the loss on the prompt: three silent mistakes that produce a model that never stops generating, answers in a hybrid format, or learns to copy questions. This lesson shows what the model really sees.

What the model sees

Here is the exact text produced by the Qwen2.5 chat template for an example from Forge's training set:

<|im_start|>system
Tu tries les messages du support client de la boutique Nimbus. Réponds UNIQUEMENT par un objet JSON avec les clés "categorie" (…), "produit" (…), "urgence" (…) et "remboursement" (…).<|im_end|>
<|im_start|>user
Madame, Monsieur,
Mon compte a été bloqué après plusieurs essais.
Merci d'avance !<|im_end|>
<|im_start|>assistant
{"categorie": "compte", "produit": "aucun", "urgence": "normale", "remboursement": false}<|im_end|>

(The system instruction, in French like the task, asks for a JSON object only, with its four keys; the customer writes that their account was locked after several attempts.) This format is called ChatML: each turn starts with <|im_start|> followed by the role, and ends with <|im_end|>. These tags are special tokens (a single identifier each), not ordinary text. Other families use other templates (Llama 3: <|start_header_id|>…<|eot_id|>; Mistral: [INST]…[/INST]; Gemma: <start_of_turn>…<end_of_turn>). SmolLM2, the course's small model, also uses ChatML.

Two details only show up when you display this text:

  • The default system prompt. Without a system message, the Qwen2.5 template adds one automatically: "You are Qwen, created by Alibaba Cloud. You are a helpful assistant." SmolLM2 does the same with its own. If you train without a system message and serve with one (or vice versa), the model sees in production a text it never saw during training.
  • The end-of-turn token. <|im_end|> is what teaches the model to stop. A fine-tuning whose examples do not end with this token produces a model that keeps generating after its answer — sometimes inventing a new "user" turn.

The rule: never format by hand

Forge never builds these strings itself; it always goes through the model's tokenizer:

def render(tokenizer, example: Example) -> str:
    """Le texte EXACT que voit le modèle à l'entraînement : à relire au moins une fois par projet."""
    answer = {"role": "assistant", "content": example.target_json()}
    messages = prompt_messages(example.message) + [answer]
    return tokenizer.apply_chat_template(messages, tokenize=False)


def generation_prompt(tokenizer, message: str) -> str:
    """Le prompt d'inférence : même format, terminé par l'ouverture du tour de l'assistant."""
    return tokenizer.apply_chat_template(prompt_messages(message), tokenize=False,
                                         add_generation_prompt=True)

add_generation_prompt=True adds the opening of the assistant's turn (<|im_start|>assistant), so the model continues with its answer. The same template is used for training and inference: that is the guarantee of consistency.

TRL's data formats

TRL accepts several dataset shapes; Forge uses the conversational prompt / completion format:

def to_prompt_completion(example: Example) -> dict:
    """Format « prompt / completion » de TRL : la perte ne porte que sur la complétion."""
    return {"prompt": prompt_messages(example.message),
            "completion": [{"role": "assistant", "content": example.target_json()}]}
FormatFieldsLoss computed on
Language (raw text)textAll the text
ConversationalmessagesEverything, or only the assistant turns (assistant_only_loss)
Prompt / completionprompt, completionThe completion only (default)
Preferencesprompt, chosen, rejectedFor DPO and the reward model (module 4)

Why not learn the prompt

If the loss covers all the text, the model also learns to predict the system prompt and the customer's message. In Forge, the system prompt is more than 100 tokens and repeats identically in every example, while the answer is about thirty: most of the learning signal would go to memorizing a fixed instruction and imitating customers. With the prompt/completion format, prompt tokens get the label -100 (ignored by the loss); TRL shows it when loading: "Building labels for train dataset".

This masking also affects measurement: the loss and "token accuracy" displayed during training only cover the 30 answer tokens. On Forge, they reach almost 100% from the first epoch — which says nothing about generalization (lesson 2.4).

The cost of tokens depends on the tokenizer

The tokenizer also decides the cost: the same message does not have the same length depending on the model.

TextQwen2.5 (vocabulary 151,665)SmolLM2 (vocabulary 49,152)
The example's customer message23 tokens35 tokens
JSON answer30 tokens34 tokens

Qwen's multilingual tokenizer splits French into fewer pieces: for the same volume, training and inference cost less, and more context is available. On the other hand, a large vocabulary makes the output layer heavier (lesson 1.3).

Checks before every training run

  1. Display two or three examples rendered by render and read them in full.
  2. Check that each answer ends with the end-of-turn token.
  3. Check that the same system prompt is used in training and in production (or explicitly none, with the template's default).
  4. Check the masking: the loss only covers the answers.
  5. After training, generate a few answers and check that the model stops.

Key takeaways

  • An Instruct model was trained on text formatted by its chat template: role tags and special tokens.
  • Never format by hand: tokenizer.apply_chat_template, for training and inference alike.
  • Watch out for the default system prompt some templates add, and for the end-of-turn token that teaches the model to stop.
  • TRL's prompt/completion format computes the loss on the answer only: the model does not learn to copy the prompt.
  • The tokenizer sets the cost: 23 tokens with Qwen, 35 with SmolLM2 for the same French message.

Practice

  1. Display chat.render for an example with the Qwen2.5 tokenizer, then with a Llama 3 model's: compare the tags.
  2. Remove the system message from prompt_messages and display the rendering again: what does the "system" turn contain?
  3. Count the tokens of the learned part (answer) and of the masked part (prompt) for ten examples: what is the ratio?

Resources