LLM Fine-Tuning with LoRA and QLoRA / How models learn from chat examples

Tokens, special tokens and chat templates

Lesson 4 of 29. Open to read. No account needed.

A chat model never sees your messages. It sees a list of numbers, made in two steps: a chat template turns the messages into one piece of text with markers between the turns, and a tokenizer turns that text into token IDs. Fine-tuning teaches the model to continue such text. If the text at training time and at answer time is built differently, the model is asked a question in a form it was never trained on.

In this lesson you will:

  • tokenise text, decode token IDs and identify the model's special tokens;
  • apply SmolLM2's chat template with and without the generation prompt, and find the default system message it inserts;
  • predict how many tokens a change to the prompt adds or removes.

Text becomes tokens

A tokenizer splits text into pieces from a fixed vocabulary and gives each piece a number, its token ID. SmolLM2's vocabulary has 49,152 entries. Common words are one token; rarer words and codes are split into several. The model reads and writes token IDs, never characters.

Three things about the pieces surprise most people:

  • A leading space belongs to the next token. "kayak" is three tokens, but " kayak" is two. Token lists mark that space with Ġ, and a newline with Ċ.
  • Codes split into characters. The asset ID TN-20 becomes five tokens: T, N, -, 2, 0. Copying an ID means copying five tokens in order.
  • Token counts, not word counts, set the cost. Every token in a prompt is processed on every call and in every training step.

Special tokens are vocabulary entries that mark structure rather than text. SmolLM2 defines three:

TokenIDRole in SmolLM2
`<im_start>`1Starts a turn; the tokenizer also names it the beginning-of-sequence token
`<im_end>`2Ends a turn. It is the end-of-sequence token that stops generation, and also the padding token
`<endoftext>`0The unknown-token placeholder; chat text does not use it

When special-token text such as <|im_end|> appears in a string, the tokenizer turns it into its single ID, not into the characters <, | and so on. The model learns that ID like any other: to end its answer, it must write token 2.

Messages become text: the chat template

A chat template is a short program, stored with the tokenizer, that turns a list of {"role": ..., "content": ...} messages into text. apply_chat_template runs it. SmolLM2 writes each message as <|im_start|>, the role, a newline, the content, then <|im_end|> and a newline.

A course example in three forms. As messages: a system message, a user message with the report, and an assistant message with the record. As templated text: each message wrapped in an im_start marker, its role and a newline at the start, and an im_end marker and a newline at the end; the inference prompt stops after the assistant header. As token IDs: 119 tokens for the whole example, of which 78 are the inference prompt and 41 the answer; the special tokens have IDs 1 and 2.

One course example as messages, as templated text and as token IDs. The inference prompt is the same text cut off after the assistant header.

The same messages are templated two ways:

  • For training, the whole conversation, answer included, ending with <|im_end|> and a newline. The model learns to write the answer and then the end marker.
  • For inference, the prompt only, with add_generation_prompt=True. This adds the assistant header, <|im_start|>assistant and a newline, so the model's next token is the first token of its answer.

Leave the header out at inference time and the model must write it itself; the next lesson shows what that looks like.

The default system message. If the messages contain no system message, SmolLM2's template inserts one: "You are a helpful AI assistant named SmolLM, trained by Hugging Face", 16 tokens long. The course always supplies its own system message, "Convert equipment reports to JSON records." (7 tokens), so the default never appears in the course's data. Templates differ between model families: in the course's checks Qwen2.5's template also inserts a default system message and Qwen3's does not. Always look at the templated text of the model you train.

Two traps in Transformers 5

  • tokenize=True returns a dictionary. In Transformers 5.20.2, apply_chat_template(..., tokenize=True) returns a BatchEncoding with the keys input_ids and attention_mask. Its len() is 2, whatever the prompt. Take ["input_ids"] before counting.
  • Templated text already contains its special tokens. When you tokenise text from apply_chat_template(..., tokenize=False), pass add_special_tokens=False, as the Transformers documentation advises. A tokenizer that adds its own beginning-of-sequence token would otherwise add a second one in front of the template's. The independent task checks what this does for SmolLM2.

Before you start

PartWhat you need
GoalSee exactly how one course example becomes text and token IDs, and predict the effect of a prompt change
Starting stateThe course environment from Set up and verify the course environment, active, with HF_HOME and HF_HUB_OFFLINE=1 set and SmolLM2-135M-Instruct downloaded
InputsNone. The example is written into the script, because the course dataset is built two lessons later
ExecutionA terminal in ~/finetune-practice/inspect-templates, as your own user
EffectsCreates that folder and the script in it. Only the tokenizer is loaded, not the model. Nothing is downloaded
TimeA few seconds per run

Check the starting state, then make the exercise folder:

python -c "import os; print(os.environ.get('HF_HUB_OFFLINE'), os.environ.get('HF_HOME'))"
mkdir -p ~/finetune-practice/inspect-templates
cd ~/finetune-practice/inspect-templates

The first line must print 1 and a path ending in finetune-practice/hf-cache. If it prints None None, run source ~/finetune-practice/course-env.sh (on Windows, . $HOME\finetune-practice\course-env.ps1) first. On Windows PowerShell make the folder with New-Item -ItemType Directory -Force $HOME\finetune-practice\inspect-templates, then cd into it.

The script

Save this as inspect_template.py:

"""Show how one course example becomes templated text and token IDs.

Run from ~/finetune-practice/inspect-templates with the course environment
active:
    python inspect_template.py
"""

import json

from transformers import AutoTokenizer

MODEL_ID = "HuggingFaceTB/SmolLM2-135M-Instruct"
REVISION = "12fd25f77366fa6b3b4b768ec3050bf629380bac"
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, revision=REVISION)


def count(text):
    """Tokens in text that is already templated, so add no special tokens."""
    return len(tokenizer(text, add_special_tokens=False)["input_ids"])


# 1. The special tokens this tokenizer defines.
print("== special tokens")
for name in ["bos_token", "eos_token", "pad_token", "unk_token"]:
    print(f"{name:<10} {getattr(tokenizer, name)!r:<16} id {getattr(tokenizer, name + '_id')}")

# 2. Ordinary text as tokens. Ġ marks a leading space and Ċ a newline.
print("\n== text as tokens")
for text in ["kayak", " kayak", "TN-20", "<|im_start|>user\nHi<|im_end|>"]:
    ids = tokenizer(text, add_special_tokens=False)["input_ids"]
    print(f"{text!r:<34} {ids}")
    print(f"{'':<34} {tokenizer.convert_ids_to_tokens(ids)}")

# 3. One course example as messages: the prompt, then the answer to learn.
prompt = [
    {"role": "system", "content": "Convert equipment reports to JSON records."},
    {"role": "user", "content": "Keys: asset, equipment, category (repair, cleaning, replacement, "
                                "inspection), location, priority (low, normal, high, urgent).\n"
                                "Report: Hello team, the tent TN-20 at the boathouse has gone missing. "
                                "It is needed for tomorrow's session."},
]
record = {"asset": "TN-20", "equipment": "tent", "category": "replacement",
          "location": "boathouse", "priority": "high"}
completion = [{"role": "assistant", "content": json.dumps(record)}]

# 4. The same example templated for training and for inference.
training_text = tokenizer.apply_chat_template(prompt + completion, tokenize=False)
inference_text = tokenizer.apply_chat_template(prompt, tokenize=False, add_generation_prompt=True)
without_header = tokenizer.apply_chat_template(prompt, tokenize=False)
print("\n== training text (prompt and answer)")
print(training_text, end="")
print("\n== how each version ends")
print(f"training text         ...{training_text[-34:]!r}")
print(f"inference prompt      ...{inference_text[-34:]!r}")
print(f"no generation header  ...{without_header[-34:]!r}")
print("\n== token counts")
print(f"training text         {count(training_text)}")
print(f"inference prompt      {count(inference_text)}")
print(f"answer part           {count(training_text) - count(inference_text)}")

# 5. Leave out the system message and the template adds its own.
default_text = tokenizer.apply_chat_template(prompt[1:], tokenize=False, add_generation_prompt=True)
print("\n== no system message: the template inserts one")
print(default_text.split("<|im_end|>")[0] + "<|im_end|>")
print(f"inference prompt with the default system message: {count(default_text)} tokens")

# 6. tokenize=True returns a BatchEncoding, a dictionary of two lists.
encoded = tokenizer.apply_chat_template(prompt, add_generation_prompt=True, tokenize=True)
print("\n== apply_chat_template(..., tokenize=True)")
print(f"{type(encoded).__name__} with keys {list(encoded.keys())}; len() is {len(encoded)}, "
      f"the prompt has {len(encoded['input_ids'])} tokens")

What each part does:

  • count tokenises text that is already templated, so it passes add_special_tokens=False.
  • Part 1 prints the four special-token roles the tokenizer defines. Three roles share two tokens.
  • Part 2 tokenises a few strings and shows both the IDs and the pieces.
  • Parts 3 and 4 build one course example and template it for training, for inference, and for inference without the header, then count tokens.
  • Part 5 removes the system message to reveal the default one.
  • Part 6 shows what tokenize=True returns.

Run it

Predict before you run: the record {"asset": "TN-20", ...} is 111 characters long. Will the answer part be nearer 20, 40 or 100 tokens?

python inspect_template.py

Output from the course's test (illustrative; the counts should match yours exactly, because the tokenizer is pinned to one revision):

== special tokens
bos_token  '<|im_start|>'   id 1
eos_token  '<|im_end|>'     id 2
pad_token  '<|im_end|>'     id 2
unk_token  '<|endoftext|>'  id 0

== text as tokens
'kayak'                            [91, 341, 494]
                                   ['k', 'ay', 'ak']
' kayak'                           [32406, 494]
                                   ['Ġkay', 'ak']
'TN-20'                            [68, 62, 29, 34, 32]
                                   ['T', 'N', '-', '2', '0']
'<|im_start|>user\nHi<|im_end|>'   [1, 4093, 198, 26843, 2]
                                   ['<|im_start|>', 'user', 'Ċ', 'Hi', '<|im_end|>']

== training text (prompt and answer)
<|im_start|>system
Convert equipment reports to JSON records.<|im_end|>
<|im_start|>user
Keys: asset, equipment, category (repair, cleaning, replacement, inspection), location, priority (low, normal, high, urgent).
Report: Hello team, the tent TN-20 at the boathouse has gone missing. It is needed for tomorrow's session.<|im_end|>
<|im_start|>assistant
{"asset": "TN-20", "equipment": "tent", "category": "replacement", "location": "boathouse", "priority": "high"}<|im_end|>

== how each version ends
training text         ...'e", "priority": "high"}<|im_end|>\n'
inference prompt      ...'.<|im_end|>\n<|im_start|>assistant\n'
no generation header  ..."for tomorrow's session.<|im_end|>\n"

== token counts
training text         119
inference prompt      78
answer part           41

== no system message: the template inserts one
<|im_start|>system
You are a helpful AI assistant named SmolLM, trained by Hugging Face<|im_end|>
inference prompt with the default system message: 87 tokens

== apply_chat_template(..., tokenize=True)
BatchEncoding with keys ['input_ids', 'attention_mask']; len() is 2, the prompt has 78 tokens

Read the output

  • The three roles share two tokens. The end of a turn, the end of generation and padding are all <|im_end|>, ID 2. The loss-mask lesson shows why padding with the end-of-turn token does not stop the model learning to end its turn.
  • The answer is 41 tokens. The record's braces, quotes and key names are cheap; its values, such as TN-20, cost a token per character. The last two of the 41 are <|im_end|> and the newline after it.
  • The inference prompt is 78 tokens and ends with the assistant header. The training text is that prompt plus the answer: 78 + 41 = 119. The prompt is the same text in both, which is what "same template for training and inference" means in practice.
  • Without a system message, SmolLM2 adds its own, and the prompt grows from 78 to 87 tokens: the default's 16 tokens replace the course's 7.
  • len() of the BatchEncoding is 2, the number of keys; the prompt itself is 78 tokens.

When your result differs

What you seeLikely causeWhat to do
An error about offline mode or a missing file when loading the tokenizerHF_HOME points elsewhere, or the setup lesson's download did not finishRun the setup lesson's check_setup.py; it names the missing file
Different token countsA different tokenizer revision, or the example text was changedCheck REVISION and that the report and record are exactly as printed
The training text has no line for the system message, or a different oneThe prompt list was editedCompare with the script above
len() of the encoding is 78An older Transformers version that returned a plain listCheck the version with pip show transformers; the course pins 5.20.2

Your turn: a one-word system message

Predict the new inference-prompt count before changing anything: what happens to the 78 tokens if the system message becomes just Convert.?

Then copy the script to one_word.py, change the system message's "content" in the copy to "Convert.", and run the copy.

Hint 1

Only the content of the system message changes. The markers, the role and the newline around it stay. Count the tokens of the old and the new content.

Hint 2

Part 2 of the output shows how text splits. Convert is one token; so is the full stop.

Solution

The inference prompt falls from 78 to 73 tokens, and the training text from 119 to 114; the answer part stays 41:

== token counts
training text         114
inference prompt      73
answer part           41

"Convert equipment reports to JSON records." is 7 tokens (Convert, Ġequipment, Ġreports, Ġto, ĠJSON, Ġrecords, .) and "Convert." is 2, so 5 tokens go. The template's own tokens do not change. A shorter system message saves 5 tokens on every training example and every call, but a model fine-tuned with one system message should be asked with that same message: changing it later is a template mismatch.

Independent task: add_special_tokens=True

First explain, in a sentence or two, why tokenising templated text with add_special_tokens=True is wrong in general. Then find out what it does for SmolLM2: copy the script to special.py, change False to True in the copy's count function only, run it and compare the counts.

Hints

  • Look at the first ID of any templated text. Which token is it, and who wrote it?
  • tokenizer.add_bos_token tells you whether this tokenizer adds a beginning-of-sequence token by itself.

Solution

In general: the template has already written every special token the model expects. A tokenizer that also adds its own beginning-of-sequence token would put a second one in front, and the model would see a sequence it never saw in training.

For SmolLM2 nothing changes. The counts stay 119, 78 and 41, because SmolLM2's tokenizer adds no special tokens of its own (tokenizer.add_bos_token is False). The templated text starts with <|im_start|> because the template wrote it.

The course scripts still pass add_special_tokens=False. The setting is harmless here by luck, not by design, and the same code may later run with a model whose tokenizer does add one.

Reset and cleanup

Nothing in this exercise is needed later. Remove the folder after checking where you are:

cd ~/finetune-practice/inspect-templates && pwd
cd .. && rm -rf inspect-templates

pwd must print a path ending in finetune-practice/inspect-templates before you go on. On Windows PowerShell use cd $HOME\finetune-practice; Remove-Item -Recurse -Force inspect-templates. Keep ~/finetune-practice/.venv and hf-cache.

Check your understanding

  1. Mark every special token in this decoded text, and say which of them the model must learn to write during fine-tuning: <|im_start|>user\nKY-07 is broken.<|im_end|>\n<|im_start|>assistant\n{"asset": "KY-07", ...}<|im_end|>\n
  2. A prompt is 78 tokens with the course's system message. Without any system message, is it shorter or longer, and by how much?
  3. A colleague counts a prompt with len(tokenizer.apply_chat_template(messages, tokenize=True)) and gets 2 for every prompt. What is wrong?
  4. Why must the inference prompt end with <|im_start|>assistant and a newline?

Answer all four before reading on.

Answers

  1. Four special tokens: <|im_start|> twice and <|im_end|> twice. The model must learn to write only the final <|im_end|>, which ends its answer. Everything before the answer, including the assistant header, is prompt that the template writes.
  2. Longer, by 9 tokens: 87. The template inserts its 16-token default system message in place of the course's 7-token one.
  3. In Transformers 5 the call returns a BatchEncoding with two keys; len() counts the keys. Use len(tokenizer.apply_chat_template(messages, tokenize=True)["input_ids"]).
  4. In training the answer always followed that header, so the model learned to write an answer from there. Without it, the model's first job is to write the header itself, which is not what it was trained to do.

24 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy