Fine-Tuning LLMs with LoRA and QLoRA: A Developer’s Guide

Full fine-tuning of a large language model is a data-center job: every weight in the network gets updated, which means you need enough GPU memory to hold the weights, the gradients, and the optimizer state, all in full precision. A 7B model already asks for more than 60 GB of VRAM just to train this way. LoRA and QLoRA changed the math. They make it possible to adapt a capable open model to your task on a single GPU by training a tiny fraction of the parameters while leaving the base model frozen. This guide explains how both methods actually work, where they break down, and how to use them well.

Why fine-tuning needs a cheaper path

A pre-trained LLM is a generalist. Fine-tuning teaches it a specialty: your support tone, your codebase conventions, a domain-specific format like JSON function calls. The classic approach, full fine-tuning, updates every parameter of the model. That works, but the cost scales badly:

  • Memory: the weights, gradients, and Adam optimizer states each consume memory. In mixed precision, training a 7B model needs roughly 56 to 60+ GB of VRAM.
  • Storage: every fine-tuned copy is a full copy of the model. Ten task variants of a 70B model means ten 140 GB files.
  • Forgetting: large updates can degrade the general capabilities the base model learned during pre-training, a phenomenon called catastrophic forgetting.

Parameter-efficient fine-tuning (PEFT) asks a different question: what if you don’t need to move all the weights, just nudge the model’s behavior along a few important directions? LoRA is the most widely used answer to that question, and QLoRA extends it to hardware most developers actually own.

How LoRA works: low-rank adapters

LoRA, introduced by Hu et al. in 2021 (“LoRA: Low-Rank Adaptation of Large Language Models”), starts from a simple observation. A weight update during fine-tuning is a large matrix, say 4096 x 4096. But the useful part of that update, the change that actually adapts the model to your task, tends to live in a much smaller subspace. LoRA approximates the update with two small matrices multiplied together.

For a frozen pre-trained weight matrix W (shape d x k), LoRA represents the adapted weight as:

W' = W + (alpha / r) * B @ A

where A is an r x k matrix, B is a d x r matrix, and r is the rank, a small number like 8, 16, or 64. During training, W stays frozen and only A and B receive gradient updates. B is initialized to zeros and A to small random values, so at the start of training the adapter contributes nothing and the model behaves exactly like the base model.

The parameter savings are dramatic. For a 4096 x 4096 attention projection, full fine-tuning updates about 16.8 million parameters. A rank-16 LoRA adapter trains 4096 x 16 + 16 x 4096, roughly 131,000 parameters, about 0.8% of the full matrix. Across the whole model, the LoRA paper reports reducing trainable parameters by up to 10,000x for GPT-3 175B. Because the optimizer state only covers the adapter parameters, memory drops steeply too.

After training, you can merge B @ A back into W with a single matrix addition, which means LoRA adds zero latency at inference time. Or you can keep the adapter separate and swap it in and out, letting one base model serve many tasks by loading different lightweight adapters.

Which layers get adapters

In a transformer, LoRA is usually applied to the attention projections, most commonly the query and value matrices (q_proj, v_proj). Many practitioners also adapt the key and output projections (k_proj, o_proj), and some adapt the MLP layers as well. Adapting more layers increases the parameter count but also the adapter’s capacity to change behavior. A common starting point is the attention projections only; add the MLP blocks if the task needs bigger behavioral shifts and you have the VRAM headroom.

Rank and alpha: the two knobs that matter

  • Rank (r): the inner dimension of A and B. Higher rank means more capacity but more parameters and memory. r=8 or 16 is enough for simple style or format adaptation; r=32 to 64 suits harder tasks with substantial new knowledge. Going beyond 64 rarely helps for most instruction-tuning workloads.
  • Alpha: a scaling factor. The update is multiplied by alpha / r, which keeps the effective step size stable as you change rank. A common convention is to set alpha to 2x the rank (e.g., r=16, alpha=32), though equal-to-rank also works. Treat the alpha/r ratio as part of your learning-rate tuning.

How QLoRA works: LoRA on a 4-bit model

LoRA cuts the trainable parameters, but the frozen base weights still sit in memory at 16-bit precision. A 7B model in FP16 needs about 14 GB just for the weights, plus the activations and the LoRA adapter state. QLoRA, introduced by Dettmers et al. in 2023 (“QLoRA: Efficient Finetuning of Quantized LLMs”), attacks that remaining memory by quantizing the frozen weights to 4 bits, then training LoRA adapters on top.

QLoRA’s design has three parts:

  1. 4-bit NormalFloat (NF4) quantization. Model weights are roughly normally distributed, so NF4 is a data type whose quantization bins are spaced to match a normal distribution, squeezing more information into 4 bits than a uniform layout would. This is where the bulk of the memory savings comes from: a 7B model drops from ~14 GB to roughly 3.5 to 4 GB for its frozen weights.

  2. Double quantization. The quantization itself needs per-block constants (scale factors), and storing those constants in 32-bit float would eat back a meaningful chunk of the savings. QLoRA quantizes the constants too, down to 8-bit, which recovers roughly 0.37 bits per parameter.

  3. Paged optimizers. Memory spikes, for example when a long sequence temporarily inflates the activation memory, can crash training with an out-of-memory error. QLoRA uses NVIDIA’s unified memory paging to spill optimizer state to CPU RAM during spikes instead of crashing.

The practical result, as reported in the QLoRA paper, is that a 65B parameter model can be fine-tuned on a single 48 GB GPU, and a 7B model fits on a 24 GB card like an RTX 4090, or even a 16 GB card with careful settings. The adapters themselves are trained in 16-bit (typically bfloat16) even though the base weights are 4-bit: during the forward and backward passes, the frozen weights are dequantized to 16-bit on the fly, one layer at a time, so the computation stays accurate.

Does 4-bit quantization hurt quality?

There is a small accuracy cost, but the QLoRA paper’s experiments found that 16-bit LoRA and 4-bit QLoRA perform comparably on the benchmarks they tested, with NF4 plus double quantization closing most of the gap versus naive 4-bit schemes. The honest way to think about it: quantization noise is a regularization-like pressure on the frozen base, and the adapters learn around it. For most practical tasks, the difference between LoRA and QLoRA is smaller than the difference between a good and bad training dataset.

LoRA vs QLoRA vs full fine-tuning

Full fine-tuning LoRA (16-bit base) QLoRA (4-bit base)
Trainable parameters All (~100%) ~0.1-1% ~0.1-1%
7B model VRAM needed 56-60+ GB ~24 GB ~10-16 GB
Inference latency Baseline Same after merge Same after merge
Checkpoint size per task Full model Megabytes (adapter only) Megabytes (adapter only)
Behavior change ceiling Highest High High, slightly below LoRA

Choose full fine-tuning when you are training at scale with serious hardware and need maximum behavioral change, for example continued pre-training on a large domain corpus. Choose LoRA when you have a 24 GB+ card and want the cleanest setup. Choose QLoRA when VRAM is the binding constraint, which for most individual developers it is.

A minimal QLoRA training setup

The Hugging Face peft and transformers libraries plus bitsandbytes make this a short script. The pattern below is the standard one; adjust model, dataset, and hyperparameters to your case. If even that script feels heavy, Unsloth wraps the same workflow with lower memory overhead, as our walkthrough on how to fine-tune a small language model shows.

from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training

bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",          # NormalFloat4, QLoRA's quantization
    bnb_4bit_compute_dtype="bfloat16",  # compute stays in 16-bit
    bnb_4bit_use_double_quant=True,     # quantize the constants too
)

model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-3.1-8B",  # any causal LM works; needs gated-repo access
    quantization_config=bnb_config,
    device_map="auto",
)
model = prepare_model_for_kbit_training(model)

lora_config = LoraConfig(
    r=16,
    lora_alpha=32,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
    lora_dropout=0.05,
    bias="none",
    task_type="CAUSAL_LM",
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()  # expect well under 1% of total

print_trainable_parameters() is worth running every time. If it reports more than a couple percent trainable, something is misconfigured, usually a target module name that does not match the model’s architecture.

For the training loop itself, the trl library’s SFTTrainer (or its newer GRPOTrainer/DPOTrainer for preference tuning) wraps the standard Hugging Face Trainer with the right defaults for instruction fine-tuning. A reasonable starting point for hyperparameters on a 7-8B model: learning rate 2e-4 with a cosine schedule, 3 epochs, per-device batch size 1-4 with gradient accumulation to reach an effective batch of 16-32, and a warmup ratio of 0.03.

Practical pointers that actually matter

Your dataset matters more than your rank. LoRA and QLoRA cannot fix a bad dataset. A few hundred to a few thousand high-quality examples in a consistent format beat ten thousand noisy ones. Format each example as the full prompt plus the exact desired response, in the same chat template the base model expects. When real examples run short, many teams bootstrap with synthetic data generated by a larger model and then filter aggressively for quality.

Evaluate on a held-out set, not on vibes. Keep 5-10% of your data aside and check the model’s outputs on it after training. Watch for two failure modes: the model parroting training examples verbatim (overfitting, lower the learning rate or the epochs) and the model losing general abilities it had before (catastrophic forgetting, usually a sign the learning rate is too high or the dataset is too narrow).

Merge for production, keep adapters for experimentation. model.merge_and_unload() folds the adapter into the base weights for a single deployable file with no inference overhead. But merging is one-way; keep the adapter checkpoint if you plan to iterate. If you serve multiple tasks from one model, skip merging and load adapters dynamically instead. For quick local sanity checks of a merged model, desktop runners are plenty, and our comparison of Ollama, LM Studio, and llama.cpp covers which fits where.

Mind the base model’s license and chat template. Some weights (Llama, for example) require accepting a license on Hugging Face before download, and every instruct model has a specific chat template. Training with the wrong template teaches the model a format it will never see at inference time, which silently tanks quality.

QLoRA is not the ceiling. The same adapter idea keeps evolving: DoRA decomposes updates into magnitude and direction components, and AdaLoRA allocates rank adaptively across layers. They are worth knowing about, but plain LoRA/QLoRA remains the default that most tooling and tutorials assume, which is a real advantage when you need community support.

The bottom line

LoRA shrinks fine-tuning to a small set of trainable adapter matrices while the base model stays frozen, and QLoRA adds 4-bit quantization so the whole thing fits on consumer hardware. Together they moved LLM fine-tuning from cluster-scale infrastructure to something a developer can run overnight on a single GPU. The mechanics are simple enough to reason about, the tooling is mature, and the main failure modes come from data and hyperparameters, not from the method itself. Start with QLoRA on a 7-8B model, a clean dataset, and conservative hyperparameters, then scale up only when the results tell you to.

Sources: Hu et al., “LoRA: Low-Rank Adaptation of Large Language Models” (2021); Dettmers et al., “QLoRA: Efficient Finetuning of Quantized LLMs” (2023). VRAM figures are approximate and vary with sequence length, batch size, and framework.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.