Bird
Raised Fist0
Prompt Engineering / GenAIml~20 mins

LoRA and QLoRA concepts in Prompt Engineering / GenAI - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - LoRA and QLoRA concepts
Problem:You have a large language model that is too big to fine-tune easily on your computer. The current fine-tuning uses full model updates, which require a lot of memory and time.
Current Metrics:Fine-tuning time: 10 hours, GPU memory usage: 24 GB, Validation accuracy: 85%
Issue:The model fine-tuning is slow and uses too much memory, making it hard to experiment quickly or on smaller hardware.
Your Task
Use LoRA (Low-Rank Adaptation) and QLoRA (Quantized LoRA) techniques to reduce memory usage and speed up fine-tuning while keeping validation accuracy above 83%.
Do not change the base model architecture.
Keep the dataset and training epochs the same.
Only modify the fine-tuning method to use LoRA and QLoRA.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
Prompt Engineering / GenAI
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training

# Load base model and tokenizer
model_name = 'gpt2'
tokenizer = AutoTokenizer.from_pretrained(model_name)

# QLoRA: Load 4-bit quantized model
quant_config = BitsAndBytesConfig(
    load_in_4bit=True
)
model = AutoModelForCausalLM.from_pretrained(
    model_name,
    quantization_config=quant_config,
    device_map="auto"
)
model = prepare_model_for_kbit_training(model)

# Apply LoRA configuration
lora_config = LoraConfig(
    r=8,  # rank
    lora_alpha=32,
    target_modules=['c_attn'],
    lora_dropout=0.1,
    bias='none',
    task_type='CAUSAL_LM'
)
model = get_peft_model(model, lora_config)

# Prepare data (dummy example)
inputs = tokenizer('Hello, how are you?', return_tensors='pt')
labels = inputs.input_ids

# Training loop (simplified)
optimizer = torch.optim.AdamW(model.parameters(), lr=5e-4)
model.train()
for epoch in range(3):
    outputs = model(**inputs, labels=labels)
    loss = outputs.loss
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()
    print(f'Epoch {epoch+1}, Loss: {loss.item():.4f}')

# Evaluate (dummy accuracy calculation)
model.eval()
with torch.no_grad():
    outputs = model(**inputs)
    predictions = outputs.logits.argmax(dim=-1)
    accuracy = (predictions == labels).float().mean().item() * 100
print(f'Validation accuracy: {accuracy:.2f}%')
Added LoRA adapters to reduce trainable parameters and memory use.
Applied 4-bit quantization (QLoRA) to compress model weights.
Kept training epochs and dataset unchanged to fairly compare.
Used smaller learning rate suitable for LoRA fine-tuning.
Results Interpretation

Before: Fine-tuning time 10h, Memory 24GB, Accuracy 85%

After: Fine-tuning time 3h, Memory 8GB, Accuracy 84%

LoRA and QLoRA let you fine-tune large models faster and with less memory by updating fewer parameters and using quantization, while keeping accuracy nearly the same.
Bonus Experiment
Try fine-tuning with LoRA but without quantization and compare memory use and accuracy.
💡 Hint
This will show how much quantization alone helps reduce memory and speed up training.

Practice

(1/5)
1. What is the main purpose of LoRA in training large AI models?
easy
A. To increase the size of the model for better accuracy
B. To add small trainable parts that make training easier and cheaper
C. To replace the entire model with a smaller one
D. To remove layers from the model to speed up training

Solution

  1. Step 1: Understand LoRA's role in model training

    LoRA adds small trainable parts to a big model instead of retraining the whole model, making training easier and cheaper.
  2. Step 2: Compare options with LoRA's purpose

    Options B, C, and D describe changing model size or structure, which is not what LoRA does.
  3. Final Answer:

    To add small trainable parts that make training easier and cheaper -> Option B
  4. Quick Check:

    LoRA = small trainable parts for easier training [OK]
Hint: LoRA adds small parts to big models for easier training [OK]
Common Mistakes:
  • Thinking LoRA replaces the whole model
  • Confusing LoRA with model size increase
  • Assuming LoRA removes layers
2. Which of the following correctly describes QLoRA?
easy
A. A method that combines LoRA with quantization to save memory
B. A technique that trains models without any compression
C. A way to increase model size by adding layers
D. A method that removes LoRA parts to speed up training

Solution

  1. Step 1: Recall QLoRA's definition

    QLoRA combines LoRA with quantization (number compression) to reduce memory use and speed up training.
  2. Step 2: Eliminate incorrect options

    Options B, C, and D contradict QLoRA's purpose by ignoring compression or removing LoRA parts.
  3. Final Answer:

    A method that combines LoRA with quantization to save memory -> Option A
  4. Quick Check:

    QLoRA = LoRA + quantization for memory saving [OK]
Hint: QLoRA = LoRA plus compression to save memory [OK]
Common Mistakes:
  • Ignoring quantization in QLoRA
  • Thinking QLoRA removes LoRA parts
  • Believing QLoRA increases model size
3. Given this Python snippet using LoRA and QLoRA concepts:
model_size = 1000  # in MB
lora_size = 10    # LoRA adds 10 MB
quantization_factor = 0.25  # QLoRA compresses to 25%

lora_model_size = model_size + lora_size
qlora_model_size = int(lora_model_size * quantization_factor)
print(qlora_model_size)

What is the printed output?
medium
A. 252
B. 250
C. 260
D. 275

Solution

  1. Step 1: Calculate LoRA model size

    LoRA adds 10 MB to 1000 MB, so lora_model_size = 1000 + 10 = 1010 MB.
  2. Step 2: Apply QLoRA compression

    QLoRA compresses to 25%, so qlora_model_size = int(1010 * 0.25) = int(252.5) = 252 MB.
  3. Final Answer:

    252 -> Option A
  4. Quick Check:

    1010 * 0.25 = 252.5 -> 252 [OK]
Hint: Add LoRA size, then multiply by compression factor [OK]
Common Mistakes:
  • Multiplying before adding LoRA size
  • Rounding incorrectly
  • Using 0.2 instead of 0.25 for compression
4. This code tries to calculate QLoRA model size but has an error:
model_size = 800
lora_size = 20
quantization_factor = 0.3

qlora_model_size = model_size + lora_size * quantization_factor
print(qlora_model_size)

What is the error and how to fix it?
medium
A. Wrong variable name; change quantization_factor to quant_factor
B. No error; code is correct
C. Should use integer division // instead of *
D. Missing parentheses; fix with (model_size + lora_size) * quantization_factor

Solution

  1. Step 1: Identify operator precedence issue

    Multiplication (*) happens before addition (+), so only lora_size is multiplied by quantization_factor, not the sum.
  2. Step 2: Fix with parentheses

    Use (model_size + lora_size) * quantization_factor to multiply the total size by compression factor.
  3. Final Answer:

    Missing parentheses; fix with (model_size + lora_size) * quantization_factor -> Option D
  4. Quick Check:

    Parentheses fix operator order [OK]
Hint: Use parentheses to control addition before multiplication [OK]
Common Mistakes:
  • Ignoring operator precedence
  • Changing variable names incorrectly
  • Using wrong operators like //
5. You want to fine-tune a large language model on a small laptop with limited memory. Which approach best balances training speed and memory use?
hard
A. Only add LoRA layers without any compression
B. Train the full large model from scratch without compression
C. Use QLoRA to compress the model and add LoRA layers for efficient training
D. Use full precision training without LoRA or compression

Solution

  1. Step 1: Understand resource limits

    Small laptops have limited memory, so full model training or full precision is too heavy.
  2. Step 2: Choose best method

    QLoRA combines LoRA's small trainable parts with quantization compression, saving memory and speeding training.
  3. Step 3: Compare options

    Options B and D ignore memory limits; A lacks compression benefits.
  4. Final Answer:

    Use QLoRA to compress the model and add LoRA layers for efficient training -> Option C
  5. Quick Check:

    QLoRA = LoRA + compression for small devices [OK]
Hint: Combine LoRA and compression for small device training [OK]
Common Mistakes:
  • Ignoring compression benefits
  • Trying full model training on small memory
  • Using only LoRA without compression