Skip to the content.

LLM Course: Fine-Tuning Open Models with LoRA and QLoRA, from Data to Deployment

A practical, code-first course on fine-tuning open-weight large language models. It walks through the whole lifecycle: deciding whether to fine-tune at all, choosing a base model, preparing and cleaning chat data, understanding LoRA and QLoRA (with a parameter and memory calculator), training with Hugging Face TRL, evaluating against the base model, preference tuning with DPO, and merging, quantizing and serving the result with llama.cpp, Ollama or vLLM.

The data tooling (ftkit/) runs anywhere with plain Python and is tested. The training scripts (scripts/) target current library versions (TRL 1.x, PEFT 0.2x, Transformers 5.x) and need a GPU (or Apple silicon for small models). The running example teaches a small model to turn messy bug reports into structured JSON tickets, a realistic task where fine-tuning clearly beats prompting a small model. It is for developers and ML engineers who want to fine-tune their first model properly.

Last reviewed: December 2026. Library versions checked at review time: TRL 1.19, PEFT 0.22, Transformers 5.24, bitsandbytes 0.50. The training scripts were written against these APIs but are not executed in this repository’s tests (they need a GPU); the data tools and calculators are tested.

Contents

Course map

Module You will Code
0. Should you fine-tune? Pick between prompting, RAG and fine-tuning Decision table
1. Base model Choose size and variant, understand chat templates  
2. Data Convert, validate, scrub, deduplicate, split, check leakage ftkit/data.py, python -m ftkit.prepare
3. LoRA and QLoRA Understand adapters; compute trainable parameters and memory ftkit/lora_math.py
4. Training Run SFT with LoRA or QLoRA scripts/train_sft.py
5. Other tools Unsloth, Axolotl, LLaMA-Factory, MLX-LM Comparison table
6. Evaluation Compare tuned vs base on held-out data scripts/evaluate.py, ftkit/score.py
7. DPO Teach preferences with chosen/rejected pairs scripts/train_dpo.py
8. Deployment Merge, convert to GGUF, quantize, serve scripts/merge_adapter.py, serving/Modelfile

Setup

git clone https://github.com/Ralpberry-Labs/llm-course-fine-tuning.git
cd llm-course-fine-tuning

# Data tools: plain Python 3.10+, nothing to install
python -m ftkit.prepare data/sample_raw.jsonl --out data/prepared \
    --system "You turn bug reports into JSON tickets." --eval data/sample_eval.jsonl
python -m unittest discover -s tests -v          # 15 tests

# Training: a fresh virtual environment with PyTorch for your platform, then
pip install "trl>=1.19" "peft>=0.22" "transformers>=5" datasets accelerate
pip install bitsandbytes                          # only for QLoRA on NVIDIA GPUs

Install PyTorch first using the selector at pytorch.org, matching your CUDA version. The current releases of TRL, PEFT and Transformers require Python 3.11 or newer.

Module 0: Should you fine-tune?

Fine-tuning changes a model’s weights so it behaves differently by default. It is powerful, but it is usually not the first tool to reach for.

Your problem Try first Fine-tune when
The model lacks facts about your product or documents RAG (retrieve and include the facts) Rarely; facts change and need citations
Output format is inconsistent (JSON, labels, style) A clear prompt with examples, structured output features A small model must follow the format cheaply and reliably
Tone or style does not match your brand Prompt with examples You have hundreds of good examples and want it by default
A big model works but is too slow or expensive Prompt caching, batching Distill the big model’s behaviour into a small fine-tuned one
A narrow task (classification, extraction, routing) Few-shot prompting You have labelled data and need speed, privacy or on-device use
The model must run offline or on-device A small instruct model The small model is not good enough out of the box

Good signs that fine-tuning will pay off: a narrow, well-defined task, hundreds to thousands of high-quality examples (or a way to create them), a clear metric, and a reason to use a smaller or self-hosted model.

The running example fits all four: turning bug reports into {"component", "platform", "severity", "summary"} tickets, with a held-out set to score field accuracy.

Module 1: Choosing a base model

Instruct or base? Most projects should start from an instruct (chat) model: it already follows instructions, has a chat template, and needs less data. Start from a base model only when you want to teach a completely new format or behaviour from scratch, and expect to need more data.

Size. Pick the smallest model that can reach your quality bar:

Size Typical use after fine-tuning Hardware for LoRA training (rough)
0.5B to 1.5B Classification, extraction, routing, on-device A laptop GPU or Apple silicon; even CPU for tiny runs
3B to 4B Solid narrow assistants, structured output A single consumer GPU (QLoRA)
7B to 9B General assistants in a domain, harder reasoning 16 to 24 GB GPU with QLoRA
14B and up When smaller models clearly fail your evaluation Datacenter GPUs, or QLoRA on 40 to 80 GB

Practical checks before committing to a base model:

Chat templates matter. Each model family formats conversations with its own special tokens. Always format training data with the model’s own template (TRL does this automatically for conversational datasets), and use the same template at inference time. Mismatched templates are one of the most common reasons a fine-tuned model behaves strangely. See the Transformers guide to chat templates.

Module 2: Preparing data

Data quality decides the result more than any hyperparameter. Research on instruction tuning (for example LIMA) found that a small set of carefully curated examples can go a long way; a large noisy set teaches noise.

Formats

TRL accepts several dataset shapes. This course standardizes on conversational data:

{"messages": [
  {"role": "system", "content": "You turn bug reports into JSON tickets."},
  {"role": "user", "content": "Turn this bug report into a ticket ...\n\nsync stuck at 99% on my mac since yesterday"},
  {"role": "assistant", "content": "{\"component\": \"sync\", \"platform\": \"macos\", \"severity\": \"medium\", \"summary\": \"Sync stuck at 99% on macOS\"}"}
]}

ftkit.data.to_messages converts the other common formats into this one:

Input format Example keys Converted to
Conversational messages unchanged (optionally adds a system prompt)
Alpaca-style instruction, input, output user = instruction + input, assistant = output
Prompt-completion strings prompt, completion user = prompt, assistant = completion

The cleaning pipeline

python -m ftkit.prepare data/sample_raw.jsonl --out data/prepared \
    --system "You turn bug reports into JSON tickets." --eval data/sample_eval.jsonl
read 25 rows -> 23 valid conversations
  skipped line 23: last message must be from the assistant (that is what the model learns)
  skipped line 25: unrecognized format: expected messages, instruction/output, or prompt/completion
removed 1 exact and 1 near duplicates, 0 too long; redacted 2 PII/secrets
train=19 valid=2 -> data/prepared/train.jsonl, data/prepared/valid.jsonl
approx token lengths (train): {'count': 19, 'min': 80, 'median': 88, 'p95': 100, 'max': 100, 'total': 1652}
eval leakage: 1 of 3 eval examples overlap with training data (indexes [2])

The sample file was built with deliberate problems so you can see each step work:

Step What it catches Why it matters
Format conversion Unknown shapes Mixed sources are normal; normalize early
Validation Missing answers, wrong role order, empty messages, misplaced system prompts The model learns from assistant turns; broken transcripts teach broken behaviour
PII and secret scrubbing Emails, phone numbers, API-key-like strings Models can memorize and repeat training data
Exact deduplication Repeated examples Duplicates overweight some behaviours and inflate evaluation
Near-duplicate removal Same request with trivial differences Compares only the part of the prompt that varies, so a shared instruction does not make every pair look alike
Length filtering Examples longer than your training max_length Truncated examples lose the answer at the end
Train/validation split   Validation loss shows over-fitting
Leakage check Evaluation examples that also appear in training Leaked evals report fake accuracy; the command exits non-zero when it finds any

How much data?

Task type A useful starting point
Format or style adaptation A few hundred good examples
Narrow extraction or classification Hundreds to a few thousand, covering the label space
Domain assistant behaviour Thousands of diverse, high-quality conversations

Diversity beats volume: cover the input variety you expect in production (lengths, languages, typos, edge cases), and include examples of what to do when the input is unclear.

Synthetic data generated by a stronger model is a common way to bootstrap. Review samples by hand, deduplicate aggressively, and keep a human-written evaluation set that the generator never saw.

Module 3: LoRA and QLoRA, explained and sized

Full fine-tuning vs adapters

Full fine-tuning updates every weight. It needs memory for the weights, their gradients and the optimizer state, which for AdamW in mixed precision is roughly 16 bytes per parameter before activations.

LoRA (Low-Rank Adaptation) freezes the original weights and learns a small update for selected weight matrices:

W' = W + (alpha / r) · B · A          W: d_out × d_in (frozen)
                                      A: r × d_in, B: d_out × r (trained), r ≪ d

QLoRA (Efficient Finetuning of Quantized LLMs) loads the frozen base model in 4-bit NF4 precision and trains LoRA adapters on top, cutting memory again so that 7B to 9B models fit on a single consumer GPU. Quality is usually close to 16-bit LoRA; training is somewhat slower because of de-quantization.

Variants you will see in PEFT include DoRA (weight-decomposed LoRA) and others; start with plain LoRA and change one thing at a time.

Count the parameters

ftkit/lora_math.py computes exact LoRA parameter counts from a model’s shape. For a Llama-3-8B-shaped model (hidden 4096, MLP 14336, 32 layers, 32 query heads, 8 key/value heads, head size 128):

from ftkit.lora_math import DecoderShape, model_lora_params
shape = DecoderShape(hidden=4096, intermediate=14336, layers=32, heads=32, kv_heads=8, head_dim=128)
model_lora_params(shape, r=16)                              # 41,943,040 (all 7 linear layers per block)
model_lora_params(shape, r=16, targets=("q_proj", "v_proj"))  # 6,815,744

About 42 million trainable parameters, roughly half a percent of the model. Targeting all linear layers (target_modules="all-linear" in PEFT) generally works better than attention-only targets, for a modest increase in adapter size.

Estimate memory

Rough memory for weights, gradients and optimizer state only, for an 8-billion-parameter model with the r=16 adapter above (from estimate_memory_gib):

Method Rough memory (excluding activations)
Full fine-tuning, mixed precision AdamW about 120 GiB
LoRA on a bf16 base about 16 GiB
QLoRA on a 4-bit base about 5 GiB
Inference, bf16 about 15 GiB
Inference, 4-bit about 4 GiB

Activations come on top and grow with batch size and sequence length. Gradient checkpointing (on by default in TRL’s SFTConfig) trades compute for activation memory. Treat these as planning numbers and measure on your hardware.

Module 4: Training with TRL

scripts/train_sft.py is a complete supervised fine-tuning (SFT) script using TRL’s SFTTrainer:

# LoRA, bf16 base (NVIDIA GPU or Apple silicon for small models)
python scripts/train_sft.py --model Qwen/Qwen3-0.6B \
    --train data/prepared/train.jsonl --valid data/prepared/valid.jsonl \
    --output runs/tickets-lora --epochs 3

# QLoRA, 4-bit base (NVIDIA GPU with bitsandbytes)
python scripts/train_sft.py --model <a 7B-9B instruct model> --qlora \
    --train data/prepared/train.jsonl --valid data/prepared/valid.jsonl --output runs/tickets-qlora

What the script does, and why:

  1. Converts each conversation to prompt-completion form (everything before the last answer is the prompt; the last assistant message is the completion). TRL then computes the loss only on the completion, so the model learns to answer rather than to imitate the questions.
  2. Builds a LoRA config with target_modules="all-linear", r=16, alpha=32, dropout 0.05.
  3. Optionally loads the base in 4-bit NF4 with double quantization and bfloat16 compute (--qlora), passed to SFTTrainer(quantization_config=...).
  4. Loads the model in bfloat16 via model_init_kwargs={"dtype": ...}. When given a model ID string, TRL otherwise loads in float32.
  5. Evaluates and saves every 50 steps, keeps the best checkpoint by validation loss, and saves only the adapter at the end.

The core of it:

trainer = SFTTrainer(
    model="Qwen/Qwen3-0.6B",
    args=SFTConfig(output_dir="runs/tickets-lora", learning_rate=2e-4, num_train_epochs=3,
                   per_device_train_batch_size=4, gradient_accumulation_steps=4,
                   max_length=1024, model_init_kwargs={"dtype": torch.bfloat16},
                   eval_strategy="steps", eval_steps=50, report_to="none"),
    train_dataset=data["train"],                  # {"prompt": [...], "completion": [...]}
    eval_dataset=data["validation"],
    peft_config=LoraConfig(r=16, lora_alpha=32, target_modules="all-linear", task_type="CAUSAL_LM"),
)
trainer.train()

Hyperparameters that matter

Setting Starting point Notes
Learning rate 1e-4 to 2e-4 for LoRA Full fine-tuning uses much lower rates (around 1e-5 to 2e-5)
Epochs 1 to 3 More epochs on small data quickly over-fits; watch validation loss
Effective batch size 16 to 64 per_device_batch × grad_accum × GPUs
LoRA rank r 16 Raise for harder tasks or lots of data; lower for tiny datasets
LoRA alpha 2 × r Scales the update; tune together with learning rate
Max length Your p95 example length (from ftkit.prepare) plus headroom Longer costs memory quadratically in attention
Scheduler Cosine with a short warmup  
Packing Off for small datasets; on for many short examples packing=True in SFTConfig combines short examples to save compute

Training steps for planning: with 1,000 examples, batch 4, gradient accumulation 4 and 3 epochs, training_steps(1000, 4, 4, 3) gives 189 optimizer steps.

Reading the curves

Pattern Meaning Action
Train and validation loss both fall, then flatten Healthy Pick the best checkpoint
Train loss keeps falling, validation rises Over-fitting Fewer epochs, more data, lower rank or learning rate
Loss barely moves Learning rate too low, or labels masked incorrectly Check the data and completion masking, raise the learning rate
Loss spikes or becomes NaN Instability Lower the learning rate, check for empty or extremely long examples

Loss alone is not quality. Always finish with Module 6.

Module 5: Other training tools

TRL plus PEFT is the most direct way to see every moving part. Other tools wrap similar techniques with different trade-offs (descriptions are ours; check each project for current features and supported models):

Tool What it is Pick it when
TRL + PEFT Hugging Face’s trainers (SFT, DPO, GRPO and more) and adapter library You want flexibility, Python control and the reference implementations
Unsloth (docs) Optimized kernels and patches for faster, lower-memory LoRA/QLoRA, with TRL integration You train on a single GPU and want speed and memory savings
Axolotl Config-file driven fine-tuning, multi-GPU friendly You want reproducible YAML configs and scale-out
LLaMA-Factory Unified fine-tuning with a CLI and web UI for many model families You prefer a UI or want to try many methods quickly
MLX-LM Apple’s MLX framework tools, including LoRA fine-tuning on Apple silicon You train on a Mac

Picks: learn with TRL (this course); move to Unsloth for faster single-GPU runs; use Axolotl for configuration-driven, multi-GPU training; use MLX-LM on a Mac.

On Apple silicon, MLX-LM reads the same train.jsonl and valid.jsonl chat files that ftkit.prepare writes:

pip install mlx-lm
mlx_lm.lora --model <hugging face model id> --train --data data/prepared --iters 600
mlx_lm.generate --model <same model id> --adapter-path adapters --prompt "app crashes on launch"

(The PyTorch-native library torchtune is no longer actively maintained according to its repository, so it is not recommended for new projects.)

Module 6: Evaluating the fine-tuned model

A fine-tune is only better if it beats the base model on held-out data that measures what you care about. scripts/evaluate.py generates answers with both the base model and the adapter for every evaluation prompt (greedy decoding for reproducibility), scores them with ftkit/score.py, and saves all outputs for reading.

python scripts/evaluate.py --model Qwen/Qwen3-0.6B --adapter runs/tickets-lora \
    --eval data/sample_eval.jsonl --fields component platform severity

For the ticket task, the scores are:

Score Meaning
valid_json Output contains a parseable JSON object
keys All expected keys are present
exact Share of the categorical fields (component, platform, severity) that match exactly

Remember that data/sample_eval.jsonl deliberately contains one leaked example (Module 2). Remove it before trusting the numbers; the prepare step tells you which one.

Evaluation checklist:

The companion course LLM Evals for Beginners covers test sets, LLM-as-judge and statistics in depth.

Module 7: Preference tuning with DPO

SFT teaches the model to imitate good answers. Preference tuning teaches it to prefer one answer over another, which helps with qualities that are easier to judge than to write: helpfulness, tone, conciseness, avoiding certain mistakes.

DPO (Direct Preference Optimization) trains directly on pairs of answers without a separate reward model:

{"prompt": [{"role": "user", "content": "Turn this bug report into a ticket ...\n\nall my notes are gone!!"}],
 "chosen": [{"role": "assistant", "content": "{\"component\": \"sync\", \"platform\": \"all\", \"severity\": \"critical\", \"summary\": \"User reports all notes missing\"}"}],
 "rejected": [{"role": "assistant", "content": "{\"component\": \"sync\", \"platform\": \"all\", \"severity\": \"low\", \"summary\": \"notes gone\"}"}]}
python scripts/train_dpo.py --model runs/tickets-merged --train data/prefs.jsonl --output runs/tickets-dpo

Guidelines:

For tasks with automatically checkable answers (math, code, strict formats), reinforcement learning methods such as GRPO (introduced in DeepSeekMath) optimize directly against a reward function. TRL provides a GRPOTrainer; it is a natural next step once SFT works.

Module 8: Merge, quantize, export and serve

Option A: serve the adapter directly

Keep the base model and load the adapter at inference time. One base can serve many adapters. With vLLM:

vllm serve <base model id> --enable-lora --lora-modules tickets=runs/tickets-lora
# clients select the adapter by name: {"model": "tickets", ...} on the OpenAI-compatible API

Option B: merge, then convert

Merging bakes the adapter into the weights, producing a normal model folder. Merge into a 16-bit base, even if you trained with QLoRA:

python scripts/merge_adapter.py --model Qwen/Qwen3-0.6B --adapter runs/tickets-lora --output runs/tickets-merged

Convert to GGUF and quantize with llama.cpp for CPU, Apple silicon and edge deployment:

python llama.cpp/convert_hf_to_gguf.py runs/tickets-merged --outfile tickets-f16.gguf --outtype f16
llama.cpp/build/bin/llama-quantize tickets-f16.gguf tickets-q4_k_m.gguf Q4_K_M

llama.cpp also ships convert_lora_to_gguf.py if you prefer to keep the adapter separate in GGUF form.

Run it with Ollama using the included serving/Modelfile (see the Modelfile reference):

ollama create tickets -f serving/Modelfile
ollama run tickets "app crashes when i open settings on android"
Quantization Size vs f16 Quality Use
f16 / bf16 100% Reference GPUs with enough memory
Q8_0 about 50% Very close to f16 When memory allows
Q5_K_M / Q4_K_M roughly 30 to 35% Small loss; Q4_K_M is a popular default Laptops, CPUs, edge
Lower (Q3, Q2) smaller Noticeable loss Only when nothing else fits

Re-run your evaluation after quantizing. Small models and structured-output tasks can be more sensitive to quantization than chatty general use.

Deployment checklist

Troubleshooting

CUDA out of memory. Lower --batch-size and raise --grad-accum to keep the effective batch; lower --max-length; switch to --qlora; make sure gradient checkpointing is on (it is the default in SFTConfig).

bf16 is not supported on this device. Older GPUs lack bfloat16: run with --no-bf16 (uses float16).

The model repeats the question or rambles. Train on completions only (the script’s prompt-completion conversion does this), and check that the end-of-turn token is part of the template so generation stops.

Great validation loss, poor real outputs. Loss measures imitation of your data, not task success. Check the evaluation metrics, read outputs, and look for template mismatches between training and inference.

The fine-tuned model forgot general skills. Lower the learning rate or epochs, use a smaller rank, or mix some general instruction data into training.

Outputs differ between Transformers and Ollama or llama.cpp. Usually a chat template or sampling settings difference. Compare the exact prompt strings, and use temperature 0 to compare.

ValueError: unrecognized format in ftkit.prepare. The row is not in a supported format; convert it to messages, Alpaca-style or prompt-completion first.

FAQ

How much data do I need to fine-tune an LLM? For a narrow format or extraction task, a few hundred high-quality, diverse examples can be enough with LoRA. Broader behaviour changes need thousands. Quality and coverage matter more than count.

LoRA or full fine-tuning? LoRA for almost everyone: far less memory, small adapters, quality close to full fine-tuning for most adaptation tasks. Consider full fine-tuning for large shifts (new language, heavy domain adaptation) with plenty of compute.

LoRA or QLoRA? QLoRA when memory is the constraint (7B+ models on consumer GPUs). LoRA on a 16-bit base when you have the memory, since it is simpler and faster per step.

Can I fine-tune on a Mac? Yes, for small models: use MLX-LM, or TRL with plain LoRA on the MPS backend. QLoRA with bitsandbytes needs an NVIDIA GPU.

Can I fine-tune on a free cloud notebook? Small models (around 1B to 3B) with LoRA or QLoRA often fit on the free GPUs some notebook services offer; availability and limits change, so check the provider.

Does fine-tuning add knowledge? It can, but unreliably, and the model cannot cite where it learned something. For facts that change or need sources, use RAG; fine-tune for behaviour and format.

What learning rate should I use for LoRA? Start around 2e-4 (1e-4 for larger models or noisy data) with a cosine schedule, and adjust based on validation curves.

How do I stop the fine-tuned model from losing general abilities? Use LoRA with a modest rank, few epochs, a lower learning rate, and mix in general data if needed. Keep a small general regression set in your evaluation.

Should I merge the adapter? Merge for single-purpose deployment and GGUF export. Keep adapters separate when one base serves several tasks (vLLM can switch adapters per request).

Where to go next

Repository layout

llm-course-fine-tuning/
├── ftkit/                     # tested, dependency-free helpers
│   ├── data.py                # convert, validate, scrub, dedupe, split, leakage, length stats
│   ├── prepare.py             # python -m ftkit.prepare CLI
│   ├── lora_math.py           # LoRA parameter counts, memory estimates, step counts
│   └── score.py               # JSON field scoring for evaluation
├── scripts/                   # need GPU libraries; compiled but not executed in tests
│   ├── train_sft.py           # SFT with LoRA or QLoRA (TRL)
│   ├── train_dpo.py           # DPO preference tuning (TRL)
│   ├── evaluate.py            # base vs tuned comparison
│   └── merge_adapter.py       # merge LoRA into the base model
├── serving/Modelfile          # Ollama example
├── data/sample_raw.jsonl      # 25 messy rows (mixed formats, duplicates, PII, invalid rows)
├── data/sample_eval.jsonl     # 3 eval rows, one deliberately leaked
├── tests/test_ftkit.py        # 15 tests
├── LICENSE
└── README.md

Contributing

Pull requests are welcome: worked examples for other tasks, results tables from real runs (with hardware, versions and settings), scripts for other trainers, and corrections when library APIs change. Please pin and state the library versions you used, keep ftkit dependency-free with tests, and verify every link and command.

License

MIT.

If this course helped you ship your first fine-tune, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.