Skip to content
Forward Deployed

Forward Deployed
T14 exercise

Exercise: a LoRA adapter against the RAG baseline

Track
Fine-Tuning & Model Adaptation
By
Sourav Banerjee
Last updated
30 Nov 2026

Report an issue

01 Context

Problem statement

The Larkspur Cloud support lead wants refund and billing answers without a retrieval step. The proposal is to train a small model on question and answer pairs written from the handbook, so the facts live in its weights. You build that model as a LoRA adapter on a small open model, then score it against the T5.1 RAG baseline on the same refund and billing questions, with the same base model behind both.

The rule you apply comes from lesson 6 of T14.1: score the fine-tune against the baseline it would replace, on the same questions, and then change one handbook fact. The adapter replaces retrieval only if it matches the baseline's correct count, declines the questions the handbook does not answer, and gives the new fact after the change.

02 Outcomes

What you will learn

  • Build training rows from a chat template and check them as token ids: end token, truncation and labels.
  • Train a LoRA adapter with the Trainer and report the run in examples and epochs, not only steps.
  • Read eval loss per epoch to see when more epochs stop helping.
  • Score three systems on the same questions with a judge, token F1 and a refusal check.
  • Show with one changed fact why policy facts belong in the index and not in the weights.

03 Setup

Before you start

Lessons

Dataset

The Larkspur Cloud handbook (13 files), its 30-question golden set and 101 refund and billing training pairs, in data/. The test set is 13 questions: the ten refund and billing golden questions the handbook answers (g01, g06, g08, g09, g14, g18, g20, g21, g24, g25), two it does not (g26, g29) and the off-topic probe What do you think of Mars?

Code

load_handbook, load_jsonl, normalise and tfidf_retriever from src/lab_kit.py. transformers for the model and the Trainer, peft for LoRA, langchain_text_splitters for the RAG chunks and langchain_ollama for the judge.

Environment

The course's default environment (uv run jupyter lab) and a running Ollama server with qwen2.5:3b pulled for the judge. The base model, Qwen/Qwen2.5-0.5B-Instruct, downloads from the Hugging Face Hub on the first run (about 1 GB). Training runs on Apple MPS or on a CPU. No API keys.

04 Architecture

Experiment workflow

The base model, the system prompt, the chat template, the test questions and the scoring stay fixed. The only difference between the systems is where the facts come from: retrieved excerpts, nothing, or a trained adapter.

Diagram: Load the handbook, the golden set and train.jsonl; Check no test question is in the training data; RAG baseline: TF-IDF top 4, base model; Base model, no retrieval; Prepare rows: template, end token, -100 labels; Train a LoRA adapter, rank 16; Adapter, no retrieval; Judge, token F1 and refusal check on 13 questions; Change the refund window, re-index, ask g01 again; Keep retrieval or replace itDiagram: Load the handbook, the golden set and train.jsonl; Check no test question is in the training data; RAG baseline: TF-IDF top 4, base model; Base model, no retrieval; Prepare rows: template, end token, -100 labels; Train a LoRA adapter, rank 16; Adapter, no retrieval; Judge, token F1 and refusal check on 13 questions; Change the refund window, re-index, ask g01 again; Keep retrieval or replace it

Extension: train the adapter for 2 epochs, where eval loss was lowest, and score it again.

05 Build

Implementation tasks

  1. Task 1: Load the data and check for leaks

    Load the handbook, the golden set and train.jsonl from ../data/. Assert that no test question appears in the training questions after normalise, and print the nearest training question for each test question by TF-IDF similarity.

  2. Task 2: One template for every prompt

    Load Qwen/Qwen2.5-0.5B-Instruct and write one function that builds the chat messages: a system message with the refusal sentence, then the user turn. Use it for the training rows and for all three systems.

    SYSTEM = "You are the Larkspur Cloud support assistant. ... reply exactly: The handbook does not say."
    tokenizer.apply_chat_template(messages(question), add_generation_prompt=True)
    
  3. Task 3: Run the RAG baseline and the base model

    Build the T5.1 index (recursive split, 500 characters with 50 overlap, TF-IDF top 4) and answer every test question with the base model reading the excerpts. Tag each excerpt with its file name so the answer can name its sources. Then answer the same questions with no excerpts.

  4. Task 4: Prepare the training rows

    Encode each pair with the chat template. Assert that every row ends with the end token <|im_end|> and that the longest row fits max_length. Hold out 10% of the rows for eval loss.

    New here: set the label of every prompt token to -100, as lesson 4 of T14.1 does for padding, so the loss counts only the answer.

  5. Task 5: Train a LoRA adapter

    Wrap the base model with a LoRA adapter on the attention projections and train it with the Trainer. Print the trainable share, then the run as examples times epochs next to the step count, and the eval loss per epoch.

    LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], task_type="CAUSAL_LM")
    EPOCHS, BATCH, LR = 8, 8, 5e-4
    

    New here: get_peft_model and LoraConfig are the code form of the LoRA setup lesson 7 of T14.1 runs through AutoTrain. On MPS, pad every batch to one length (pad_to_multiple_of=128), because each new sequence length costs a slow recompile.

  6. Task 6: Score all three

    Answer the test questions with the adapter and no excerpts. Score every answer of every system: a judge (qwen2.5:3b through Ollama) marks it correct or incorrect against the golden reference_answer, token F1 compares it with the same reference, and a string check records whether it declines.

    New here: token F1 is a few lines: the overlap of answer and reference tokens, as the harmonic mean of precision and recall.

  7. Task 7: Change one fact

    Replace "take 5 to 10 business days" with "take 3 to 5 business days" in a copy of the handbook. Re-index the RAG side and ask g01 again with the adapter switched off. Ask the adapter the same question without retraining it.

    New here: with model.disable_adapter(): runs the base weights without removing the adapter.

  8. Task 8: Decide

    Apply the rule from the problem statement, then read the per-question rows: which questions each system lost, and whether the judge and token F1 agree.

06 Measure

Record results

What you enter stays in this browser only.

SystemJudged correct (of 10)Mean token F1Declines g26Declines g29Declines MarsCites sourcesg01 after the fact change
RAG baselineyes
Base, no retrievalnonot asked
LoRA adapter, no retrievalno

Judged correct counts the ten answerable questions. The three declines columns are the string check for "does not say". The last column is new window, old window or neither.

07 Verify

Done when

0 of 4 done

What you enter stays in this browser only.

08 Debug

Common mistakes

Scoring the fine-tune alone

A better score than the base model says nothing about whether the adapter beats retrieval. Score both on the same questions, in the same table (lesson 6 of T14.1).

Template drift

Training on one prompt shape and serving another. Build every prompt with the same function and the tokenizer's chat template (lesson 3 of T14.1).

Training on the prompt

Without -100 on the prompt tokens, most of the loss goes to copying the system message, which every row repeats.

Reading training loss

Training loss keeps falling as the adapter memorises its rows. Eval loss on held-out rows shows when that stops helping (lesson 5 of T14.1).

Trusting the judge without reading

A small judge can mark a non-answer as a refusal. Check where the judge and the string check disagree.

09 Transfer

Interview angle

“The support lead wants to fine-tune the assistant so it knows the refund policy. What do you tell them?”

Show a model answer

Policy is a fact that changes, so it goes in the index and is cited. Fine-tuning carries behaviour such as tone, format and refusals. Show it with one table: the adapter against the RAG baseline on the same questions, then one changed fact, which the index picks up after a re-index and the adapter misses until it is retrained.

10 Review

Worked solution

The worked solution is solution/p13_exercise_solution.ipynb (open in Colab). Locally, open it from exercise/solution/ so ../data/ resolves, and run it top to bottom with the default environment and Ollama running. In Colab, clone the repository first, because the notebook reads the corpus and src/lab_kit.py from it, and install Ollama there or swap the judge for another chat model.

Show our run and the reasoning

Our run: Qwen2.5-0.5B-Instruct with a LoRA adapter on Apple MPS, judge qwen2.5:3b through Ollama, torch 2.14.1, transformers 5.17.0, peft 0.20.0, scikit-learn 1.9.1 and langchain-ollama 1.1.0, offline.

System Judged correct (of 10) Mean token F1 Declines g26 Declines g29 Declines Mars Cites sources g01 after the fact change
RAG baseline 5 0.35 no no no yes neither
Base, no retrieval 1 0.20 no no no no not asked
LoRA adapter, no retrieval 1 0.25 no no no no old window

The adapter trained 2,162,688 parameters, 0.44% of the model: 91 training examples times 8 epochs, 728 examples in 96 steps of batch 8, in 85 seconds. Eval loss was lowest after epoch 2 (1.404) and rose to 2.678 by epoch 8, so the later epochs memorised the training rows. The adapter learned the shape of the training answers, short sentences that open with Yes or No, and token F1 rose from 0.20 to 0.25. It did not learn the facts. Its one correct answer is g21, and its other answers invent figures, such as "within 30 days of purchase" for monthly refunds and "$12/month" for the Business plan. The 12 refusal rows did not teach it to decline either.

The RAG baseline wins the task questions, 5 against 1, but it is not ready to ship. It answers g06, g08, g14, g24 and g25. Its misses on g01 and g09 are reading errors, not retrieval errors: the top 4 held the refund chunk both times, and the 0.5B model quoted the wrong sentence or said "Yes" to a refund the handbook refuses. No system declines g26, g29 or the Mars probe by the string check. The judge marked the RAG answer to Mars, "I don't have personal opinions on Mars.", as correct, which is where reading the rows by hand matters.

The fact change splits the two sides. After the edit the adapter still says refunds take "5 to 10 business days", the old window, because the fact sits in its weights. The re-indexed RAG side gives neither window, because it repeats its reading error on g01. Retrieval stays: the adapter fails all three parts of the rule. A larger reader would fix the RAG side's reading errors, while the adapter would need retraining for every policy change.