Large language models are trained on enormous datasets and can perform a wide range of tasks. However, a general-purpose model may not follow the response format, terminology, or specialized instructions required by a particular application.
For example, imagine building an AI assistant for a company's technical support team. The assistant needs to understand internal terminology, follow a consistent response format, and provide answers that match the company's support guidelines.
Prompt engineering can help, but repeatedly adding detailed instructions does not always produce consistent results.
This is where fine-tuning becomes useful.
Low-Rank Adaptation (LoRA) is a parameter-efficient fine-tuning technique that adapts a pretrained model by training a relatively small number of additional parameters instead of updating all its original weights.
It allows developers to customize open-weight language models with significantly less training memory and storage than conventional full fine-tuning.
In this guide, we will walk through a practical LoRA fine-tuning workflow using Hugging Face, including dataset preparation, adapter configuration, model training, and evaluation.
1. What Is LoRA Fine-Tuning?
Traditional full fine-tuning updates the model's original parameters using a task-specific dataset.
For a large language model containing billions of parameters, this can require substantial GPU memory because training involves gradients, optimizer states, and model parameters.
LoRA takes a different approach.
Instead of modifying the pretrained weights directly, it freezes the original model and introduces smaller trainable matrices into selected layers of the Transformer architecture.
Suppose a pretrained model contains a weight matrix:
[ W \in \mathbb{R}^{d \times k} ]
LoRA represents its trainable update using two smaller matrices:
[ \Delta W = BA ]
Where:
- (A) is a trainable matrix with dimensions (r \times k).
- (B) is a trainable matrix with dimensions (d \times r).
- (r) is the LoRA rank, which is much smaller than the original dimensions.
The adapted weight becomes:
[ W' = W + \frac{\alpha}{r}BA ]
Here, (\alpha) is the LoRA scaling factor.
The original weight matrix (W) remains frozen. Only the smaller matrices (A) and (B) are updated during training.
This significantly reduces the number of trainable parameters.
For example, rather than updating an entire large weight matrix, LoRA learns a compact representation of the required adjustment.
Why use LoRA?
- Lower memory requirements: Only adapter parameters need gradients and optimizer states.
- Smaller checkpoints: The adapter can be stored separately from the original model.
- Reusable base models: Different adapters can customize the same pretrained model for different tasks.
- Flexible deployment: Adapters can be loaded separately or merged into the original model.
LoRA does not guarantee better answers than full fine-tuning. Its advantage is that it provides an efficient way to adapt a model while retaining much of the original pretrained knowledge.
2. Choose a Pretrained Model
Before training, select a base model suitable for your target task.
For this walkthrough, we will use:
Qwen/Qwen2.5-0.5B-Instruct
It is a compact instruction-tuned model suitable for demonstrating the workflow.
When selecting a model, consider:
- Model size and available GPU memory.
- Supported languages and capabilities.
- Maximum context length.
- Existing instruction-following performance.
- Architecture compatibility with your training framework.
- Model license and permitted usage.
One important distinction: a model being publicly available with downloadable weights does not automatically make its license an open-source license. Check the actual license before commercial deployment or redistribution.
For this example, we will use a smaller model so the training workflow is easier to reproduce.
3. Prepare the Training Environment
We will use four main libraries:
- Transformers: Loads the pretrained language model and tokenizer.
- Datasets: Loads and processes the training examples.
- PEFT: Implements LoRA adapters.
- TRL: Provides the supervised fine-tuning trainer.
Install the dependencies:
pip install -U torch transformers datasets peft trl accelerate
For this tutorial, we will use supervised fine-tuning (SFT), where the model learns from examples containing instructions and expected responses.
The training workflow looks like this:
Pretrained LLM
|
v
Prepare Training Dataset
|
v
Configure LoRA Adapters
|
v
Supervised Fine-Tuning
|
v
Save LoRA Adapter
|
v
Evaluate Fine-Tuned Model
4. Prepare a High-Quality Dataset
Dataset quality has a direct impact on fine-tuning results.
A common mistake is assuming that collecting more training examples automatically produces a better model.
In practice, inconsistent, duplicated, incorrect, or poorly formatted examples can reduce performance.
For this example, suppose we want to adapt a model to answer Python programming questions in a consistent teaching style.
A training example might contain:
Instruction:
Explain Python decorators with a simple example.
Expected response:
A Python decorator is a function that modifies the behavior of another function without changing its original source code.
It is commonly used for logging, authentication, and performance measurement.
A dataset can store these examples in JSONL format, with one JSON object per line.
Example:
{
"prompt": [
{
"role": "user",
"content": "Explain Python decorators with a simple example."
}
],
"completion": [
{
"role": "assistant",
"content": "A Python decorator is a function that modifies the behavior of another function without changing its original source code."
}
]
}
Create separate files:
dataset/
train.jsonl
validation.jsonl
test.jsonl
Each file should contain the same structured fields.
The three splits serve different purposes:
| Dataset | Purpose |
|---|---|
| Training | Updates the LoRA parameters |
| Validation | Monitors performance during training |
| Test | Measures final performance on unseen examples |
Do not place duplicate or near-duplicate examples across these splits. Otherwise, evaluation results may look better than actual performance.
Dataset preparation checklist
Before training:
- Remove duplicate examples.
- Correct inaccurate answers.
- Use consistent instruction and response formats.
- Remove unnecessary or sensitive information.
- Check token lengths against the model's context limit.
- Keep a separate test dataset that is not used for training decisions.
For conversational models, use the model's expected chat format. Different models can use different chat templates and special tokens.
5. Configure LoRA Adapters
Now we need to decide how LoRA will be applied to the pretrained model.
The important configuration parameters include:
| Parameter | Purpose |
|---|---|
r | Rank of the LoRA update matrices |
lora_alpha | Scaling factor for adapter updates |
lora_dropout | Dropout applied to LoRA layers |
target_modules | Model layers that receive LoRA adapters |
task_type | Identifies the training task |
For an initial experiment, we can use:
from peft import LoraConfig
lora_config = LoraConfig(
task_type="CAUSAL_LM",
r=16,
lora_alpha=32,
lora_dropout=0.05,
target_modules=[
"q_proj",
"k_proj",
"v_proj",
"o_proj"
],
bias="none"
)
The target modules represent attention projection layers commonly used in Transformer architectures.
The selected module names must match the architecture of your chosen model. Inspect the model's layer names before applying LoRA to a different architecture.
How should you choose the LoRA rank?
Rank controls the capacity of the trainable update matrices.
A smaller rank means fewer trainable parameters and a smaller adapter. A larger rank provides more capacity but increases training and storage costs.
Typical starting values include:
r=8: Small adapter and limited parameter budget.r=16: A practical starting point for many experiments.r=32: More adaptation capacity.r=64: Larger adapter when additional capacity is justified.
These are starting points, not universal rules. Test different ranks against the same validation set rather than assuming that a higher rank will always improve results.
6. Train the Model Using Hugging Face TRL
With the dataset and LoRA configuration ready, we can start supervised fine-tuning.
First, load the dataset and tokenizer:
from datasets import load_dataset
from transformers import AutoTokenizer
model_id = "Qwen/Qwen2.5-0.5B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(model_id)
dataset = load_dataset(
"json",
data_files={
"train": "dataset/train.jsonl",
"validation": "dataset/validation.jsonl"
}
)
Next, configure the training parameters.
from trl import SFTConfig
training_args = SFTConfig(
output_dir="./qwen-lora-output",
num_train_epochs=2,
per_device_train_batch_size=2,
per_device_eval_batch_size=2,
gradient_accumulation_steps=8,
learning_rate=1e-4,
logging_steps=10,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="eval_loss",
greater_is_better=False,
completion_only_loss=True,
max_length=1024,
eos_token=tokenizer.eos_token,
report_to="none"
)
A few parameters deserve attention.
Learning rate: LoRA commonly uses a higher learning rate than full fine-tuning because only a smaller set of parameters is being trained. The value 1e-4 is a reasonable starting point, not a universal optimum.
Gradient accumulation: This allows multiple smaller batches to contribute to one optimizer update. With a batch size of 2 and accumulation of 8, the effective batch size is 16 for a single training device.
Evaluation strategy: Evaluating after each epoch allows us to monitor performance on examples the model has not trained on.
Completion-only loss: The trainer focuses its loss computation on expected responses rather than treating the input prompt as the target.
Finally, create the trainer and start training:
from trl import SFTTrainer
trainer = SFTTrainer(
model=model_id,
args=training_args,
train_dataset=dataset["train"],
eval_dataset=dataset["validation"],
processing_class=tokenizer,
peft_config=lora_config
)
trainer.train()
The trainer handles the supervised fine-tuning loop, while PEFT ensures that the base model remains frozen and only the LoRA adapter parameters are updated.
The exact GPU requirements depend on the model, sequence length, batch size, precision, and hardware. Start with a small run and adjust the configuration if you encounter out-of-memory errors.
7. What Is QLoRA, and When Should You Use It?
You may also encounter QLoRA when researching memory-efficient LLM fine-tuning.
QLoRA combines LoRA with quantization.
In conventional LoRA training, the pretrained model is generally loaded in a floating-point representation while the adapters remain trainable.
QLoRA loads the frozen base model in a lower-bit representation, commonly 4-bit, and trains the LoRA adapters on top.
This reduces the memory required to hold the base model.
The distinction is:
| Approach | Base model | Trainable parameters |
|---|---|---|
| Full fine-tuning | Floating point | All model parameters |
| LoRA | Floating point | LoRA adapters |
| QLoRA | Quantized, commonly 4-bit | LoRA adapters |
QLoRA is especially useful when the full-precision base model would otherwise exceed available GPU memory.
It does introduce additional quantization and hardware considerations, so it is worth starting with ordinary LoRA before adding that complexity.
8. Save and Load the Fine-Tuned Adapter
After training, the LoRA adapter can be saved separately.
trainer.save_model("./qwen-python-lora")
token



