Skip to content
AgenticAIWiki
  1. Learn
  2. Part 5
  3. 29. Fine-tuning
  4. 29.9

Lesson 29.9 · 9 of 9 · 7 min read · Reviewed 24 Nov 2026

QLoRA training with TRL and Unsloth

By the end, you can

  • Describe the steps of a QLoRA training run with common open-source libraries.
  • Choose batch, accumulation and epoch settings and work out how many optimiser steps they give.

The shape of a run

QLoRA (29.3) keeps a frozen base model in 4-bit and trains small LoRALoRA: Low-rank adaptation: fine-tuning a small set of added weights instead of the whole model. adapters on top. A training run has the same five stages whichever library you use:

  1. Load the base model in 4-bit, with its tokenizerTokenizer: The component that splits text into tokens and maps each token to an id the model can process. and chat template (29.8).
  2. Attach LoRA adapters to chosen layers.
  3. Prepare the data: messages JSONL, split into train, validation and test (29.2).
  4. Train with a trainer that handles batching, loss masking and checkpoints.
  5. Save the adapter, evaluate it (29.5), then serve it on the base or merge it in.

The libraries, by job

Job Common choice What it does
4-bit loading bitsandbytes Stores base weights in a 4-bit format (NF4 in the QLoRA paper)
Adapters PEFT Adds and saves LoRA matrices
Training loop TRL Supervised, preference and other trainers for language models
All of the above, faster Unsloth Wraps loading, adapters and training with optimised kernels to cut memory and time

These are examples; other stacks such as Axolotl or cloud training services cover the same steps. Library APIs change often, so treat the code below as a sketch and check the current docs.

A sketch with TRL and PEFT

from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer

bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4")
model = AutoModelForCausalLM.from_pretrained(BASE_ID, quantization_config=bnb)
tok = AutoTokenizer.from_pretrained(BASE_ID)

lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
                  target_modules=["q_proj", "v_proj"], task_type="CAUSAL_LM")
args = SFTConfig(output_dir="out", per_device_train_batch_size=4,
                 gradient_accumulation_steps=4, num_train_epochs=3,
                 learning_rate=2e-4, gradient_checkpointing=True)

trainer = SFTTrainer(model=model, args=args, train_dataset=train, eval_dataset=valid,
                     processing_class=tok, peft_config=lora)
trainer.train()
trainer.save_model("out/adapter")

With Unsloth the stages are the same: load the model through its own loader with 4-bit switched on, call its helper to add LoRA adapters, then pass the model to a TRL trainer.

Work out the steps

The trainer counts optimiser steps, one per effective batch.

examples          2,000
per-device batch  4      gradient accumulation 4  ->  effective batch 16
steps per epoch   2,000 / 16 = 125
epochs            3      ->  375 optimiser steps

Gradient accumulation lets a small GPU act like it has a bigger batch: it adds up gradients over several small batches before each update. Gradient checkpointing saves memory by recomputing some activations, at the cost of slower steps.

What to watch while it trains

Signal Healthy Worrying
Training loss Falls, then flattens Drops to near zero: memorising
Validation loss Falls, then flattens Rises while training loss falls: overfitting
Sample outputs Improve on held-out prompts Repeats, never stops (check end tokens)
GPU memory Stable Out of memory: lower batch or sequence length, raise accumulation

Save checkpoints, pick the one with the best validation result, and only then run the test set and safety checks (29.5).

Common mistakes

  • Comparing runs with different effective batch sizes and calling the difference a data effect.
  • Setting a long maximum sequence length “to be safe”: memory grows with it.
  • Shipping the last checkpoint instead of the best one.
  • Forgetting that the adapter only works with the exact base model it was trained on.

Key points

  • A QLoRA run loads the base in 4-bit, attaches LoRA adapters, trains them on formatted chat data, then saves the small adapter.
  • Hugging Face TRL provides the trainer, PEFT the adapters and bitsandbytes the 4-bit loading; Unsloth wraps the same steps with faster, leaner kernels.
  • Effective batch = per-device batch x gradient accumulation; optimiser steps = examples / effective batch x epochs.
  • Watch validation loss and your own eval, not training loss alone; stop before the model overfits.
Hands-on labOn your own machine

Train a QLoRA adapter on one GPU

Run a small QLoRA fine-tune end to end on a real GPU with an open-source stack, and compare the adapter with the base model on held-out prompts.

You will have: A saved LoRA adapter, a training log with training and validation loss, and a short table comparing base and tuned outputs on ten held-out prompts.

Steps

  1. On a machine with a CUDA GPU (or a hosted notebook), create a virtual environment and install TRL, PEFT, bitsandbytes and transformers, or Unsloth, following their install pages. If the model download needs a hub token, keep it in an environment variable, never in code.
  2. Prepare 200 to 500 examples as messages JSONL with train and validation splits (29.2), and confirm the tokenizer's chat template renders them correctly (29.8).
  3. Load a small instruct model (1B to 8B) in 4-bit, attach LoRA adapters with rank 16 on the attention projections, and set batch, accumulation and epochs; write down the optimiser step count before you start.
  4. Train, logging training and validation loss; keep the checkpoint with the best validation loss.
  5. Run the same ten held-out prompts through the base and tuned models and record both outputs side by side.
  6. Save the adapter and note the exact base model id it requires.

Done when

  • The run finishes without running out of memory and the step count matches your calculation.
  • Validation loss falls, then flattens, and you saved the best checkpoint rather than the last.
  • At least seven of the ten held-out prompts are judged better or equal with the adapter, and the adapter file is in megabytes.

Docs: TRL documentation (Hugging Face) · PEFT documentation (Hugging Face) · Unsloth documentation

Quick checkYou have 3,200 training examples, a per-device batch of 4, gradient accumulation of 8 and 2 epochs on one GPU. How many optimiser steps will the run take?
stepsCounts if within ±10%. You can type 1.2k, 3M or 2.5e6.
How sure are you?
Enter a number and how sure you are

Finished the chapter? Take the chapter check.