FrontierBasics · step by step

Fine-tune an open-weight model, step by step

By the end you can explain to anyone what an LLM is, how it is built, what fine-tuning changes, and every step you took to get the result.

In short: Fine-tuning means taking an existing AI model whose weights you can download (an open-weight You can download and run the weights. Still check the licence. model) and training it a little more on your own examples, so it learns one specific habit, such as always answering in a fixed format. The cheap, common way is to freeze the model and train only a small add-on (a method called LoRA; QLoRA when the model is also compressed to save memory), then test it on examples it has never seen.

Your project

You run support for a small online tea shop. Customer messages arrive messy. You want a model that turns each one into a clean ticket: category, urgency and a one-line summary, every time, in the same format.

Recordings replay a real workflow. Commands are real; outputs are examples of what you would see, not a live run.

Start

See the finish line

Why this step: Know what 'done' looks like before taking step one.

Read the transcript
  1. The same customer message goes to two models.

  2. $ ask original-model "Ordered Darjeeling on 3 Nov, still not here, need it for a gift on Friday!!"

    Send a customer message to the original, untouched model.

  3. I'm sorry to hear your order hasn't arrived! There are many reasons a parcel can be delayed, such as courier issues or high demand. Here are some steps you can take: 1. Check your tracking number...

    Polite, long, and not a ticket. Your software cannot read this.

  4. $ ask ticket-model "Ordered Darjeeling on 3 Nov, still not here, need it for a gift on Friday!!"

    Send the same message to the model you will build.

  5. {"category": "delivery", "urgency": "high", "summary": "Darjeeling order from 3 Nov not delivered; needed by Friday."}

    Short, structured, the same shape every time. This is the model you will build.

  6. Same starting model. The only difference: the second one was fine-tuned on 600 examples of messages and correct tickets.

  7. How you'll get there: first understand (3 steps), then plan (3 steps), then fine-tune it yourself in 6 steps: examples → machine → settings → train → test → ship.

What you just did: You saw the goal: a general model that writes paragraphs, turned into a specialist that writes tickets.

Recipe card +1 Goal: turn messy messages into clean tickets, every time.

Check: What is different about the second model?
Show the answer

It was trained further on examples of the exact task. Both start from the same model. Fine-tuning trained the second one further on 600 worked examples of the task.

Part 1 of 3

Understand

What an LLM is, how it is built, and whether you need to fine-tune at all.

Step 1 of 12 · Part 1, 1 of 3

What an LLM actually is

Why this step: You cannot explain fine-tuning without knowing what is being tuned.

Read the transcript
  1. An LLM (large language model) does one thing: given some text, it predicts the next piece of text.

  2. tok.tokenize("My order hasn't arrived")

    Ask the model's tokenizer (the part that cuts text into pieces) to show how it splits a sentence.

  3. ['My', 'Ġorder', 'Ġhasn', "'t", 'Ġarrived']

    Text is cut into tokens: words or word-pieces. Ġ marks a space.

  4. top_next_tokens("My order hasn't arrived")

    Ask the model: which piece of text is most likely to come next?

  5. ' yet'   41%
    '.'      22%
    ' and'   11%
    ' after'   6%

    For every possible next token the model gives a probability. Pick one, add it, repeat. That loop writes whole answers.

  6. Those probabilities come from billions of numbers inside the model, called weights (or parameters). The weights ARE the model.

What you just did: You saw that an LLM is a next-token predictor, and that its behaviour lives in its weights.

Recipe card +1 An LLM predicts the next token; its knowledge and habits live in its weights.

Check: Where does a model's behaviour actually live?
Show the answer

In its weights, the billions of numbers inside it. The weights decide the probabilities for every next token. Change the weights and you change the behaviour. That is what fine-tuning does.

Step 2 of 12 · Part 1, 2 of 3

How an LLM is built

Why this step: Fine-tuning is the last stage of a recipe the model maker already started. See the whole recipe.

Read the transcript
  1. Stage 1, pretraining: the model reads trillions of tokens of text and practises predicting the next token. Weights start random and are nudged after every guess. Costs millions of dollars.

  2. Result: a base model. It knows language and facts, but it only continues text. It does not follow instructions.

  3. Stage 2, instruction tuning: more training on examples of questions with good answers. Now it behaves like an assistant.

  4. Stage 3, preference tuning: people (or another model) pick the better of two answers, and the model is trained toward the preferred one.

  5. sum(p.numel() for p in model.parameters())

    Count every weight inside the model.

  6. 1,543,714,304

    The model you will download has finished all three stages: 1.5 billion weights, ready to use.

  7. Your fine-tune is stage 4: a small extra round of training on YOUR examples. Hours, not months; one GPU A chip that does millions of small sums at once. Models train and run on them., not thousands.

What you just did: You saw the three stages a model maker runs, and that your fine-tune is a small fourth stage on top.

Recipe card +1 Built in stages: pretraining → instruction tuning → preference tuning. Fine-tuning adds one more, with my data.

Check: Which stage teaches the model language and general knowledge?
Show the answer

Pretraining. Pretraining on trillions of tokens is where knowledge comes from. Later stages shape behaviour, not knowledge.

Step 3 of 12 · Part 1, 3 of 3

Is fine-tuning even needed?

Why this step: Nothing is trained in this step: the model stays exactly as it is. We only test whether written instructions alone are enough, because fine-tuning costs time and GPU A chip that does millions of small sums at once. Models train and run on them. hours.

Read the transcript
  1. First, the cheap way: write instructions and examples into every message (prompting). The model itself does not change.

  2. $ python try_prompt.py --test 50

    Run 50 test messages through the model with our best written instructions, and count good tickets.

  3. valid JSON tickets: 41 / 50
    wrong category:    7 / 50

    Close, but 9 broken tickets in 50 would break the software that reads them. Instructions alone are not enough.

  4. Option 2, RAG (retrieval): fetch relevant documents and paste them into the prompt. Right tool when the model is missing FACTS, such as today's prices or your policies.

  5. Option 3, fine-tuning: right tool when the model is missing a BEHAVIOUR: a fixed format, a tone, a narrow task done the same way thousands of times.

  6. Our problem is behaviour (always output a ticket in one shape), so fine-tuning fits.

What you just did: Without changing the model, you tested instructions alone. They fell short on consistency, and the gap is behaviour, not facts, so you chose to fine-tune.

Recipe card +1 Try prompting first. Facts missing → RAG. Behaviour missing → fine-tune.

Check: Your model keeps getting this week's prices wrong. Best fix?
Show the answer

RAG: fetch current prices into the prompt. Prices are facts that change. A fine-tune would freeze old prices into the weights. Retrieval gives fresh facts each time.

Part 2 of 3

Plan

Choose the method and the model before touching any data.

Step 4 of 12 · Part 2, 1 of 3

How much of the model do you change?

Why this step: Changing all 1.5 billion weights needs expensive hardware. Most people change a tiny add-on instead.

Read the transcript
  1. Full fine-tuning: change all 1.5 billion. Best quality ceiling, but needs ~16 bytes of GPU A chip that does millions of small sums at once. Models train and run on them. memory per weight: about 25 GB Gigabyte, a unit of memory. This 1.5-billion-weight model is about 3 GB. for this small model.

  2. PEFT (parameter-efficient fine-tuning): freeze the model, train a small add-on. Main types: LoRA, QLoRA, DoRA A refined LoRA that adjusts size and direction separately., adapters Small extra layers inserted into the model and trained., prefix tuning Trains a few learned 'virtual tokens' fed in before the input., prompt tuning Like prefix tuning, but only at the input..

  3. LoRA: beside each big weight table, add two thin tables whose product is a small correction. Only the thin tables train: about 1% of the weights.

  4. QLoRA: LoRA, with the frozen model stored in 4-bit numbers to save memory. Fits on a free 16 GB GPU.

  5. Our pick: QLoRA. It fits on one free 16 GB GPU and trains only about 1% of the weights.

What you just did: You compared changing every weight (full fine-tuning) with training a small add-on (LoRA, QLoRA), and chose QLoRA.

Recipe card +1 How: QLoRA. Keep the model frozen in 4-bit and train a small LoRA add-on.

Check: What does LoRA train?
Show the answer

Small add-on tables beside the frozen weights. LoRA freezes the original weights and trains thin add-on tables, about 1% of the size, that apply a small correction.

Step 5 of 12 · Part 2, 2 of 3

What do you teach it?

Why this step: The kind of examples you have decides the training method.

Read the transcript
  1. SFT (supervised fine-tuning): show input → correct output pairs. Our case.

  2. Preference tuning Training toward the better of two answers.: show a better and a worse answer. Methods: RLHF Reinforcement learning from human feedback: people rate answers, the model learns from the ratings. with PPO The classic training algorithm used inside RLHF., DPO Learns straight from better-vs-worse answer pairs. Simpler than RLHF., ORPO Does SFT and preference learning in one pass., KTO Learns from answers simply marked good or bad, no pairs needed.; GRPO Scores many answers with a rule (is the maths right?) and trains toward the best. Used for reasoning models. scores answers with a reward rule, used for reasoning.

  3. Two more names: continued pretraining (feed raw domain text, e.g. legal documents) and distillation (train a small model on a big model's answers).

  4. Our pick: SFT. Our data is message → correct ticket, exactly what SFT learns from.

What you just did: You learned the training methods by the kind of example each needs, and chose SFT.

Recipe card +1 What: SFT. Show the model messages with the correct ticket.

Check: You have pairs of answers where people marked one as better. Which method fits?
Show the answer

DPO. DPO learns directly from better-versus-worse pairs. SFT needs a single correct answer per input.

Step 6 of 12 · Part 2, 3 of 3

Pick the base model

Why this step: The model must fit your GPU A chip that does millions of small sums at once. Models train and run on them., allow your use, and already be close to the task.

Read the transcript
  1. Common open-weight You can download and run the weights. Still check the licence. families: Llama, Qwen, Mistral, Gemma. 'Open-weight' means you can download the weights, not that anything goes: read the licence The legal terms of use. Apache-2.0 allows commercial use..

  2. 1,500,000,000 weights × 2 bytes   (16-bit) = 3.0 GB
    1,500,000,000 weights × 0.5 bytes (4-bit)  = 0.8 GB

    Back-of-envelope memory maths: number of weights × space per weight.

  3. Rule of thumb: weights take bytes-per-weight × count. Training needs room on top for the add-on, activations and optimizer.

  4. Pick 'Instruct A model that has had instruction tuning, so it follows requests.' over 'Base': it already follows instructions, so we only teach the ticket format.

  5. $ MODEL="Qwen/Qwen2.5-1.5B-Instruct"   # Apache-2.0 licence, 1.5B, instruct

    Write down which model we will use. This name is its address on Hugging Face The main website hosting open models and datasets., the site that hosts open models.

What you just did: You checked size against memory, checked the licence and chose a small instruct model.

Recipe card +1 Model: Qwen2.5-1.5B-Instruct: small, permissive licence, already follows instructions.

Check: Why start from an Instruct model instead of a Base model?
Show the answer

It already follows instructions, so we teach only our format. A base model only continues text. An instruct model already behaves like an assistant, so fewer examples are needed.

Part 3 of 3

Fine-tune it, step by step

The hands-on fine-tuning starts here. Six steps: examples → machine → settings → train → test → ship.

Step 7 of 12 · Part 3, 1 of 6

Prepare the examples

Why this step: The model learns only from your examples. Their quality sets the ceiling.

Read the transcript
  1. Each example is one conversation: the instruction, a customer message, and the correct ticket. One example per line, in a JSONL A file with one JSON record per line. file.

  2. $ head -n 1 tickets.jsonl

    Show the first line of our examples file.

  3. {"messages": [{"role": "system", "content": "Turn the message into a ticket."}, {"role": "user", "content": "Tin arrived dented, tea fine"}, {"role": "assistant", "content": "{\"category\": \"damage\", \"urgency\": \"low\", \"summary\": \"Tin dented in transit; contents fine.\"}"}]}

    The assistant turn is the answer we want the model to learn.

  4. $ wc -l tickets.jsonl

    Count the lines in the file. One line = one example.

  5. 600 tickets.jsonl

    Hundreds of clean, varied examples beat thousands of sloppy ones.

  6. ds = load_dataset("json", data_files="tickets.jsonl")["train"]
    ds = ds.train_test_split(test_size=0.1, seed=42)

    Load the file and split it: 90% to learn from, 10% kept aside for testing.

  7. train: 540 rows   test: 60 rows

    The 60 test examples are hidden from training. They are your honest exam later.

What you just did: You wrote 600 message → ticket examples in chat format and held 60 back for testing.

Recipe card +1 Data: 600 examples (message → correct ticket), 540 to train, 60 held back to test.

Check: Why hold back 60 examples the model never trains on?
Show the answer

To test it fairly on examples it has not memorised. A model can score well on examples it has seen by memorising. Unseen examples show whether it really learned the task.

Step 8 of 12 · Part 3, 2 of 6

Set up the machine

Why this step: Training runs on a GPU A chip that does millions of small sums at once. Models train and run on them., using a few standard open-source libraries.

Read the transcript
  1. A free Google Colab Google's free in-browser notebooks, with a borrowed GPU. notebook with a T4 A common GPU with about 15 GB of memory, free on Colab. GPU is enough for this model. A rented cloud GPU works the same way.

  2. $ nvidia-smi --query-gpu=name,memory.total --format=csv

    Ask the machine which GPU it has and how much memory.

  3. name, memory.total [MiB]
    Tesla T4, 15360 MiB

    15 GB Gigabyte, a unit of memory. This 1.5-billion-weight model is about 3 GB. of GPU memory: plenty for QLoRA on 1.5B.

  4. $ pip install -q transformers peft trl bitsandbytes datasets accelerate

    Download the free software tools we need (one line, about a minute).

  5. transformers loads models. peft Parameter-efficient fine-tuning: freeze the model, train a small add-on. adds LoRA. trl runs the training loop (SFTTrainer). bitsandbytes does 4-bit. Tools such as Unsloth and Axolotl wrap the same steps.

What you just did: You confirmed a GPU and installed the libraries, each with one clear job.

Recipe card +1 Machine: one 16 GB GPU + transformers, peft, trl, bitsandbytes.

Check: Which library adds the LoRA add-on to the model?
Show the answer

peft. peft (parameter-efficient fine-tuning) implements LoRA. bitsandbytes handles 4-bit storage; datasets loads the data.

Step 9 of 12 · Part 3, 3 of 6

Configure the run

Why this step: A few settings decide memory use, speed and how hard the model is pushed.

Read the transcript
  1. model = AutoModelForCausalLM.from_pretrained(MODEL,
        quantization_config=BitsAndBytesConfig(load_in_4bit=True))

    The Q in QLoRA: the frozen model is loaded in 4-bit (quantization Storing numbers with fewer bits to save memory, e.g. 16-bit to 4-bit. = storing numbers with fewer bits).

  2. lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
        target_modules="all-linear", task_type="CAUSAL_LM")

    r = width of the add-on tables (bigger = more capacity). alpha = how strongly the correction applies.

  3. args = SFTConfig(output_dir="ticket-lora", num_train_epochs=3,
        learning_rate=2e-4, per_device_train_batch_size=4,
        gradient_accumulation_steps=4, eval_strategy="steps", eval_steps=10,
        save_steps=10, load_best_model_at_end=True)

    Epochs = passes over the data. Learning rate How big each adjustment to the weights is. = size of each nudge. 4 × 4 = 16 examples per update.

  4. print(f"training {trainable:,} weights")

    Count how many weights will actually be trained.

  5. training 18,464,768 weights

    About 1.2% of 1.5 billion. The other 98.8% stay frozen.

What you just did: You loaded the model in 4-bit, attached a LoRA add-on and set how long and how hard to train.

Recipe card +1 Settings: 4-bit model, LoRA r=16, 3 passes, learning rate 2e-4, keep the best checkpoint.

Check: What does the learning rate control?
Show the answer

How big each nudge to the weights is. After each batch the weights are nudged to reduce error. The learning rate sets the size of that nudge: too big is unstable, too small is slow.

Step 10 of 12 · Part 3, 4 of 6

Train: how the model actually learns

Why this step: This is the step where the model changes. Training repeats one simple loop many times.

Read the transcript
  1. The loop: take one example message. The model writes its ticket word by word. Each word is compared with the correct ticket. Then the add-on is nudged so the right words become a little more likely.

  2. Nobody writes rules. The examples do the teaching. The loop covers all 540 examples, 3 times over, with a nudge after every batch of 16: about 100 nudges in total.

  3. Loss = how wrong the model's next-token guesses are on the ticket answers. Lower is better.

  4. $ trainer = SFTTrainer(model=model, args=args, peft_config=lora,
        train_dataset=ds["train"], eval_dataset=ds["test"])
    trainer.train()

    Hand everything to the trainer (model, settings, add-on, examples) and press start.

  5. step  train_loss  eval_loss
      10      1.92       1.41
      30      0.48       0.44
      50      0.31       0.36
      70      0.20       0.35
     100      0.11       0.41

    Both fall at first: the model is learning the task.

  6. After step 70, train loss keeps falling but eval loss rises. The model is starting to memorise the 540 examples instead of learning the pattern. This is overfitting.

  7. Loading best model from ticket-lora/checkpoint-70 (eval_loss 0.35)

    Because we set load_best_model_at_end, the run keeps the checkpoint A saved snapshot of the model mid-training. before overfitting began.

  8. On a T4 A common GPU with about 15 GB of memory, free on Colab. this takes about 15 minutes.

What you just did: You saw how training works (guess, compare with the right answer, nudge, repeat), watched the mistakes shrink, spotted overfitting and kept the best checkpoint.

Recipe card +1 Train: guess → compare with the right answer → nudge → repeat; stop when the test score gets worse.

Check: What happens in each round of training?
Show the answer

The model guesses, is compared with the correct answer, and is nudged toward it. Training is guess, compare, nudge, repeat. Small corrections from many examples add up to the new habit. No rules are written and nothing is copied in.

Step 11 of 12 · Part 3, 5 of 6

Test it honestly

Why this step: Low loss is a hint, not proof. Test the real task on the 60 held-back messages.

Read the transcript
  1. $ python evaluate.py --test 60

    Run all 60 held-back messages through the old and the new model, and score both.

  2.                  before   after
    valid JSON       51/60    60/60
    right category   41/60    55/60
    right urgency    38/60    52/60

    'Before' is the original model with the best prompt from step 3. 'After' is your fine-tune.

  3. Read some failures by hand, too. Several of the 5 wrong categories turn out to be 'damage' vs 'refund'. That points to unclear training examples, not a model problem.

  4. Also ask a few ordinary questions. A narrow fine-tune can make a model worse at everything else (called catastrophic forgetting Narrow training making a model worse at things it used to do.). Fine here: this model has one job.

What you just did: You measured the task on unseen messages, compared before and after, and read the failures.

Recipe card +1 Test: score the real task on held-back data, before vs after, and read the mistakes.

Check: What is the most honest test of your fine-tune?
Show the answer

Scoring the real task on held-back examples. Only unseen examples, scored on what you actually need (valid, correct tickets), show real improvement.

Step 12 of 12 · Part 3, 6 of 6

Merge, shrink and run it

Why this step: The add-on is a separate file. Make one model file that runs anywhere, including a laptop.

Read the transcript
  1. base = AutoModelForCausalLM.from_pretrained(MODEL, torch_dtype=torch.float16)
    merged = PeftModel.from_pretrained(base, "ticket-lora/checkpoint-70").merge_and_unload()
    merged.save_pretrained("ticket-model"); tok.save_pretrained("ticket-model")

    Reload the original in full 16-bit Each weight stored as a precise number in 2 bytes. Normal full quality., then fold the add-on into it. Merging into the 4-bit copy would lose quality.

  2. $ python llama.cpp/convert_hf_to_gguf.py ticket-model --outfile ticket.gguf
    llama-quantize ticket.gguf ticket-q4.gguf Q4_K_M

    Convert the model into one portable file, then shrink it to 4-bit.

  3. ticket.gguf      3.1 GB
    ticket-q4.gguf   1.0 GB

    GGUF A one-file model format that runs on ordinary laptops. is a single-file format for local tools. Q4_K_M stores it in about 4 bits per weight.

  4. $ echo "FROM ./ticket-q4.gguf" > Modelfile
    ollama create ticket-model -f Modelfile
    ollama run ticket-model "Wrong tea sent, I ordered green"

    Register the file with Ollama A free app that runs models on your own computer. (a free app that runs models on a laptop), then ask it a new message.

  5. {"category": "wrong-item", "urgency": "medium", "summary": "Received wrong tea; ordered green."}

    The finish line from step 0, now running on your own machine. For many users at once, serve it with vLLM Free software for serving a model to many users at once. instead.

What you just did: You folded the add-on into the model, shrank it to 1 GB Gigabyte, a unit of memory. This 1.5-billion-weight model is about 3 GB. and ran it locally.

Recipe card +1 Ship: merge the add-on into the full model, convert to GGUF, shrink to 4-bit, run with Ollama.

Check: Why merge the add-on into the full 16-bit model, not the 4-bit one?
Show the answer

Merging into the rounded 4-bit numbers loses quality. The 4-bit copy is a rounded version. Fold the correction into the precise original, then shrink once at the end.

Finish

Explain it back

Put your recipe back in order. If you can do this, you can explain fine-tuning to anyone.

  1. An LLM predicts the next token; its knowledge and habits live in its weights.
  2. Built in stages: pretraining → instruction tuning → preference tuning. Fine-tuning adds one more, with my data.
  3. Try prompting first. Facts missing → RAG. Behaviour missing → fine-tune.
  4. How: QLoRA. Keep the model frozen in 4-bit and train a small LoRA add-on.
  5. What: SFT. Show the model messages with the correct ticket.
  6. Model: Qwen2.5-1.5B-Instruct: small, permissive licence, already follows instructions.
  7. Data: 600 examples (message → correct ticket), 540 to train, 60 held back to test.
  8. Machine: one 16 GB GPU + transformers, peft, trl, bitsandbytes.
  9. Settings: 4-bit model, LoRA r=16, 3 passes, learning rate 2e-4, keep the best checkpoint.
  10. Train: guess → compare with the right answer → nudge → repeat; stop when the test score gets worse.
  11. Test: score the real task on held-back data, before vs after, and read the mistakes.
  12. Ship: merge the add-on into the full model, convert to GGUF, shrink to 4-bit, run with Ollama.
Fine-tuning in one minute

An LLM predicts the next token, and its behaviour lives in billions of weights. Model makers build it in stages: pretraining, instruction tuning, preference tuning. Prompting couldn't make it write our tickets reliably, and the gap was behaviour, not facts, so we fine-tuned. We used QLoRA with SFT: froze a 4-bit copy of a small instruct model and trained a 1% add-on on 540 message → ticket examples. We watched the loss, kept the best checkpoint before overfitting, scored it on 60 unseen messages (valid tickets went from 51 to 60), then merged it, shrank it to 1 GB and ran it locally.

Common questions

What is fine-tuning an LLM?
Training an existing model further on your own examples so its weights shift toward a specific behaviour, such as a fixed format, tone or narrow task.
When should I fine-tune instead of using RAG?
Fine-tune when the model lacks a behaviour (format, style, a repeated task). Use RAG when it lacks facts, especially facts that change.
What is the difference between LoRA and QLoRA?
LoRA trains small add-on tables beside frozen weights. QLoRA does the same with the frozen model stored in 4-bit, so it fits on a single 16 GB GPU.
What is the difference between SFT and DPO?
SFT trains on input → correct output pairs. DPO trains on pairs of a better and a worse answer, pushing the model toward the preferred one.
How many examples do I need to fine-tune?
For a narrow task, a few hundred clean, varied examples are often enough. Quality matters more than quantity.