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

Next-token loss, loss masks and stop tokens

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

Fine-tuning changes a model by scoring its predictions on your examples and nudging it towards the right answers. Which tokens are scored decides what it learns. Score the prompt as well as the answer, and the model also learns to write equipment reports. Fail to score the end-of-turn token, and it never learns to stop.

In this lesson you will:

  • compute next-token cross-entropy by hand, with the one-token shift and the ignore index -100;
  • build a completion-only loss mask for a course example and check it against the labels TRL prepares, position by position;
  • trace a reply that never stops, or starts with the wrong text, to its cause.

How one prediction is scored

At every position a language model outputs a probability for each token in its vocabulary: its guess at the next token. Training compares that guess with the token that actually comes next.

The score is cross-entropy: minus the natural logarithm of the probability the model gave the right token. A confident right guess costs little; a confident wrong one costs a lot:

Probability given to the right tokenLoss, −log p
0.80.223
0.50.693
0.251.386

The loss for an example is the mean over the positions that are scored. For the three positions above it is (0.693 + 1.386 + 0.223) / 3 = 0.768.

To leave a position out, its label is set to -100, the ignore index. PyTorch's cross-entropy skips it, and the mean is taken over the remaining positions only: with the first position ignored, the loss is (1.386 + 0.223) / 2 = 0.805, not a sum divided by three.

The one-token shift

The model's output at position t is its guess for the token at position t + 1. So the guess at the last position has nothing to be scored against, and the first token is never a target.

In Transformers you do not shift anything yourself. The labels you pass line up with input_ids, one label per token, and the model shifts them inside its loss. The exercise checks this: the model's own loss and a loss computed by hand with the shift agree exactly, and the same computation without the shift gives a much larger, meaningless number.

Completion-only loss

In a prompt-completion example, the prompt is given to the model at answer time; only the completion is its job. A loss mask sets every prompt token's label to -100 and keeps the completion's token IDs as labels.

The loss mask for one course example. The 78 prompt tokens, from the system message to the assistant header, are grey with label -100. The 41 answer tokens, the record followed by the im_end token and a newline, carry loss. Arrows show that the prediction at each position is scored against the token at the next position.

The course example's 119 tokens: 78 masked, 41 carrying loss, including the end-of-turn token. Each prediction is scored against the next token.

For the course example:

  • the 78 prompt tokens, from the system message to the assistant header, get -100;
  • the 41 answer tokens carry loss: the record, then <|im_end|>, then the newline after it.

The end-of-turn token must carry loss. It is how the model learns to stop. Generation stops when the model writes <|im_end|>; a model never scored on writing it has no reason to.

TRL 1.16.0 builds this mask for you when the data is in prompt-completion form, which is why the course data has prompt and completion columns. It folds the mask into a labels column. The alternative, completion_only_loss=False, scores every token: the model then also learns to predict the system message, the instruction and the report, and the loss number mixes prompt and answer, so it is not comparable with a completion-only run. The course uses completion-only loss throughout.

Padding and the end-of-turn token

Examples in a batch have different lengths, so shorter ones are padded to the longest. SmolLM2's padding token is <|im_end|>, the same token that ends a turn. That looks dangerous: if padding labels are masked, is the real end-of-turn masked too?

It is not, because TRL's collator masks by position, not by token. It sets -100 wherever the attention mask marks padding, and leaves the real <|im_end|> with its label. A collator that instead masked every token equal to the pad ID would also mask the real end-of-turn token, and the model would never learn to stop. The exercise checks which one you have.

How replies stop, and how they fail to

generate stops when the model writes the token in its generation settings' eos_token_id: for SmolLM2, <|im_end|>, ID 2. Three things break this:

SymptomCauseEvidence to look at
The reply runs on after the answer, often into a new invented turnGeneration stops at the wrong token; or the model never learned to write `<im_end>` because its label was maskedThe eos_token_id passed to generate or in generation_config; the decoded training labels
The reply starts with assistantThe inference prompt lacks the generation header, so the model writes itThe inference code's add_generation_prompt
The answer has the wrong format or style although training went wellThe inference template differs from training: another system message, model or templateThe templated inference text, compared with the training text

Fix the cause the evidence shows. Raising max_new_tokens or cutting the reply text after the first } hides the symptom and leaves the model broken.

Before you start

PartWhat you need
GoalA hand-built loss mask that equals TRL's labels at every position, and a demonstration of each stop failure
Starting stateThe course environment from Set up and verify the course environment, active, with HF_HOME and HF_HUB_OFFLINE=1 set; Tokens, special tokens and chat templates completed
InputsNone. Two course examples are written into the script
ExecutionA terminal in ~/finetune-practice/loss-masks, as your own user
EffectsCreates that folder, two scripts and an empty trainer-output folder. Nothing is trained, downloaded or uploaded
Time and memoryAbout 7 seconds and 1.2 GB per script in the course's test on a lightly loaded computer; 40 to 70 seconds when it was busy

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/loss-masks
cd ~/finetune-practice/loss-masks

The first line must print 1 and a path ending in finetune-practice/hf-cache; if it prints None None, load course-env.sh (or course-env.ps1) as in the setup lesson. On Windows PowerShell make the folder with New-Item -ItemType Directory -Force $HOME\finetune-practice\loss-masks, then cd into it.

The mask script

Save this as loss_mask.py:

"""Build a completion-only loss mask by hand and compare it with TRL's labels.

Run from ~/finetune-practice/loss-masks with the course environment active:
    python loss_mask.py
"""

import json
import math

import torch
import torch.nn.functional as F
from datasets import Dataset
from transformers import AutoModelForCausalLM, AutoTokenizer
from trl import SFTConfig, SFTTrainer

MODEL_ID = "HuggingFaceTB/SmolLM2-135M-Instruct"
REVISION = "12fd25f77366fa6b3b4b768ec3050bf629380bac"
torch.set_num_threads(4)

# 1. Cross-entropy by hand: three targets in a ten-token vocabulary.
print("== cross-entropy by hand")
targets = torch.tensor([5, 9, 2])
chosen = [0.5, 0.25, 0.8]  # the probability the model gives each target
probs = torch.zeros(3, 10)
for row, (target, p) in enumerate(zip(targets.tolist(), chosen)):
    probs[row] = (1 - p) / 9  # the rest is shared by the other nine tokens
    probs[row, target] = p
print("each -log p:", [round(-math.log(p), 3) for p in chosen])
print("mean loss:  ", round(F.cross_entropy(probs.log(), targets).item(), 3))
masked = torch.tensor([-100, 9, 2])  # -100 means "no loss at this position"
print("first position set to -100:", round(F.cross_entropy(probs.log(), masked).item(), 3))

# 2. Two course examples in TRL's prompt-completion format.
SYSTEM = "Convert equipment reports to JSON records."
INSTRUCTION = ("Keys: asset, equipment, category (repair, cleaning, replacement, inspection), "
               "location, priority (low, normal, high, urgent).\nReport: {}")


def example(report, record):
    return {"prompt": [{"role": "system", "content": SYSTEM},
                       {"role": "user", "content": INSTRUCTION.format(report)}],
            "completion": [{"role": "assistant", "content": json.dumps(record)}]}


rows = [
    example("Hello team, the tent TN-20 at the boathouse has gone missing. It is needed for tomorrow's session.",
            {"asset": "TN-20", "equipment": "tent", "category": "replacement",
             "location": "boathouse", "priority": "high"}),
    example("PD-03 (paddle, lodge) is broken.",
            {"asset": "PD-03", "equipment": "paddle", "category": "repair",
             "location": "lodge", "priority": "normal"}),
]

# 3. The mask by hand: -100 for every prompt token, the token ID for every answer token.
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, revision=REVISION)
first = rows[0]
prompt_text = tokenizer.apply_chat_template(first["prompt"], tokenize=False, add_generation_prompt=True)
full_text = tokenizer.apply_chat_template(first["prompt"] + first["completion"], tokenize=False)
prompt_ids = tokenizer(prompt_text, add_special_tokens=False)["input_ids"]
input_ids = tokenizer(full_text, add_special_tokens=False)["input_ids"]
hand_labels = [-100] * len(prompt_ids) + input_ids[len(prompt_ids):]
loss_ids = [t for t, label in zip(input_ids, hand_labels) if label != -100]
print("\n== the mask by hand")
print(f"{len(input_ids)} tokens, {len(prompt_ids)} masked, {len(loss_ids)} carry loss")
print("loss-bearing text:", repr(tokenizer.decode(loss_ids)))

# 4. The labels TRL prepares. Building the trainer tokenises the data; nothing is trained.
model = AutoModelForCausalLM.from_pretrained(MODEL_ID, revision=REVISION, dtype=torch.float32)
trainer = SFTTrainer(model=model, processing_class=tokenizer, train_dataset=Dataset.from_list(rows),
                     args=SFTConfig(output_dir="trainer-output", use_cpu=True, bf16=False, report_to="none"))
prepared = trainer.train_dataset[0]
print("\n== TRL's labels")
print("columns:", trainer.train_dataset.column_names)
print("same token IDs:", prepared["input_ids"] == input_ids)
print("labels match the hand mask at every position:", prepared["labels"] == hand_labels)

# 5. Padding: the shorter example is padded with <|im_end|>, SmolLM2's pad token.
batch = trainer.data_collator([trainer.train_dataset[0], trainer.train_dataset[1]])
ids, labels, attention = batch["input_ids"][1], batch["labels"][1], batch["attention_mask"][1]
real = attention.bool()
end_of_turn = (ids == tokenizer.eos_token_id) & real
print("\n== padding the shorter example")
print(f"batch shape {tuple(batch['input_ids'].shape)}; this example: {int(real.sum())} real tokens, "
      f"{int((~real).sum())} padding")
print("every padding label is -100:", bool((labels[~real] == -100).all()))
print("labels at its real <|im_end|> tokens:", labels[end_of_turn].tolist())

# 6. The shift: the logits at position t are scored against the token at t + 1.
x, y = torch.tensor([input_ids]), torch.tensor([hand_labels])
model.eval()
with torch.no_grad():
    output = model(input_ids=x, labels=y)
    shifted = F.cross_entropy(output.logits[0, :-1], y[0, 1:], ignore_index=-100)
    unshifted = F.cross_entropy(output.logits[0], y[0], ignore_index=-100)
print("\n== the one-token shift")
print(f"model's own loss         {output.loss.item():.4f}")
print(f"by hand, shifted         {shifted.item():.4f}")
print(f"by hand, not shifted     {unshifted.item():.4f}")

What each part does:

  • Part 1 builds three probability rows over a ten-token vocabulary and scores them with PyTorch's cross_entropy, with and without -100. cross_entropy expects scores before softmax, and the logarithm of a probability row is such a score.
  • Parts 2 and 3 template one example for inference and in full, and build the mask: -100 for each of the inference prompt's tokens, then the rest of the token IDs.
  • Part 4 builds an SFTTrainer without training it. Building it is enough: TRL tokenises the data and adds its labels column. The model is loaded in float32. Transformers 5 would otherwise load SmolLM2 in bfloat16, and its rounding makes hand and model losses differ in the fourth decimal place.
  • Part 5 pads the two examples into one batch with TRL's collator and looks at the shorter one.
  • Part 6 computes the loss three ways.

The stop script

Save this as stop_demo.py:

"""Show how a reply stops, and two ways it fails to.

Run from ~/finetune-practice/loss-masks with the course environment active:
    python stop_demo.py
"""

import json

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

MODEL_ID = "HuggingFaceTB/SmolLM2-135M-Instruct"
REVISION = "12fd25f77366fa6b3b4b768ec3050bf629380bac"
torch.set_num_threads(4)
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, revision=REVISION)
model = AutoModelForCausalLM.from_pretrained(MODEL_ID, revision=REVISION, dtype=torch.float32)
print("generation stops at token", model.generation_config.eos_token_id,
      repr(tokenizer.convert_ids_to_tokens(model.generation_config.eos_token_id)))

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 = json.dumps({"asset": "TN-20", "equipment": "tent", "category": "replacement",
                     "location": "boathouse", "priority": "high"})
inference_prompt = tokenizer.apply_chat_template(prompt, tokenize=False, add_generation_prompt=True)


def continue_text(text, **settings):
    """Greedy continuation of text; prints it with and without special tokens."""
    inputs = tokenizer(text, return_tensors="pt", add_special_tokens=False)
    with torch.inference_mode():
        output = model.generate(**inputs, max_new_tokens=40, do_sample=False,
                                pad_token_id=tokenizer.pad_token_id, **settings)
    new = output[0, inputs["input_ids"].shape[1]:]
    print(f"{len(new)} new tokens")
    print("raw:    ", repr(tokenizer.decode(new)))
    print("decoded:", repr(tokenizer.decode(new, skip_special_tokens=True)))


# A. The correct record is already written, as if the model had produced it.
print("\n== A. after the record, with the model's own stop token")
continue_text(inference_prompt + record)

# B. The same, but generation is told to stop at a token the model never writes here.
print("\n== B. after the record, stopping at <|endoftext|> instead")
continue_text(inference_prompt + record, eos_token_id=tokenizer.convert_tokens_to_ids("<|endoftext|>"))

# C. The prompt without the assistant header that add_generation_prompt=True adds.
print("\n== C. the prompt without the generation header")
continue_text(tokenizer.apply_chat_template(prompt, tokenize=False))

continue_text generates greedily, so the output is the same on every run. Cases A and B start from the inference prompt plus the correct record, as if the model had just written it: they test only what happens at the end of the answer. Case C starts from a prompt templated without add_generation_prompt=True.

Run them

Predict before you run:

  1. How many of the 119 tokens carry loss?
  2. Will the shorter example's real <|im_end|> keep its label after padding?
  3. In case B, what will the model write after its <|im_end|>?
python loss_mask.py
python stop_demo.py

Output from the course's test (illustrative; the masks and generated text should match yours exactly, and the losses to about the fourth decimal place):

== cross-entropy by hand
each -log p: [0.693, 1.386, 0.223]
mean loss:   0.768
first position set to -100: 0.805

== the mask by hand
119 tokens, 78 masked, 41 carry loss
loss-bearing text: '{"asset": "TN-20", "equipment": "tent", "category": "replacement", "location": "boathouse", "priority": "high"}<|im_end|>\n'

== TRL's labels
columns: ['prompt', 'completion', 'input_ids', 'labels']
same token IDs: True
labels match the hand mask at every position: True

== padding the shorter example
batch shape (2, 119); this example: 103 real tokens, 16 padding
every padding label is -100: True
labels at its real <|im_end|> tokens: [-100, -100, 2]

== the one-token shift
model's own loss         0.7204
by hand, shifted         0.7204
by hand, not shifted     18.5968
generation stops at token 2 '<|im_end|>'

== A. after the record, with the model's own stop token
1 new tokens
raw:     '<|im_end|>'
decoded: ''

== B. after the record, stopping at <|endoftext|> instead
40 new tokens
raw:     '<|im_end|>\n<|im_end|><|im_start|>system\n<|im_end|>\n<|im_start|>user\nWhat is the best way to prepare for a job interview in the tech industry? Your response should contain at least 3 bullet points. Use the'
decoded: '\nsystem\n\nuser\nWhat is the best way to prepare for a job interview in the tech industry? Your response should contain at least 3 bullet points. Use the'

== C. the prompt without the generation header
40 new tokens
raw:     '<|im_start|>assistant\n{\n  "type": "report",\n  "data": {\n    "type": "report",\n    "data": {\n      "type": "report",\n      "data":'
decoded: 'assistant\n{\n  "type": "report",\n  "data": {\n    "type": "report",\n    "data": {\n      "type": "report",\n      "data":'

Read the output

  • Cross-entropy by hand. 0.768 for three positions, 0.805 when the first is ignored: the mean is over the scored positions only.
  • The mask. 78 masked, 41 carrying loss, and the loss-bearing text is exactly the record, <|im_end|> and the newline.
  • TRL's labels match the hand mask at every position. The columns show where they live: input_ids and labels, beside the original prompt and completion.
  • Padding. The shorter example has 103 real tokens and 16 of padding, all -100. It has three real <|im_end|> tokens: the first two end the system and user turns and are prompt, so -100; the last ends the answer and keeps its label, 2.
  • The shift. With the shift, the hand computation equals the model's loss. Without it, each prediction is scored against the token it was given rather than the next one, and the loss is about 26 times larger.
  • Case A. After the correct record the model writes <|im_end|> and stops: one new token. Even the untuned model has learned this ending.
  • Case B. Told to stop at <|endoftext|>, a token it does not write here, the model writes <|im_end|>, carries on, and invents a new conversation about job interviews. Decoded with skip_special_tokens=True, as the course's scoring does, the markers vanish and the reply reads system, user and a question. This is what a run-on reply looks like.
  • Case C. Without the generation header the model writes <|im_start|>assistant itself, so the decoded reply starts with assistant. (The untuned model's answer is wrong anyway; the beginning is the point.)

When your result differs

What you seeLikely causeWhat to do
labels match the hand mask at every position: FalseThe SFTConfig was changed, often completion_only_lossCompare the SFTConfig line with the script; the "Your turn" below changes it on purpose
Hand and model losses differ in the fourth decimal placeThe model was loaded without dtype=torch.float32Check the from_pretrained line
Case A writes more than one tokenA different model revision, or the record text was changedCheck REVISION and the record
An error about offline mode or a missing fileHF_HOME points elsewhere, or the model was not downloadedRun the setup lesson's check_setup.py

Your turn: score the whole sequence

Predict first: with completion_only_loss=False, how many of the 119 labels will not be -100, and how many predictions will the loss actually score after the shift?

Then copy loss_mask.py to full_loss.py and, in the copy only, add completion_only_loss=False to the SFTConfig(...) call. Run it, then run the first half of the copy again and count its labels:

python -c "exec(open('full_loss.py').read().split('# 5. Padding')[0]); print(sum(l != -100 for l in prepared['labels']), prepared['labels'] == input_ids)"

Hint 1

With nothing masked, what is left to distinguish a label from the token ID at the same position?

Hint 2

The shift drops one label. Which one?

Solution

The script now prints labels match the hand mask at every position: False. The one-line check prints the first sections again, then 119 True: every label is simply the token ID at its position. After the shift the loss scores 118 predictions, because the first token has nothing before it to predict it.

So in full-sequence mode 118 predictions are scored, of which only 41 are the answer. The model spends most of its training signal learning to reproduce the system message, the instruction and reports it will always be given, and its loss is no longer comparable with a completion-only run.

Independent task: trace three faulty replies

Each reply below came from a fine-tuned course model, with the evidence a colleague collected. The replies were written for this exercise; replies 1 and 2 have the shapes that stop_demo.py produces. For each, name the cause, the evidence that shows it, and a specific fix.

  1. The reply assistant\n{"asset": "KY-07", "equipment": "kayak", ...}. The scoring code builds prompts with tokenizer.apply_chat_template(prompt, tokenize=False).
  2. The reply {"asset": "TN-20", ..., "priority": "high"}\nsystem\n\nuser\nWhat is the best way to prepare for a job interview. The scoring code calls model.generate(..., eos_token_id=0).
  3. The reply {"asset": "HM-12", ..., "priority": "low"}{"asset": "HM-13", ..., "priority": "normal"}. Decoding the loss-bearing labels of one training example gives {"asset": "HM-40", ..., "priority": "high"}, with nothing after the closing brace.

Hints

  • In each case, ask what the model saw in training at that point, and what it saw at inference.
  • For reply 3, compare the decoded labels with this lesson's 41 loss-bearing tokens.

Solution

  1. Missing generation header. Evidence: the prompt call has no add_generation_prompt=True, so the prompt ends after the user turn and the model writes the assistant header itself. Fix: add add_generation_prompt=True, as course_eval.py does. Not a fix: stripping assistant from the reply.
  2. Generation stops at the wrong token. Evidence: eos_token_id=0 is <|endoftext|>; the model wrote <|im_end|> after the record, as case B shows, and generation carried on into an invented turn. Fix: remove the argument, so the model's own generation_config (ID 2) applies. Not a fix: a smaller max_new_tokens.
  3. The end-of-turn token was masked in training. Evidence: the loss-bearing labels end at }; in a correct mask they end with <|im_end|> and a newline. Nothing in training taught the model to stop after a record, so it went on to write another. Fix: rebuild the training labels so the end-of-turn token carries loss, check them as in this lesson, and retrain. Not a fix: cutting the reply after the first }, which hides the fault.

Reset and cleanup

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

cd ~/finetune-practice/loss-masks && pwd
cd .. && rm -rf loss-masks

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

Check your understanding

  1. A training example's templated text is <|im_start|>user\nPD-03 is broken.<|im_end|>\n<|im_start|>assistant\n{"asset": "PD-03", ...}<|im_end|>\n. With completion-only loss, which parts carry loss?
  2. Two positions have probabilities 0.5 and 0.25 for their right tokens, and a third position has label -100. What is the loss?
  3. A batch pads with <|im_end|>. A colleague's collator sets -100 wherever input_ids equals the pad token ID. What will the trained model do, and why?
  4. Why does the labels column line up with input_ids rather than being shifted by one?

Answer all four before reading on.

Answers

  1. The record, the final <|im_end|> and the newline after it. The user turn, its <|im_end|> and the assistant header are prompt, labelled -100.
  2. (0.693 + 1.386) / 2 = 1.040. The ignored position is left out of both the sum and the count.
  3. It will not stop after its answer. The rule masks the real end-of-turn token too, because it has the same ID as padding, so the model is never scored on writing it. TRL's collator masks by the attention mask instead.
  4. Transformers shifts inside the model's loss: the output at position t is compared with the label at t + 1. Shifting the labels as well would score each prediction two tokens ahead.

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