HSR Sector 6 · Bangalore +91 96110 27980 Mon–Sat · 09:30–20:30
Chapter 20 of 25 — Generative AI Fundamentals
advanced Chapter 20 of 25

Fine-Tuning LLMs: Full Fine-Tuning, LoRA, QLoRA and PEFT

By Vikas Swami, CCIE #22239 | Updated Mar 2026 | Free Course

What is fine tuning in LLMs?

Fine tuning is additional training that starts from a pretrained large language model and adapts it to a task, domain, or output convention. Full fine tuning lets the optimizer update the whole model, while parameter-efficient fine tuning (PEFT) trains a much smaller set of parameters. LoRA learns low-rank weight updates, and QLoRA trains those updates on top of a quantized, frozen base model.

Suppose an IT support team wants a model to classify incoming tickets into a fixed set of queues. A general-purpose model may understand that a VPN problem concerns networking but produce a label such as “Connectivity” when the routing system expects NETWORK. Fine tuning can make the expected taxonomy and output format more likely by training on examples of tickets paired with the correct routing decisions.

That improvement comes from changing learned parameters. Prompt engineering changes the input the model sees on each request, and retrieval adds relevant evidence to that input. Neither requires changing the model weights. Start with a prompt baseline: if instructions, examples, and output validation already meet your target, training creates an extra artifact to test, deploy, and maintain.

How does LLM fine tuning differ from pretraining?

In pretraining, a decoder-only language model typically learns to predict the next token across a broad corpus. The target token comes from the sequence itself, so the objective is self-supervised and does not require human-written labels. Continued pretraining can use the same objective on domain text, such as internal product documentation, to adapt the model to the language used in that domain.

Training stageTypical dataSource of supervisionWhat it teaches
Initial pretrainingBroad text and code corporaNext tokens from the corpusGeneral language, code, and knowledge patterns
Continued pretrainingRaw domain or organisation textNext tokens from the domain corpusDomain vocabulary and recurring patterns
Supervised fine tuning (SFT)Inputs paired with reference outputsTarget tokens in the reference outputsTask behaviour, output format, and response conventions

Instruction tuning commonly uses SFT with examples written as instructions and desired responses. It describes how the training examples are framed, not which weights are trainable. You can instruction-tune with full updates or LoRA. For ticket routing, a reference output might be a single queue label. For summarisation, it might be a reviewed summary that preserves dates and unresolved action items.

For causal SFT, the model predicts each target token from earlier tokens, including the reference answer prefix during training. With response-only supervision, let M be the set of positions whose target tokens count toward the loss. The objective is L = -(1 / |M|) sum_{t in M} log p(y_t | y_<t). Prompt tokens remain visible to the model even when their targets are excluded from the loss. This distinction matters: a loss mask controls what is scored, while an attention mask controls which positions can be attended to.

A smaller task dataset usually means fewer training steps than initial pretraining, but it does not make each step cheap. Model size, sequence length, effective batch size, and the update method all affect memory and runtime. A short ticket classifier and a long-document summariser can have very different training costs even when their datasets contain the same number of examples.

How does full fine tuning compare with PEFT?

In full fine tuning, the optimizer can update every model parameter, including embeddings, attention and feed-forward weights, and the output head where applicable. This gives the training run the greatest freedom to change the model. It does not guarantee a better result: a small or narrow dataset can produce overfitting or degrade abilities that the base model previously had. Compare methods on the same held-out task data and on examples of capabilities you want to preserve.

Two training paths show full-model weight updates and adapter-only updates on a frozen base.
Full fine tuning updates the base weights, while adapter-based PEFT stores a separate set of trained parameters.

Memory comes from several sources: model weights, gradients, optimizer states, and intermediate activations saved for backpropagation. For example, AdamW with two FP32 moment buffers uses 8 bytes of moment storage per trainable scalar, before accounting for weights, gradients, or any FP32 master copy. Freezing a parameter avoids its weight gradient and optimizer state, but the base weights still take up memory. Backpropagation may still traverse frozen layers to deliver gradients to adapters in earlier layers.

MethodWhat trains?Operational trade-off
Full fine tuningThe model parametersHigh update flexibility; usually a separate full checkpoint for each variant
LoRALow-rank matrices on selected projectionsSmall adapter checkpoint; the original base is still required unless the update is merged
QLoRALoRA matrices over a frozen, low-bit baseLower base-weight memory; low-bit kernels and compute dtype matter
Prompt tuningLearned input embeddingsFew trainable parameters; virtual tokens consume input positions
Prefix tuningLearned prefixes supplied to attention layers, typically as key and value vectorsFew trainable parameters; prefix positions add attention work
Bottleneck adaptersSmall inserted modules, often with a nonlinear bottleneckSeparate adapter weights; extra layers remain in the forward path

PEFT is the family of methods; peft is also the name of a Python library that implements several of them. The family is useful when you want one shared base plus separate versions for different tasks, such as ticket routing and handover summarisation. Training fewer parameters reduces optimizer work and checkpoint size. It can improve training speed, but actual throughput still depends on sequence length, batch shape, kernels, and hardware.

How does LoRA work? A worked numeric example

Consider a bias-free linear layer y = Wx with a frozen weight W of shape d_out × d_in. LoRA adds two matrices: A of shape r × d_in and B of shape d_out × r. For standard LoRA scaling, s = alpha / r, and the forward pass becomes y = Wx + sB(Ax). The update sBA has rank at most r. The full effective weight W + sBA can still have high rank.

A LoRA diagram shows a frozen linear path and a scaled two-matrix adapter path whose outputs are added.
LoRA trains a low-rank correction while leaving the original weight matrix unchanged.

For a numerical example, take W = [[1, 0], [0, 2]], A = [[1, -1]], B = [[2], [1]], and x = [3, 1], with r = 1 and alpha = 1. Use column-vector convention. These represent adapter values after an imagined training step:

  1. The frozen path gives Wx = [3, 2].
  2. The adapter compresses the input to Ax = [3 - 1] = [2].
  3. It projects back to B(Ax) = [4, 2]. Scaling is 1, so the two paths sum to [7, 4].
  4. Multiplying the matrices first gives W + BA = [[3, -2], [1, 1]]. Applying this merged weight to the same input also gives [7, 4].

The small example illustrates the calculation; the savings show up in wider layers. For a single 4096 × 4096 projection, updating the dense weight trains 16,777,216 scalars. Rank 8 LoRA trains 8 × (4096 + 4096) = 65,536 scalars, about 0.39% of that projection's dense parameter count. This is a per-layer ratio. The complete model's trainable count depends on which projections you target and whether you also train biases, embeddings, or output heads.

A common initialisation uses random values for A and zeros for B. The initial update is zero. On the first backward pass, B can receive a gradient because Ax can be nonzero; the gradient to A through that path is initially zero because it contains a factor of B. Rank controls update capacity, while the target modules determine where updates can act. For example, LoRA on query and value projections changes how a Transformer forms queries and value vectors; targeting feed-forward projections gives it another route to adapt. Compare target sets on validation examples instead of assuming that increasing rank will fix every failure.

What is QLoRA and why does 4-bit training use less memory?

QLoRA stores the frozen base's quantized linear weights in a low-bit format, commonly 4-bit NormalFloat (NF4), while training LoRA adapters. NF4 uses a codebook designed for approximately normally distributed weights. Blockwise quantization uses scale information to represent weights in each block, and double quantization reduces overhead by quantizing those scale constants. During a forward operation, kernels dequantize weight values as needed for computation in a dtype such as BF16. The optimizer updates adapter parameters, not the 4-bit base codes.

As a storage estimate, one billion scalars at 4 bits each occupy 0.5 GB in decimal units, compared with 2 GB at 16 bits. This only counts the packed values. Actual memory includes quantization metadata, weights that stay in higher precision, adapters, optimizer states, activations, and temporary buffers. If training fails with long sequences, reduce sequence length or the per-device microbatch before assuming that another reduction in adapter rank will solve the problem. Gradient accumulation can recover a larger effective batch, and activation checkpointing trades recomputation for lower activation memory.

At deployment, you can serve the adapter with a compatible quantized base. If you need a standalone weight file, a typical approach is to load the original base at a supported higher precision, apply and merge the trained update, then quantize the merged model if needed. Quantization and addition do not generally commute. Test the final served artifact because merging and requantizing can change predictions relative to the training configuration.

How do you train a QLoRA adapter in Python?

This smoke test uses PyTorch, Transformers, PEFT, bitsandbytes, and Accelerate in a CUDA environment that supports bitsandbytes 4-bit operations and BF16. It teaches a small chat model to emit a queue label. The chat template formats the prompt and the reference answer consistently, and the loss covers the assistant completion, including its turn terminator. Four examples and one optimizer step verify the data flow; they do not establish routing quality.

import torch
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from transformers import (
    AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig,
)

torch.manual_seed(7)
base_id = "Qwen/Qwen2.5-0.5B-Instruct"
tok = AutoTokenizer.from_pretrained(base_id)
quant = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_use_double_quant=True,
    bnb_4bit_compute_dtype=torch.bfloat16,
)
base = AutoModelForCausalLM.from_pretrained(
    base_id, quantization_config=quant,
    dtype=torch.bfloat16, device_map={"": 0},
)
base.config.use_cache = False
base = prepare_model_for_kbit_training(
    base, use_gradient_checkpointing=False
)
model = get_peft_model(base, LoraConfig(
    task_type="CAUSAL_LM", r=8, lora_alpha=16,
    target_modules=["q_proj", "v_proj"], bias="none",
))
model.print_trainable_parameters()

def encode(ticket, queue):
    messages = [{
        "role": "user",
        "content": (
            "Return exactly one queue: ACCESS, NETWORK, or HARDWARE.\n"
            f"Ticket: {ticket}"
        ),
    }]
    prefix = tok.apply_chat_template(
        messages, tokenize=True, add_generation_prompt=True
    )
    ids = tok.apply_chat_template(
        messages + [{"role": "assistant", "content": queue}],
        tokenize=True, add_generation_prompt=False,
    )
    assert ids[:len(prefix)] == prefix
    assert len(ids) > len(prefix)
    return ids, [-100] * len(prefix) + ids[len(prefix):]

rows = [
    ("VPN connects but internal hosts do not resolve.", "NETWORK"),
    ("My password reset link has expired.", "ACCESS"),
    ("The laptop battery no longer charges.", "HARDWARE"),
    ("My account is locked after several attempts.", "ACCESS"),
]
items = [encode(*row) for row in rows]
width = max(len(ids) for ids, _ in items)
inputs, masks, labels = [], [], []

for ids, target in items:
    pad = width - len(ids)
    inputs.append(ids + [tok.pad_token_id] * pad)
    masks.append([1] * len(ids) + [0] * pad)
    labels.append(target + [-100] * pad)

device = torch.device("cuda:0")
batch = {
    name: torch.tensor(values, dtype=torch.long, device=device)
    for name, values in (
        ("input_ids", inputs), ("attention_mask", masks), ("labels", labels)
    )
}
opt = torch.optim.AdamW(
    (p for p in model.parameters() if p.requires_grad), lr=2e-4
)
model.train()
opt.zero_grad(set_to_none=True)
loss = model(**batch).loss
loss.backward()
opt.step()
print(f"Training batch loss: {loss.item():.4f}")
model.save_pretrained("ticket-router-adapter")
tok.save_pretrained("ticket-router-adapter")

The causal model shifts logits and labels internally, so the logit at the final prompt position predicts the first completion token. The value -100 excludes prompt and padding targets from the loss. Do not infer the prompt boundary from character counts: tokenization can change around string boundaries, and chat templates vary across models. The prefix assertion catches a template or tokenisation mismatch rather than silently teaching the wrong target span.

The saved directory contains the adapter and tokenizer files rather than a complete copy of the base model. Record the base model revision, library versions, quantization settings, and chat template alongside it. When you turn this example into a training run, track validation loss and evaluate generated outputs with the same template, stopping rules, and parsing logic that your application will use.

When should you use fine tuning, prompting, or RAG?

Choose based on the failure you can reproduce. If correct evidence is already in the prompt but the model repeatedly chooses the wrong queue or ignores a response convention, improve the prompt and output controls first, then test supervised fine tuning. If the answer depends on the latest access policy, a versioned retrieval-augmented generation (RAG) system can supply the current policy at request time. Fine tuning can help the model follow a citation format, but it does not provide a reliable lookup mechanism for changing facts.

  • Start with LoRA when a capable base already handles the task reasonably well and you need consistent labels, terminology, or style. Use QLoRA when base-weight memory prevents a practical run at higher precision.
  • Compare full fine tuning when a representative dataset, a compute budget, and validation evidence suggest a capacity bottleneck. Before making that jump, check label quality, model choice, adapter targets, and rank.
  • Use retrieval or tools for current facts such as policy revisions, stock counts, or live ticket status. If retrieval is failing, measure whether it found the source before training the generator to compensate.
  • Combine the methods when a workflow needs both current evidence and stable behaviour. Retrieve the current support policy, then use a tuned model to produce the expected fields, cite evidence, or abstain when information is missing.

Build an evaluation split before training. Keep duplicates, paraphrases, and tickets from the same incident on the same side of the split; use a time-based split if you need to simulate future traffic. For routing, report exact output validity, per-class precision and recall, macro F1, and a confusion matrix. A small adapter can appear successful because it handles the common queue while silently sending rare cases to the wrong team. Compare against the base model under the same decoding settings, review the costliest errors, and keep sensitive fields out of training records unless their use is authorised. The LLM evaluation and safety chapter explains how to extend these checks beyond a single task score.

Key Takeaways

  • Fine tuning starts from pretrained weights. The training objective, dataset format, and choice of trainable parameters are separate decisions.
  • Full fine tuning offers the most update flexibility but needs more optimizer memory and can degrade existing abilities.
  • LoRA learns a scaled low-rank correction to selected weights. The base weights stay frozen.
  • QLoRA reduces base-weight storage using quantization while training adapters with higher-precision computation.
  • Prompt and padding masks need separate treatment. Mask prompt labels while preserving the prompt as model context.
  • Use retrieval for current evidence and fine tuning for repeatable behaviour. Measure both on held-out examples before deploying.

Frequently Asked Questions

How many examples do I need for LLM fine tuning?

There is no universal minimum. A narrow formatting task may need far fewer examples than a task with ambiguous labels and many edge cases. Start with a reviewed training set and an independent validation set. Plot task performance as you add examples, and prioritise gaps revealed by errors, such as missing examples near the boundary between two queues.

Is QLoRA always slower than LoRA?

No. Low-bit computation introduces dequantization work, but smaller base weights can reduce memory traffic or let you fit a larger microbatch. The result depends on the GPU, kernels, sequence lengths, and batch size. Compare end-to-end training throughput at the same sequence length and effective batch size, then check whether both runs achieve comparable validation quality.

Can I merge a LoRA adapter into the base model?

Yes. For supported linear layers, merging adds the scaled product of the learned matrices to the corresponding base weights. This removes the separate adapter branch from inference, which is useful when serving a single variant. Keep an unmerged copy if you need to switch adapters, and test outputs again if the merged model is quantized.

Does increasing LoRA rank always improve accuracy?

No. Higher rank allows a wider range of weight updates, but it adds trainable parameters and can overfit weak or limited data. Try several ranks with the same target modules and a comparable training setup. If the main failure is incorrect labels, missing facts, or poor coverage of rare cases, raising rank does not address the underlying problem.

Can fine tuning teach a model new facts?

Training can change the facts a model tends to produce, but it offers no reliable way to verify that a specific fact was learned, stayed current, or can be cited. For policies, prices, and product specifications, retrieve the answer from an authoritative source at request time. Fine tuning can help the model use that evidence consistently and abstain when it is insufficient.

Ready to Master Generative AI Fundamentals?

Join 45,000+ students at Networkers Home. CCIE-certified trainers, 24x7 real lab access, and Placement Guarantee* — structured interview support until placed.

Explore Course