TExcelTAD
Home › NLP, Transformers & LLM Fine-Tuning › Instruction Tuning and Chat Templates

Instruction Tuning and Chat Templates

Supervised fine-tuning teaches a model one behaviour from (prompt, response) pairs. Instruction tuning is SFT on many tasks at once, each phrased as a natural-language instruction: "Summarise this", "Translate to French", "Is this review positive?", "Write a SQL query that...". The goal is a model that follows instructions it has never seen, not one that is good at a fixed list of tasks. Chat assistants add one more layer: the instructions arrive as a conversation of messages with roles, and a chat template turns that conversation into the single token sequence the model actually reads.

This lesson builds a chat template and its training labels from scratch, applies one with the Transformers API, and then instruction-tunes a tiny model to measure two things that decide whether instruction tuning works in practice: how much phrasing diversity buys, and what a formatting mismatch costs. As in the previous lesson, the offline environment has no pretrained generative LLM, so the recorded model is trained from scratch, and the prose says where that limits the conclusions.

Instruction data sets

The early instruction-tuning work (FLAN, T0, Super-NaturalInstructions, around 2021 and 2022) converted existing NLP data sets into instructions with several hand-written templates per task, and found that models tuned on many tasks handle held-out tasks much better than the base model, with the gain growing with the number of tasks and the model size. Today's chat data mixes such converted tasks with human-written and model-generated conversations. Three properties matter more than raw size:

  • Diversity of tasks and phrasings, so the model learns "follow the instruction" rather than "recognise these templates".
  • Quality of the responses: a small set of excellent, consistent answers (the LIMA paper, Zhou et al., 2023, used about 1,000) can beat a much larger noisy set, because SFT copies the style and the mistakes of its data.
  • Coverage of the formats you will serve: multi-turn conversations, system prompts, refusals, tool calls, long inputs.

A useful split for evaluation keeps whole tasks or instruction phrasings out of training (not just examples), since generalisation to new instructions is the point.

Chat templates

A chat is a list of messages, each with a role (system, user, assistant, sometimes tool) and content. The template writes them out with role markers and an end-of-turn marker, and at inference ends with the generation prompt, the opening marker of an assistant turn, so the model's next tokens are the answer. Different model families use different markers (<|im_start|>, [INST], <|start_header_id|>...), and a model only behaves well with the exact format it was tuned on. Training labels follow the SFT rule: only the assistant's tokens and its end marker are scored.

python · try it yourself
def render(messages, add_generation_prompt=False):
    """A minimal chat template: role markers around each turn, an end marker after each."""
    out = ""
    for m in messages:
        out += f"<|{m['role']}|>\n{m['content']}<|end|>\n"
    if add_generation_prompt:
        out += "<|assistant|>\n"                      # the model continues from here
    return out

chat = [{"role": "system", "content": "You answer questions about TAD Bikes."},
        {"role": "user", "content": "Do you take cash?"},
        {"role": "assistant", "content": "No. You can pay by card or with the app wallet."}]
text = render(chat)
print(text, end="")

# training labels: only the assistant's content and its end marker are scored (character spans here)
start = text.index("<|assistant|>\n") + len("<|assistant|>\n")
end = text.index("<|end|>", start) + len("<|end|>")
print("scored span:", repr(text[start:end]), f"| {end - start} of {len(text)} characters")

# at inference: the conversation so far + the generation prompt
prompt = render(chat[:2], add_generation_prompt=True)
print("inference prompt ends with:", repr(prompt[-40:]))
<|system|>
You answer questions about TAD Bikes.<|end|>
<|user|>
Do you take cash?<|end|>
<|assistant|>
No. You can pay by card or with the app wallet.<|end|>
scored span: 'No. You can pay by card or with the app wallet.<|end|>' | 54 of 159 characters
inference prompt ends with: '\nDo you take cash?<|end|>\n<|assistant|>\n'

Only 54 of the 159 characters carry a loss. In a multi-turn chat every assistant turn is scored and every system and user turn is masked. Note the newline after <|assistant|> in the generation prompt: if training always had it and inference leaves it out, the model sees a sequence it has never seen in that position, a classic silent bug.

In Transformers the template is a Jinja string stored with the tokenizer (tokenizer.chat_template), and apply_chat_template renders it. The GPT-2 tokenizer cached here has no template, so the example sets the same template as above. It also shows the second half of the story: unless the markers are registered as special tokens, the tokenizer splits them into pieces.

python · try it yourself
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("sshleifer/tiny-gpt2")
print("chat template before:", tok.chat_template)

tok.chat_template = (
    "{% for m in messages %}<|{{ m['role'] }}|>\n{{ m['content'] }}<|end|>\n{% endfor %}"
    "{% if add_generation_prompt %}<|assistant|>\n{% endif %}"
)
chat = [{"role": "user", "content": "Do you take cash?"}]
text = tok.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
print(repr(text))
ids = tok.apply_chat_template(chat, add_generation_prompt=True)["input_ids"]
print(len(ids), "tokens:", tok.convert_ids_to_tokens(ids))

n_before = len(tok)
tok.add_special_tokens({"additional_special_tokens": ["<|user|>", "<|assistant|>", "<|end|>"]})
ids = tok.apply_chat_template(chat, add_generation_prompt=True)["input_ids"]
print(len(ids), "tokens:", tok.convert_ids_to_tokens(ids), "| vocabulary", n_before, "->", len(tok))
chat template before: None
'<|user|>\nDo you take cash?<|end|>\n<|assistant|>\n'
24 tokens: ['<', '|', 'user', '|', '>', 'Ċ', 'Do', 'Ġyou', 'Ġtake', 'Ġcash', '?', '<', '|', 'end', '|', '>', 'Ċ', '<', '|', 'ass', 'istant', '|', '>', 'Ċ']
11 tokens: ['<|user|>', 'Ċ', 'Do', 'Ġyou', 'Ġtake', 'Ġcash', '?', '<|end|>', 'Ċ', '<|assistant|>', 'Ċ'] | vocabulary 50257 -> 50260

Without special tokens, <|assistant|> costs 6 tokens and a user can type the same characters to fake a turn boundary. Registered as special tokens, each marker is one id (the vocabulary grows from 50,257 to 50,260; the model's embedding matrix must then grow too, model.resize_token_embeddings(len(tok)), and the new rows must be trained). Real chat models ship their template in tokenizer_config.json; use it rather than writing your own, and render training data and inference prompts with the same call.

The recorded run: diversity and format

A tiny decoder (2 blocks, width 64, character-level, with <user>, <assistant> and <end> as single tokens) is instruction-tuned on three tasks over random 3 to 5 letter words: reverse the word, copy it, or give its first letter. Two training sets of 3,000 conversations each:

  • one fixed phrasing: always "reverse: abc";
  • varied phrasings: the task keyword with 0 to 2 filler phrases around it from a list of six ("please reverse the word: abc", "copy for me: abc", ...).

Both are trained for 500 steps with the loss on the answer only, then tested on 100 new words per task (300 prompts) in four ways: the trained format; the keyword surrounded by filler phrases neither model has seen ("at once", "if you can", "this one"); the trained format without the generation prompt <assistant>; and a plain-text template ("user: ... assistant: "). The score is exact match of greedy decoding, computed in one batched forward pass (greedy decoding produces the answer exactly when the model's top token is right at every answer position given the right prefix).

python · try it yourself
import random, re
import torch, torch.nn as nn, torch.nn.functional as F

SPECIAL = ["<pad>", "<user>", "<assistant>", "<end>"]
VOCAB = SPECIAL + list("abcdefghijklmnopqrstuvwxyz :")
stoi = {c: i for i, c in enumerate(VOCAB)}
END = stoi["<end>"]

def encode(text):                                         # special tokens are single ids, the rest characters
    return [stoi[p] for p in re.findall(r"<pad>|<user>|<assistant>|<end>|.", text)]

def render(user_text):                                    # our chat template, with the generation prompt
    return f"<user>{user_text}<end><assistant>"

TASKS = {"reverse": lambda w: w[::-1], "copy": lambda w: w, "first": lambda w: w[0]}
FILLER = ["please", "now", "the word", "for me", "kindly", "quickly"]
HELD_OUT_FILLER = ["at once", "if you can", "this one"]

class TinyGPT(nn.Module):
    def __init__(self, V=len(VOCAB), d=64, heads=4, layers=2, T=48):
        super().__init__()
        self.tok, self.pos = nn.Embedding(V, d), nn.Embedding(T, d)
        self.blocks = nn.ModuleList(nn.TransformerEncoderLayer(d, heads, 4 * d, dropout=0.0, batch_first=True, norm_first=True)
                                    for _ in range(layers))
        self.norm, self.head = nn.LayerNorm(d), nn.Linear(d, V)
    def forward(self, x):
        T = x.shape[1]
        h = self.tok(x) + self.pos(torch.arange(T))
        for b in self.blocks:
            h = b(h, src_mask=torch.triu(torch.full((T, T), float("-inf")), 1))
        return self.head(self.norm(h))

rng = random.Random(0)
def word(): return "".join(rng.choice("abcdefghijklmnopqrstuvwxyz") for _ in range(rng.randint(3, 5)))

def phrase(task, w, fillers, r):                          # keyword plus 0 to 2 filler phrases around it
    before = " ".join(r.sample(fillers, r.randint(0, 1)))
    after = " ".join(r.sample(fillers, r.randint(0, 1)))
    return " ".join(p for p in [before, task, after] if p) + ": " + w

def make_data(n, varied):
    data = []
    for _ in range(n):
        task, w = rng.choice(list(TASKS)), word()
        text = phrase(task, w, FILLER, rng) if varied else f"{task}: {w}"
        data.append((render(text), TASKS[task](w)))
    return data

def train(data, steps=500):
    torch.manual_seed(0)
    model = TinyGPT()
    opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
    g = random.Random(1)
    for _ in range(steps):
        rows = []
        for prompt, ans in g.sample(data, 64):
            p, a = encode(prompt), encode(ans + "<end>")
            rows.append((p + a, [-100] * (len(p) - 1) + a + [-100]))   # loss on the answer and <end> only
        T = max(len(i) for i, _ in rows)
        x = torch.tensor([i + [0] * (T - len(i)) for i, _ in rows]); y = torch.tensor([l + [-100] * (T - len(l)) for _, l in rows])
        loss = F.cross_entropy(model(x).flatten(0, 1), y.flatten(), ignore_index=-100)
        opt.zero_grad(); loss.backward(); opt.step()
    return model.eval()

@torch.no_grad()
def greedy_correct(model, prompts, answers):
    """Greedy decoding returns `answer` exactly iff, fed the right prefix, the argmax is right at every step
    (answer tokens and <end>). So one batched forward pass replaces token-by-token generation."""
    rows = [(encode(p), encode(a + "<end>")) for p, a in zip(prompts, answers)]
    T = max(len(p) + len(a) for p, a in rows)
    x = torch.tensor([p + a + [0] * (T - len(p) - len(a)) for p, a in rows])
    pred = model(x).argmax(-1)
    return [all(pred[i, len(p) - 1 + j].item() == t for j, t in enumerate(a)) for i, (p, a) in enumerate(rows)]

test_words = [word() for _ in range(100)]
tests = {"as trained": lambda t, w: render(f"{t}: {w}"),
         "unseen filler words": lambda t, w: render(phrase(t, w, HELD_OUT_FILLER, tr)),
         "no generation prompt": lambda t, w: f"<user>{t}: {w}<end>",
         "other template": lambda t, w: f"user: {t}: {w} assistant: "}
for name, varied in [("one fixed phrasing", False), ("varied phrasings", True)]:
    model = train(make_data(3000, varied))
    scores, tr = [], random.Random(2)                     # the same unseen-filler prompts for both models
    for tname, fmt in tests.items():
        cases = [(fmt(t, w), f(w)) for t, f in TASKS.items() for w in test_words]
        hits = greedy_correct(model, *zip(*cases))
        scores.append(f"{tname} {sum(hits) / len(hits):.3f}")
    print(f"{name:18s} | " + " | ".join(scores))
print("an unseen-filler prompt:", repr(render(phrase("reverse", "abc", HELD_OUT_FILLER, random.Random(5)))))
one fixed phrasing | as trained 1.000 | unseen filler words 0.270 | no generation prompt 0.140 | other template 0.003
varied phrasings   | as trained 0.983 | unseen filler words 0.403 | no generation prompt 0.160 | other template 0.017
an unseen-filler prompt: '<user>this one reverse this one: abc<end><assistant>'

What the 300 test prompts per column show:

  • Diversity helps generalisation, a little here. On unseen filler words, the model trained on varied phrasings is right 0.403 of the time against 0.270, while being almost as good on the trained format (0.983 against 1.000). It has learned that extra words around the keyword do not change the task. A model this small, trained from scratch, has no idea what "at once" means; a pretrained LLM brings that knowledge with it, which is why instruction tuning of a large pretrained model generalises to new instructions far better than this toy can.
  • The format is not a detail. Leaving out the generation prompt drops both models to 0.14 to 0.16, and a different template to almost 0. The tokens around the content are part of what the model learned. In real deployments the same failure shows up as rambling, answering as the user, or ignoring the system prompt, and it is caused by a serving stack that renders the conversation differently from the training script.

Forgetting and data mixing

Instruction tuning is fine-tuning, so it can erase abilities the base model had (catastrophic forgetting): a model tuned only on short chat answers may lose long-form writing or a language that is rare in the SFT data. The usual remedies are to mix some pretraining-style text or data from earlier stages into the SFT set, to keep the learning rate low and the epochs few (1 to 3), and to train adapters instead of the full model (LoRA for LLMs). Evaluate on held-out tasks and on general benchmarks before and after.

Pitfalls

  • Training and serving with different templates. Render both with the same apply_chat_template call and the tokenizer saved with the model; test one conversation end to end and compare token ids.
  • Markers as plain text. Register role and end markers as special tokens, resize the embeddings, and make sure user content cannot produce them.
  • Scoring the user turns. Mask everything except assistant turns (TRL's assistant_only_loss, or your own labels), unless you mean to train the model to write user messages.
  • Evaluating on the training templates. Hold out phrasings and whole tasks; a model that only knows your 20 templates will look perfect on them.
  • Quantity over quality. Deduplicate, remove contradictory or wrong answers, and keep the style consistent; the model copies everything, including mistakes and verbosity.
  • Forgetting the EOS / end-of-turn token in the scored part, so the model never stops (SFT lesson).

Practice

  1. Write the rendered training text and the scored span for a chat with one user turn "hi" and one assistant turn "hello", with the template of the first example.
  2. The varied-phrasing model scored 0.983 on the trained format and 0.403 on unseen fillers. What would you change in the data to raise the second number, and why might it lower the first?
  3. A tokenizer has no special tokens for your markers. Name two problems this causes.
  4. Why does a held-out set of tasks say more about an instruction-tuned model than a held-out set of examples of the training tasks?
Answers
  1. <|user|>\nhi<|end|>\n<|assistant|>\nhello<|end|>\n; the scored span is hello<|end|> (the assistant content and its end marker), everything else is masked.
  2. More and more varied fillers (positions, lengths, real paraphrases instead of a short list), so that the model cannot rely on any fixed context. With the same model size and steps, the task becomes harder to learn, so accuracy on the plain format can drop a little, as it did here (1.000 to 0.983).
  3. Each marker costs several tokens and its pieces also occur in normal text, so turn boundaries are ambiguous to the model; and a user can type the marker characters to inject a fake system or assistant turn.
  4. Examples of a training task share its template and its answer style, so the score measures memorised task formats. The purpose of instruction tuning is to follow new instructions, which only a held-out task (or phrasing) tests.

Test yourself

What is the generation prompt in a chat template?

  1. The system message
  2. The opening marker of an assistant turn, added at the end of the prompt so the model's next tokens are the answer
  3. The first user message
  4. The EOS token

Why register chat markers such as <|assistant|> as special tokens?

  1. To shorten the vocabulary
  2. So each marker is one id that user text cannot produce by accident, instead of several ordinary pieces
  3. Because Jinja requires it
  4. To mask them from the loss

In the lesson's run, both models scored near 0 with a plain 'user: ... assistant:' template. What does that show?

  1. The models are untrained
  2. An instruction-tuned model depends on the exact format it was trained with; serving must use the same template
  3. Plain text templates are always worse
  4. The test words were too long

Which statement about instruction data matches the evidence summarised in the lesson?

  1. More examples always beat better examples
  2. A small set of high-quality, diverse examples can beat a much larger noisy set
  3. Only one template per task should be used
  4. User turns should carry the loss