🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10
AI Engineering16 min read

LLM Fine-Tuning: LoRA, QLoRA, and Full Fine-Tuning Compared

C
ChatWhole AI Team|2026-09-03

LLM Fine-Tuning: LoRA, QLoRA, and Full Fine-Tuning Compared

Fine-tuning large language models has become more accessible with techniques like LoRA and QLoRA, but choosing the right approach depends on your budget, dataset size, and performance requirements. This guide compares all major fine-tuning approaches with practical implementation code.

The Fine-Tuning Spectrum

Sponsored

The spectrum is really a question about how much of the model you are willing to move. Full fine-tuning updates every weight, which maximises the degrees of freedom available to the optimiser and maximises the memory bill: for an 8B model, weights plus Adam moments plus gradients land near 56 bytes per parameter in mixed precision, so 8B parameters needs roughly 450 GB before activations — the reason four 80 GB accelerators are the stated minimum. Parameter-efficient methods freeze those weights and train a small number of new ones, which cuts the optimiser state proportionally and limits what the method can express.

A useful mental model: the trainable fraction tells you what kind of change is possible. Adding a domain vocabulary and a new output format needs very little movement and suits LoRA at rank 8 to 16. Reshaping reasoning behaviour on a narrow domain needs more, and may need rank 32 or full updates. Choose from the evaluation failure you are fixing, not from the paper you last read.

Architecture Diagram
Full Fine-Tuning ←→ Parameter-Efficient Fine-Tuning (PEFT)
     ↓                        ↓
Most expensive,            Cheapest, fastest
best quality               good quality

Full Fine-Tuning

Updates all model parameters. Requires the most resources but achieves the best results. It is also the option that can teach behaviour the base model never demonstrated — a new output schema, a language it barely saw in pretraining, a domain where the vocabulary is absent — because every layer participates rather than a handful of low-rank deltas. The cost is not only hardware: full runs overwrite the base checkpoint, so you now maintain a divergent lineage and must re-evaluate everything the base model used to do well. Keep the original weights, keep the data snapshot id, and run the same evaluation suite against both before promoting.

python
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    TrainingArguments,
    Trainer
)

# Load base model
model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-3.1-8B",
    torch_dtype=torch.bfloat16,
    device_map="auto"
)

# Training configuration
training_args = TrainingArguments(
    output_dir="./output",
    num_train_epochs=3,
    per_device_train_batch_size=4,
    gradient_accumulation_steps=8,
    learning_rate=2e-5,
    weight_decay=0.01,
    warmup_ratio=0.03,
    lr_scheduler_type="cosine",
    fp16=True,
    logging_steps=10,
    save_strategy="epoch",
)

# Train
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=dataset,
    tokenizer=tokenizer,
)
trainer.train()

Requirements

  • GPU: 4x A100 80GB (for 8B model)
  • RAM: 128GB+
  • Storage: 500GB+ (model checkpoints)
  • Cost: ~$50-100/hour
  • Time: 4-24 hours depending on dataset

LoRA (Low-Rank Adaptation)

Freezes the original model and trains small rank-decomposition matrices. Reduces trainable parameters by 90%+.

The arithmetic behind that percentage is worth doing once. A 4096 by 4096 projection holds 16.7M parameters; at rank 16 the adapter trains 16 × (4096 + 4096) = 131,072, which is 0.78 percent of the matrix, and only the adapter's moments live in optimizer memory. Because the delta is additive at inference, one base model can carry many adapters and switch between them per request — the pattern behind per-tenant personalization. Rank is the capacity dial: doubling r roughly doubles trainable parameters and the adapter file, and in practice quality plateaus between 16 and 32 for most instruction-tuning data. lora_alpha sets the scale of the delta relative to r; keeping alpha at twice r keeps the effective learning rate stable when you change rank.

python
from peft import LoraConfig, get_peft_model, TaskType

# Configure LoRA
lora_config = LoraConfig(
    task_type=TaskType.CAUSAL_LM,
    r=16,                    # Rank (higher = more capacity)
    lora_alpha=32,           # Scaling factor
    lora_dropout=0.1,        # Dropout for regularization
    target_modules=[         # Which layers to adapt
        "q_proj", "k_proj", "v_proj", "o_proj",
        "gate_proj", "up_proj", "down_proj"
    ],
    bias="none",
)

# Apply LoRA to model
model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-3.1-8B",
    torch_dtype=torch.bfloat16,
    device_map="auto"
)

model = get_peft_model(model, lora_config)

# Print trainable parameters
model.print_trainable_parameters()
# Output: trainable params: 41,943,040 || all params: 8,071,319,552 || 0.52%

# Train (same as before, but much faster and cheaper)
trainer = Trainer(model=model, args=training_args, ...)
trainer.train()

# Save only the LoRA weights (~100MB instead of 16GB)
model.save_pretrained("./lora_weights")

# Load for inference
from peft import PeftModel
base_model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B")
model = PeftModel.from_pretrained(base_model, "./lora_weights")

LoRA Hyperparameters

ParameterRangeEffect
r (rank)4-64Higher = more capacity, more parameters
lora_alpha8-64Scaling factor (usually 2x rank)
lora_dropout0.05-0.2Regularization
target_modulesvariesWhich layers to adapt

QLoRA (Quantized LoRA)

Sponsored

LoRA with 4-bit quantization. Fine-tune 70B models on a single 48GB GPU.

The memory saving comes from three stacked choices rather than from 4-bit alone. NF4 stores each weight in four bits, nested quantization moves the per-group scale to eight bits and recovers roughly 0.4 bits per parameter, and double quantization therefore takes 70B parameters to about 35 GB of weights. Compute stays in bfloat16, so the model is dequantized on the fly for each matmul — which is why training runs about 30 percent slower than 16-bit at the same step count. Gradient checkpointing is not optional here: without it, activations for a 4K sequence at batch 2 will exhaust the card long before the weights do. Quality loss against 16-bit LoRA is typically 0.5 to 1 percent on downstream metrics, and it is measurable, so keep an evaluation set that can see it.

python
from peft import LoraConfig, get_peft_model
from transformers import BitsAndBytesConfig

# 4-bit quantization config
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",           # NormalFloat4 quantization
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_use_double_quant=True,       # Nested quantization
)

# Load quantized model
model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-3.1-70B",
    quantization_config=bnb_config,
    device_map="auto"
)

# Apply LoRA (same as before)
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=TaskType.CAUSAL_LM,
)

model = get_peft_model(model, lora_config)

# Train with gradient checkpointing (saves memory)
training_args = TrainingArguments(
    per_device_train_batch_size=2,
    gradient_accumulation_steps=16,
    gradient_checkpointing=True,  # Critical for QLoRA
    ...
)

QLoRA vs LoRA Performance

MetricLoRA (16-bit)QLoRA (4-bit)Difference
Model qualityBaseline-0.5-1%Negligible
Memory usage32GB12GB62% less
Training speed1x0.7x30% slower
Inference speed1x0.9x10% slower

RLHF (Reinforcement Learning from Human Feedback)

Fine-tune models to align with human preferences.

Three models are in the loop at once: the policy being trained, a frozen reference model that provides the KL anchor, and a reward model trained on human preference pairs. The KL term is the part teams underweight — set init_kl_coef too low and the policy discovers reward hacks such as repeating the preferred phrasing in every answer; set it too high and the update barely moves. A practical starting point is 0.2 with a target KL near 6.0 nats over a rollout, then watch the reward curve and the KL curve together: reward rising while KL also rises means you are still inside the useful region, reward rising with KL flat usually means the reward model is being gamed.

python
from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead

# Load model with value head for PPO
model = AutoModelForCausalLMWithValueHead.from_pretrained(
    "meta-llama/Llama-3.1-8B",
    torch_dtype=torch.bfloat16
)

# PPO configuration
ppo_config = PPOConfig(
    learning_rate=1.4e-5,
    batch_size=64,
    mini_batch_size=16,
    ppo_epochs=4,
    kl_penalty="kl",  # KL divergence penalty
    init_kl_coef=0.2,
    target_kl=6.0,
    gamma=1.0,
    lam=0.95,
    cliprange=0.2,
)

# Reward model
reward_model = AutoModelForCausalLM.from_pretrained(
    "meta-llama/Llama-3.1-8B-reward"
)

# RLHF training loop
ppo_trainer = PPOTrainer(
    config=ppo_config,
    model=model,
    ref_model=None,  # Uses model's own copy
    tokenizer=tokenizer,
)

for batch in dataloader:
    query_tensors = [tokenizer.encode(q) for q in batch['queries']]
    
    # Generate responses
    response_tensors = ppo_trainer.generate(query_tensors)
    
    # Get rewards
    rewards = [reward_model(r) for r in response_tensors]
    
    # PPO update
    stats = ppo_trainer.step(query_tensors, response_tensors, rewards)

DPO (Direct Preference Optimization)

Simpler alternative to RLHF — no reward model needed.

DPO derives its loss from the same preference objective RLHF approximates, but collapses the reward model and the policy update into one expression over chosen and rejected pairs. That removes the most failure-prone component — a reward model that stops reflecting human preference — and replaces it with a requirement for clean pair data. beta is the knob that matters: it controls how far the policy may drift from the reference, with values from 0.05 to 0.2 covering most cases, and higher values behaving like a stronger KL penalty. Train on a preference set of at least a few thousand pairs, split by prompt rather than by row, and evaluate with a held-out pairwise win rate against the base model rather than with training loss, because training loss keeps falling long after win rate has stopped improving.

python
from trl import DPOTrainer, DPOConfig

# DPO training
dpo_config = DPOConfig(
    beta=0.1,                    # KL penalty weight
    loss_type="sigmoid",         # DPO loss variant
    learning_rate=5e-7,
    per_device_train_batch_size=4,
    gradient_accumulation_steps=4,
)

trainer = DPOTrainer(
    model=model,
    ref_model=ref_model,
    args=dpo_config,
    train_dataset=preference_dataset,  # (chosen, rejected) pairs
    tokenizer=tokenizer,
)

trainer.train()

RLHF vs DPO Comparison

AspectRLHFDPO
ComplexityHigh (3 models)Low (2 models)
Training stabilityCan be unstableMore stable
Reward hackingPossibleLess likely
PerformanceSlightly betterVery competitive
Compute costHigherLower

Cost Comparison

Prices below assume on-demand A100 capacity at roughly USD 2 per GPU-hour for the single-GPU rows and USD 2.50 for the multi-GPU rows, so the arithmetic can be checked rather than trusted. LoRA on an 8B model at two hours on one card is about USD 45 to 60, while the same dataset through full fine-tuning across four cards for six hours lands near USD 300 — a fivefold difference that buys single-digit metric gains on most instruction-tuning benchmarks. The row that surprises people is QLoRA on 70B: it fits on one 80 GB card but takes twice as long per step, so it is cheaper than full tuning and more expensive than LoRA on 8B. Include evaluation and at least one failed run in any budget you quote.

MethodGPU RequiredTime (10K examples)Cost
Full Fine-Tuning4x A100 80GB4-8 hours$200-400
LoRA (8B)1x A100 80GB2-4 hours$50-100
QLoRA (8B)1x A100 40GB3-6 hours$30-60
QLoRA (70B)1x A100 80GB8-16 hours$100-200
DPO2x A100 80GB4-8 hours$100-200
RLHF4x A100 80GB12-24 hours$300-600

When to Use Each Method

Advertisement

One decision precedes the four below: whether you need fine-tuning at all. If the failure is that the model does not know your private data, retrieval fixes it faster and keeps the knowledge current, whereas fine-tuning bakes a snapshot into weights that goes stale on the next data drop. If the failure is format — the model knows the answer but will not emit your schema — a few hundred curated examples through LoRA is usually enough. If the failure is genuinely new behaviour, only a fine-tuning run can move it, and you should expect to iterate two or three times before the evaluation set agrees.

Use Full Fine-Tuning when:

  • You have a large dataset (100K+ examples)
  • Maximum quality is critical
  • Budget allows for significant compute
  • You're fine-tuning a small model (<3B parameters)

Use LoRA when:

  • You have a medium dataset (10K-100K examples)
  • You need good quality with lower cost
  • You want to preserve base model capabilities
  • You need to fine-tune for multiple tasks

Use QLoRA when:

  • You have limited GPU budget
  • You're fine-tuning a large model (8B-70B)
  • You want to experiment quickly
  • Training speed is less critical

Use DPO/RLHF when:

  • You want to align model with human preferences
  • You have preference data (chosen/rejected pairs)
  • Safety and alignment are important

Production Deployment

Merging and serving as separate adapters are two different operational choices. Merging produces one ordinary checkpoint: no extra memory at load, no routing logic, but a full redeploy whenever an adapter changes. Serving adapters side by side keeps the base model resident once and swaps deltas per request, which costs a little extra memory and a little latency for the swap, and lets you run a new adapter on 5 percent of traffic without touching the base. The constraint people hit first is that the base model must be identical across adapters — an adapter trained against a different revision will load and then produce silently degraded output, so record the base model revision inside the adapter directory and assert it at load time.

Serving LoRA Models

python
# Option 1: Merge LoRA weights into base model
from peft import PeftModel

base_model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B")
model = PeftModel.from_pretrained(base_model, "./lora_weights")
merged_model = model.merge_and_unload()
merged_model.save_pretrained("./merged_model")

# Option 2: Serve with dynamic LoRA switching
class LoRAServing:
    def __init__(self, base_model):
        self.base_model = base_model
        self.lora_weights = {}  # name -> weights
    
    def load_lora(self, name: str, path: str):
        self.lora_weights[name] = PeftModel.from_pretrained(
            self.base_model, path
        )
    
    def generate(self, prompt: str, adapter: str = None):
        if adapter:
            model = self.lora_weights[adapter]
        else:
            model = self.base_model
        return model.generate(prompt)

Conclusion

The choice of fine-tuning method depends on your specific constraints:

  1. QLoRA is the best starting point for most teams — low cost, good quality
  2. LoRA is ideal for production systems needing multiple adapters
  3. Full fine-tuning is for maximum quality when budget allows
  4. DPO is the simplest way to align with human preferences
  5. RLHF is for cutting-edge alignment when DPO isn't enough

The trend is toward parameter-efficient methods. With LoRA and QLoRA, you can fine-tune state-of-the-art models on a single GPU.

A sequence that works for a first project: confirm the problem is not a retrieval problem, collect 10K examples with a documented provenance, run QLoRA at rank 16 with alpha 32 and dropout 0.05 on a fixed evaluation set, then raise rank only if the eval shows capacity errors rather than data errors. Log trainable parameters, base model revision, data snapshot id, and eval scores with every run so the second attempt can be compared to the first. Promote only against a held-out set the training loop never saw, and keep the base model one deploy away at all times.

Common Mistakes

Fine-tuning to inject private knowledge that will change next month, then maintaining a stale weight snapshot

Fix: Use retrieval for facts that change, and reserve fine-tuning for behaviour and format the model must produce every time

Loading a LoRA adapter onto a different base model revision and shipping the silently degraded output

Fix: Record the base model revision inside the adapter directory and assert it at load time so startup fails loudly

Judging a preference-tuning run by its falling training loss instead of by a held-out win rate

Fix: Split pairs by prompt, and promote only when the held-out pairwise win rate against the base model improves

Key Takeaways

  • Full fine-tuning on 8B parameters needs roughly 450 GB before activations because weights, Adam moments and gradients together cost about 56 bytes per parameter
  • LoRA at rank 16 on a 4096 square projection trains 131,072 parameters, 0.78 percent of the matrix, and adapters at rank 16 to 32 cover most instruction tuning
  • QLoRA reaches 4-bit weights at about 35 GB for a 70B model but runs 30 percent slower, since compute stays in bfloat16 and gradient checkpointing is mandatory
  • DPO removes the reward model and makes pair quality the binding constraint, so evaluate on a held-out win rate rather than on training loss

Explore More Articles

Search across 3100+ tutorials and news articles.