Skip to content

How to Fine-Tune a Model with LoRA in Practice

Summary

LoRA allows fine-tuning a model on a single GPU by updating only a small portion of the weights. This guide covers the working pipeline from library installation to using the trained adapter, including parameter breakdown.

What We Do

We fine-tune an open-source model to respond in a specific style or solve a narrow task. Instead of training all billions of parameters, we train a small 'adapter' that is then applied to the base model.

The result is a file of tens of megabytes instead of gigabytes of the full model, and training runs on a regular GPU with 16–24 GB VRAM.

What You Need

  • NVIDIA GPU with 16+ GB VRAM (12 GB is also possible, but with a smaller model);
  • Python 3.10+;
  • Base model from Hugging Face (e.g., Qwen2.5-7B);
  • Dataset of 'prompt-response' pairs.

Step 1. Install Libraries

pip install torch transformers datasets accelerate peft bitsandbytes
  • peft — implementation of LoRA and PEFT methods;
  • bitsandbytes — 4-bit quantization of the base model;
  • accelerate — launching training on one or multiple GPUs.

Step 2. Load Model in 4 Bits

Quantizing the base model saves memory: training runs on a 'compressed' version — this is QLoRA.

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig

model_name = "Qwen/Qwen2.5-7B-Instruct"

quant = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
)

model = AutoModelForCausalLM.from_pretrained(
    model_name,
    quantization_config=quant,
    device_map="auto",
)

tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenizer.pad_token = tokenizer.eos_token

Step 3. Configure LoRA

Key parameters:

from peft import LoraConfig, get_peft_model

lora_config = LoraConfig(
    r=16,                  # adapter rank
    lora_alpha=32,         # influence scale (usually 2×r)
    lora_dropout=0.05,     # regularization
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
    task_type="CAUSAL_LM",
)

model = get_peft_model(model, lora_config)
model.print_trainable_parameters()

What the parameters mean:

Parameter What it does How to choose
r Adapter size 8–32: larger = more capacity, but heavier
lora_alpha Adapter influence strength Usually 2×r
lora_dropout Protection against overfitting 0.05–0.1
target_modules Which layers to train For LLM — q_proj, k_proj, v_proj, o_proj

print_trainable_parameters() will show the proportion of trainable parameters — usually 1–5% of the whole model.

Step 4. Prepare the Dataset

Easiest is a JSONL file with instruction and output fields:

{"instruction": "Write a greeting for the customer", "output": "Hello! We are glad to see you."}
{"instruction": "Explain what a refund is", "output": "A refund is..."}

Load and format:

from datasets import load_dataset

def format_example(example):
    text = f"\n{example['instruction']}\n\n{example['output']}"
    return {"text": text}

dataset = load_dataset("json", data_files="data/train.jsonl")
dataset = dataset["train"].map(format_example)

def tokenize(ex):
    return tokenizer(ex["text"], truncation=True, max_length=512)

dataset = dataset.map(tokenize, batched=True)

Step 5. Configure Training

from transformers import TrainingArguments

training_args = TrainingArguments(
    output_dir="./lora-checkpoints",
    per_device_train_batch_size=2,
    gradient_accumulation_steps=4,   # simulates a larger batch
    num_train_epochs=3,
    learning_rate=2e-4,
    logging_steps=10,
    save_strategy="epoch",
    bf16=True,
    report_to="none",
)
  • gradient_accumulation_steps — accumulates gradients, emulating a batch of 8 without extra memory;
  • learning_rate=2e-4 — typical start for LoRA;
  • bf16=True — speeds up and saves memory on new GPUs.

Step 6. Launch Training

from trl import SFTTrainer

trainer = SFTTrainer(
    model=model,
    args=training_args,
    train_dataset=dataset,
    tokenizer=tokenizer,
)

trainer.train()

SFTTrainer from the trl library is tailored for training language models with instructions. Install it beforehand:

pip install trl

Step 7. Save the Adapter

model.save_pretrained("./my-lora-adapter")
tokenizer.save_pretrained("./my-lora-adapter")

Only the adapter is saved — no need to save the base model.

Step 8. Use the Fine-Tuned Model

from peft import PeftModel

base = AutoModelForCausalLM.from_pretrained(
    model_name,
    quantization_config=quant,
    device_map="auto",
)
model = PeftModel.from_pretrained(base, "./my-lora-adapter")

inputs = tokenizer("Write a greeting for the customer", return_tensors="pt")
out = model.generate(**inputs, max_new_tokens=100)
print(tokenizer.decode(out[0], skip_special_tokens=True))

Common Issues

1. Not Enough Memory (CUDA OOM)

Reduce r to 8, max_length to 256, batch to 1 or use a smaller model (3B).

2. Model 'Forgets' How to Speak Properly

Looks like overfitting. Reduce number of epochs or learning_rate, add more diverse examples.

3. Responses Too Short or Cut Off

Check that the dataset has examples of the required length and increase max_length during tokenization.

Checklist Before Launch

  • Base model and dataset are compatible in format;
  • target_modules match the architecture;
  • Training runs on one epoch without errors, then on all;
  • Adapter is saved and loaded separately from the base.

See Also