Fine-Tuning Llama 3 with LoRA: A Step-by-Step Guide

Fine-tuning large language models like Meta's Llama 3 traditionally demands massive computational clusters. However, parameter-efficient fine-tuning (PEFT) techniques like Low-Rank Adaptation (LoRA) and QLoRA (Quantized LoRA) make it possible to fine-tune billion-parameter models on modest consumer hardware or single-GPU cloud instances.

This comprehensive guide walks through setting up your training environment, preparing custom instruction datasets, configuring 4-bit quantization, and executing LoRA fine-tuning using Hugging Face libraries.

1. Environment Setup and Dependencies

Create a clean Python virtual environment and install the required Hugging Face ecosystem libraries, including transformers, peft, bitsandbytes, and trl.

C
# Create and activate virtual environment
python3 -m venv venv
source venv/bin/activate

# Install required ML dependencies
pip install torch torchvision torchaudio
pip install transformers datasets accelerate peft bitsandbytes trl

2. Loading Llama 3 with 4-Bit QLoRA Quantization

To fit Llama 3 into limited VRAM, configure BitsAndBytesConfig to load the base model in 4-bit precision.

C
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig

model_id = "meta-llama/Meta-Llama-3-8B-Instruct"

# Configure 4-bit quantization
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.float16,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_use_double_quant=True
)

# Load tokenizer and model
tokenizer = AutoTokenizer.from_pretrained(model_id)
tokenizer.pad_token = tokenizer.eos_token

model = AutoModelForCausalLM.from_pretrained(
    model_id,
    quantization_config=bnb_config,
    device_map="auto"
)

3. Configuring LoRA Adapters with PEFT

Define your LoRA configuration parameters, targeting the attention projection layers of Llama 3.

C
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training

model = prepare_model_for_kbit_training(model)

peft_config = LoraConfig(
    r=16,
    lora_alpha=32,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
    lora_dropout=0.05,
    bias="none",
    task_type="CAUSAL_LM"
)

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

4. Training the Model and Saving Checkpoints

Set up the SFTTrainer from Hugging Face's trl library and begin the supervised fine-tuning process.

C
from transformers import TrainingArguments
from datasets import load_dataset
from trl import SFTTrainer

dataset = load_dataset("json", data_files="train_data.json")

training_args = TrainingArguments(
    output_dir="./results",
    per_device_train_batch_size=2,
    gradient_accumulation_steps=4,
    learning_rate=2e-4,
    logging_steps=10,
    num_train_epochs=3,
    fp16=True,
    optim="paged_adamw_8bit"
)

trainer = SFTTrainer(
    model=model,
    train_dataset=dataset["train"],
    peft_config=peft_config,
    max_seq_length=512,
    tokenizer=tokenizer,
    args=training_args
)

trainer.train()
model.save_pretrained("./llama-3-lora-adapter")

Conclusion

By combining QLoRA quantization with Hugging Face's PEFT and TRL libraries, you can successfully adapt Llama 3 for specialized domain instructions and custom applications without requiring enterprise-grade hardware clusters.