Papa Programmer
Lesson 15 of 36

Fine-tune a model to follow instructions

10 min read

Optional

The task

The task is a small version of Define the task and what success means: given "Classify: …" and a support message, reply with one word, access or billing. A base chat model might answer in a sentence, add an explanation or pick a different label name. Instruction tuning teaches it your exact format.

Each training example is one conversation: a user turn with the request and an assistant turn with the reply you want. For a real project, include cases where the right reply is to ask for missing information, and leave out personal data the task does not need.

Render the chat template

Every chat model expects its turns in a specific text format, with role markers and special TokenA small piece of text that a model reads or writes as one unit, such as a short word, part of a longer word or a punctuation mark. In English, one token is about four characters.. The tokeniser knows that format, and apply_chat_template produces it. Do not write the markers by hand. Print the result for a few examples before you train, and check that it looks right.

python
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct")
messages = [
	{"role": "user", "content": "Classify: I cannot sign in."},
	{"role": "assistant", "content": "access"},
]
formatted = tokenizer.apply_chat_template(
	messages, tokenize=False, add_generation_prompt=False
)
print(formatted)

The model files download on first use. The printed text shows the role markers and the end marker that this particular model uses. Another model prints something different, which is why you must use the template that ships with your model. Formatting data for training explains the file format that feeds this step.

What the loss covers

Supervised fine-tuning trains the model to predict each next token of the example. A choice sits in that sentence: which tokens count. Counting only the reply puts the full learning signal on what you want the model to say. Counting the whole conversation also trains the model to predict the request, which wastes effort. Tokenisation for training showed how labels of -100 take the prompt and the padding out of the loss.

The example below keeps things short and counts every non-padding token, including the prompt. That is acceptable for a demonstration. For a real run, mask the prompt, or use a library trainer that does it for you, and print one batch to confirm.

Train for two steps

The program below fine-tunes a 135 million parameter model for two steps on four toy conversations, and prints its reply to one held-out request before and after. It demonstrates the mechanics. Two steps on four examples cannot show a real improvement. Install compatible versions of PyTorch, Transformers, Datasets and Accelerate first. The model downloads on first use, and the run saves its output in instruction-output.

python
import torch
from datasets import Dataset
from transformers import (
	AutoModelForCausalLM,
	AutoTokenizer,
	DataCollatorForLanguageModeling,
	Trainer,
	TrainingArguments,
)

base = "HuggingFaceTB/SmolLM2-135M-Instruct"
tokenizer = AutoTokenizer.from_pretrained(base)
if tokenizer.pad_token is None:
	tokenizer.pad_token = tokenizer.eos_token
model = AutoModelForCausalLM.from_pretrained(base)

chats = [
	[{"role": "user", "content": "Classify: I cannot sign in."},
	 {"role": "assistant", "content": "access"}],
	[{"role": "user", "content": "Classify: My login fails."},
	 {"role": "assistant", "content": "access"}],
	[{"role": "user", "content": "Classify: Explain my invoice."},
	 {"role": "assistant", "content": "billing"}],
	[{"role": "user", "content": "Classify: Why was I charged twice?"},
	 {"role": "assistant", "content": "billing"}],
]

def tokenize_chats(batch):
	texts = [tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=False)
			 for chat in batch["messages"]]
	return tokenizer(texts, truncation=True, max_length=128, add_special_tokens=False)

train = Dataset.from_dict({"messages": chats}).map(
	tokenize_chats, batched=True, remove_columns=["messages"]
)

def reply(model, request):
	inputs = tokenizer.apply_chat_template(
		[{"role": "user", "content": request}],
		tokenize=True, add_generation_prompt=True,
		return_tensors="pt", return_dict=True,
	).to(model.device)
	model.eval()
	with torch.no_grad():
		output = model.generate(**inputs, max_new_tokens=12, do_sample=False,
								pad_token_id=tokenizer.pad_token_id)
	return tokenizer.decode(output[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True)

held_out = "Classify: I cannot access my account."
print("Before:", reply(model, held_out))
trainer = Trainer(
	model=model,
	args=TrainingArguments(
		output_dir="instruction-output", max_steps=2,
		per_device_train_batch_size=2, learning_rate=5e-5,
		save_strategy="no", report_to="none",
	),
	train_dataset=train,
	processing_class=tokenizer,
	data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False),
)
trainer.train()
print("After:", reply(model, held_out))
trainer.save_model("instruction-output/model")
tokenizer.save_pretrained("instruction-output/model")

The reply function uses greedy decoding, with do_sample=False, so that the before and after answers differ only because of the training and not because of random sampling. The two replies depend on the machine and the library versions, so this Lesson does not print them. Run it and read what you get.

Compare before and after

A few printed replies are a smell test. A fair comparison scores both models on the same held-out requests with the same settings, and looks at three things: the format, the label, and what happens when the right answer is unknown.

The program below shows a simple scorer. The replies are fictional stand-ins for what you would collect from the two models.

python
allowed = {"access", "billing"}
requests = ["I cannot access my account", "Wrong amount on my bill", "Update my card", "Hello?"]
truth = ["access", "billing", "billing", "access"]
before = ["It sounds like you may have an account problem.", "billing", "billing details", "Hello! How can I help?"]
after = ["access", "billing", "billing", "billing"]

def score(name, replies):
	valid = [r in allowed for r in replies]
	correct = [r == t for r, t in zip(replies, truth)]
	print(f"{name}: valid format {sum(valid)}/{len(valid)}, correct {sum(correct)}/{len(correct)}")

score("before", before)
score("after ", after)
for text, t, a in zip(requests, truth, after):
	if a != t:
		print(f"still wrong: {text!r} expected {t}, got {a}")

It prints:

text
before: valid format 1/4, correct 1/4
after : valid format 4/4, correct 3/4
still wrong: 'Hello?' expected access, got billing

The tuned model fixed the format, and every reply is now one of the allowed words. It still gets "Hello?" wrong, because the training set had no example of a message with no clear category. That finding is a to-do for the next round of data, which is the loop Error analysis and the next round describes. Save the base model and run it on the same inputs every time you compare.

For tuning chat models at larger scale, see the Hugging Face supervised fine-tuning guide, and for the template details, the chat templates guide.

  1. ExamplesWrite requests and the replies you want, and keep a held-out set.
  2. TemplateRender each chat with the model's own template and check the text.
  3. TrainFit the replies, with the prompt masked out of the loss.
  4. GenerateRun the tuned and original models on held-out requests with fixed settings.
  5. ScoreCompare format, correctness and behaviour on unknown cases.
Instruction tuning in five steps
Use the model's templateRole markers and special tokens must match what the model was trained to read.
Score the replyMask the prompt so the loss covers the answer you want.
Compare, do not admireRun the same held-out requests through both models and score them.

Your reading position is saved

0%

0 of 36 complete

Contents

Learning tools