Skip to main content
LoRA (Low-Rank Adaptation) is a parameter-efficient fine-tuning method that trains small adapter layers while keeping the pretrained model frozen. This dramatically reduces memory requirements and training time compared to full-parameter fine-tuning.

Overview

LoRA achieves efficient fine-tuning by:
  • Training only 0.1-1% of model parameters
  • Keeping original model weights frozen
  • Adding trainable low-rank decomposition matrices to attention layers
  • Enabling single-GPU training for 7B models
  • Allowing multiple adapters for different tasks
LoRA provides 90-95% of full fine-tuning performance with only 20-40% of the memory requirements.

When to Use LoRA

Choose LoRA when:
  • You have single GPU with 16-40GB memory
  • You need fast iteration on different tasks
  • You want to maintain multiple task-specific adapters
  • You need quick deployment without merging weights
  • Your task requires moderate adaptation from pretrained behavior

Hardware Requirements

Memory Requirements

Qwen-7B LoRA Fine-tuning (Single A100-80GB):
LoRA (emb) refers to training with embedding and output layers as trainable parameters, required when fine-tuning base models with new tokens.

GPU Recommendations by Model Size

Installation

Use peft<0.8.0 to avoid tokenizer loading issues. Version 0.8.0+ has a known bug with Qwen tokenizer.

LoRA Configuration

LoRA adds trainable rank decomposition matrices to specific model layers:

Parameter Explanation

int
default:64
Rank of the low-rank decomposition matrices. Higher rank = more capacity but more memory.
  • r=8: Very efficient, good for simple tasks
  • r=16-32: Balanced, suitable for most tasks
  • r=64: Higher capacity, recommended default
  • r=128: Maximum capacity, for complex tasks
int
default:16
Scaling factor for LoRA updates. Affects learning rate.Scaling = lora_alpha / r
  • Common pattern: lora_alpha = r/4 or r/2
  • Does not affect trainable parameters
  • Adjust if model underfits or overfits
list
required
Model layers where LoRA adapters are applied.For Qwen: ["c_attn", "c_proj", "w1", "w2"]
  • c_attn: Attention query, key, value projections
  • c_proj: Attention output projection
  • w1, w2: Feed-forward network layers
float
Dropout probability for LoRA layers (regularization).
list
Additional modules to train beyond LoRA adapters.For base models: ["wte", "lm_head"] (embedding and output layers)For chat models: None (not needed)

Single-GPU Training

Basic Training Script

finetune/finetune_lora_single_gpu.sh

Running Single-GPU Training

1

Prepare Your Data

Create training data in JSON format:
2

Launch Training

3

Monitor Training

Watch training progress:
The LoRA adapter is saved to output_qwen/.

Multi-GPU Training

For faster training or larger models, use distributed LoRA training:
finetune/finetune_lora_ds.sh

DeepSpeed ZeRO-2 Configuration

finetune/ds_config_zero2.json
ZeRO-2 shards optimizer states and gradients across GPUs, but keeps model parameters replicated. This is ideal for LoRA since adapter parameters are small.

Base Model vs Chat Model

Key differences when fine-tuning base models vs chat models:
Advantages:
  • Lower memory usage (no extra trainable parameters)
  • Compatible with DeepSpeed ZeRO-3
  • No special handling needed
  • Recommended for most use cases

Fine-tuning Base Models

When fine-tuning base models:
  • Automatically enables training of embedding (wte) and output (lm_head) layers
  • Required for model to learn ChatML special tokens
  • Higher memory usage (~13.6GB extra for Qwen-7B)
  • Cannot use ZeRO-3 (must use ZeRO-2)
Fine-tuning base models with LoRA requires significantly more memory. Consider using chat models instead.

Loading and Using LoRA Adapters

Load Adapter for Inference

Merge Adapter with Base Model

For deployment, you can merge the adapter into the base model:
After saving merged model, manually copy *.cu and *.cpp files if you need KV cache quantization support.

Switch Between Multiple Adapters

Hyperparameter Tuning

Learning Rate

LoRA uses higher learning rates than full fine-tuning:
  • Conservative: 1e-4 (safer for base models)
  • Standard: 3e-4 (recommended for chat models)
  • Aggressive: 5e-4 (fast convergence, watch for instability)
LoRA adapters benefit from higher learning rates because only a small subset of parameters is being trained.

LoRA Rank (r)

Adjust based on task complexity:

Batch Size Optimization

Adjust based on GPU memory:

Advanced Techniques

Custom Target Modules

Target specific layers for your use case:

LoRA with Custom Tokens

If adding new tokens to vocabulary:

Quantization After LoRA Training

Quantize your merged LoRA model for deployment:
See Q-LoRA documentation for details.

Monitoring Training

TensorBoard Integration

View training metrics:

Weights & Biases Integration

Troubleshooting

Issue: ValueError: Tokenizer class QWenTokenizer does not existSolution: Downgrade PEFT
Solutions:
  1. Reduce per_device_train_batch_size to 1
  2. Reduce model_max_length (e.g., 512 → 256)
  3. Enable gradient checkpointing: --gradient_checkpointing
  4. Reduce LoRA rank: --lora_r 32 or --lora_r 16
  5. Use Q-LoRA instead (see Q-LoRA guide)
Possible causes:
  • Learning rate too low: Try --learning_rate 5e-4
  • LoRA rank too small: Increase --lora_r 128
  • Data quality issues: Review training samples
  • Insufficient training: Increase epochs
Debug:
Issue: ZeRO-3 incompatible with base model LoRASolution: Use ZeRO-2 or switch to chat model
Issue: *.cu and *.cpp files missing from saved adapterSolution: Manually copy from source

Performance Comparison

LoRA vs Full-Parameter (Qwen-7B)

LoRA vs Q-LoRA

Best Practices

Do’s
  • Use chat models when possible for lower memory usage
  • Start with default LoRA config (r=64, alpha=16)
  • Enable gradient checkpointing for memory savings
  • Monitor training loss to detect convergence
  • Save multiple checkpoints for checkpoint selection
Don’ts
  • Don’t use ZeRO-3 with base model LoRA (embedding trainable)
  • Don’t use excessively high learning rates (>5e-4)
  • Don’t skip validation data for complex tasks
  • Don’t merge adapters for Q-LoRA (not supported)
  • Don’t forget to copy support files (*.cu, *.cpp) when needed

Next Steps

Q-LoRA Training

Further reduce memory with quantization

Multi-node Training

Scale LoRA training across multiple machines