LLM Masterclass / Module 6 of 10 Phase 2: Pre-Training, SFT & Parameter-Efficient Fine-Tuning (LoRA/QLoRA)

LoRA, QLoRA, DoRA & Parameter-Efficient Fine-Tuning (PEFT) — Mathematical & Production Blueprint

34 min study + 2 Live Wasm Labs + Interactive LoRA/QLoRA VRAM Calculator
⚡ Answer-First Executive Summary (TL;DR) Module 6 Key Takeaways
  • ✓ LoRA freezes the pre-trained weight matrix W_0 ∈ ℝ^(d×k) and injects a trainable low-rank update ΔW = (α/r) B A where B ∈ ℝ^(d×r), A ∈ ℝ^(r×k), and rank r ≪ min(d, k)—reducing trainable parameters by 99.0% to 99.9% and eliminating optimizer state VRAM on W_0.
  • ✓ Initialization Invariant: Matrix A is initialized with random Gaussian/Kaiming weights while Matrix B is initialized to all zeros (B = 0), guaranteeing that ΔW = B A = 0 at training step 0 so the model starts identically to the pre-trained base model.
  • ✓ QLoRA (Dettmers et al.) enables fine-tuning a 70B LLM on a single 48GB–80GB GPU by storing frozen base weights W_0 in 4-bit NormalFloat (NF4) with Double Quantization (saving 0.37 bits/param) and dequantizing W_0 to BF16 on-the-fly during the forward/backward pass while computing gradients only for BF16 LoRA adapters B and A.
  • ✓ At inference time, LoRA adds zero latency: either fold adapters permanently into base weights via W_merged = W_0 + (α/r)BA, or serve hundreds of per-tenant adapters dynamically in vLLM using S-LoRA / Punica batched CUDA kernels.

01. The Mathematics & Architecture of Low-Rank Adaptation (LoRA)

Aghajanyan et al. (2020) showed that pre-trained language models have a very low intrinsic dimension when adapted to downstream tasks. Building on this, Hu et al. (2021) proposed constraining the weight update ΔW of any linear projection h = W₀x to a low-rank factorization:

h = W₀x + ΔWx = W₀x + (α / r) · B A x

where W₀ ∈ ℝd×k is frozen (requires zero gradients and zero AdamW optimizer states!), A ∈ ℝr×k projects the k-dimensional input down to rank r ≪ min(d, k), and B ∈ ℝd×r projects it back up to d dimensions:

                   Output h = W_0 x + (α / r) · B(A x)   (h ∈ ℝ^d)
                              ▲                   ▲
                              │      ( + )        │
             ┌────────────────┘                   └────────────────┐
             │                                                     │
  ┌──────────┴──────────┐                               ┌──────────┴──────────┐
  │  FROZEN Base Weight │                               │  LoRA Up-Matrix B   │
  │   W_0 ∈ ℝ^(d × k)   │                               │    B ∈ ℝ^(d × r)    │
  │ (BF16 or 4-bit NF4) │                               │ (Initialized B = 0) │
  │  0 Gradients / Opt  │                               └──────────▲──────────┘
  └──────────▲──────────┘                                          │ Low-Rank Bottleneck (r = 16)
             │                                          ┌──────────┴──────────┐
             │                                          │ LoRA Down-Matrix A  │
             │                                          │    A ∈ ℝ^(r × k)    │
             │                                          │  (A ~ N(0, σ²))     │
             └────────────────────┬─────────────────────┘──────────▲──────────┘
                                  │                                │
                           Input Activation x ∈ ℝ^k ───────────────┘

02. Interactive Fine-Tuning GPU VRAM Calculator (Full FT vs. LoRA BF16 vs. 4-Bit QLoRA)

Live Fine-Tuning VRAM Estimator (All 7 Linear Projections Targeted, Rank r=16, Grad Checkpointing ON)

Slide to select base LLM parameter count (Ψ Billion Parameters):

70B Parameter LLM
1. Full Fine-Tuning (BF16 + AdamW)
~1,120.0 GB
16B/param (2B W + 2B G + 12B Opt) — Requires 16×80GB cluster
2. Standard LoRA (16-Bit Base)
~146.5 GB (-87%)
2B/param frozen BF16 base + tiny BF16 LoRA adapters & activations
3. 4-Bit QLoRA (NF4 + Double Quant)
~44.2 GB (-96%)
0.55B/param NF4 base + BF16 LoRA adapters — Fits 1×80GB GPU!

03. PEFT Family Comparison (LoRA, QLoRA, DoRA, rsLoRA, LoRA+) & Production peft / trl Recipe

Table 6.1 — Parameter-Efficient Fine-Tuning (PEFT) Methods & Hyperparameter Guide
PEFT Method Weight Update Equation Base Weight Precision When to Use in Production
LoRA W = W₀ + (α / r) B A BF16 / FP16 (2 B/param) Default choice for 7B–14B models when 24GB–80GB VRAM is available; fastest training throughput (no NF4 dequantization overhead).
QLoRA (NF4 + DQ) W = dequantBF16(W₀NF4) + (α / r) B A 4-bit NF4 (~0.55 B/param) Fine-tuning 32B–70B+ models on a single GPU; matches 16-bit LoRA accuracy within 0.5%.
DoRA W = m · (W₀ + (α/r)BA) / ‖W₀ + (α/r)BA‖c BF16 or 4-bit NF4 Decouples magnitude m from directional update; superior accuracy at compact ranks (r = 8 or 16). Enable via use_dora=True.
rsLoRA W = W₀ + (α / √r) B A BF16 or 4-bit NF4 Prevents gradient norm collapse at high ranks (r ∈ {64, 128, 256}). Enable via use_rslora=True.
# Production HuggingFace PEFT + TRL QLoRA Fine-Tuning Blueprint
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from trl import SFTConfig, SFTTrainer
import torch

bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",           # Information-theoretically optimal 4-bit NormalFloat
    bnb_4bit_use_double_quant=True,      # Quantize quantization scales (saves ~0.37 bits/param)
    bnb_4bit_compute_dtype=torch.bfloat16,
)

lora_config = LoraConfig(
    r=32,                                # Low-rank bottleneck dimension
    lora_alpha=64,                       # Scaling α = 2 * r
    target_modules="all-linear",         # q/k/v/o_proj + gate/up/down_proj
    lora_dropout=0.05,
    use_dora=True,                       # Optional: Magnitude-direction decomposition
    use_rslora=True,                     # Rank-stabilized α / sqrt(r) scaling
    bias="none",
    task_type="CAUSAL_LM",
)

💻 Hands-On WebAssembly LLM Engineering Labs (Module 6)

Click Run & Edit Live (Wasm) on any lab below to execute and modify the algorithm in our browser Pyodide runtime.

▶ Interactive Wasm Lab

Lab 6.1: Implementing a Complete LoRA Linear Layer (Forward, Step-0 Invariant & Zero-Latency Weight Merging)

Run this live Python implementation of a LoRA Layer to verify parameter reduction, the B=0 step-0 identity invariant, and exact numerical equivalence between unmerged and merged inference.

import math

class LoRALinear:
    def __init__(self, in_features: int, out_features: int, r: int = 4, alpha: float = 8.0, use_rslora: bool = False):
        self.in_features = in_features
        self.out_features = out_features
        self.r = r
        self.scaling = (alpha / math.sqrt(r)) if use_rslora else (alpha / r)
        self.merged = False

        # Frozen pre-trained weight W_0 (out_features x in_features)
        self.W0 = [[((i * 7 + j * 3) % 11 - 5) * 0.1 for j in range(in_features)] for i in range(out_features)]
        # Trainable A (r x in_features): initialized with non-zero Kaiming-like values
        self.A = [[((i + j + 1) % 5 - 2) * 0.05 for j in range(in_features)] for i in range(r)]
        # Trainable B (out_features x r): MUST be initialized to 0.0 so ΔW = 0 at step 0!
        self.B = [[0.0 for _ in range(r)] for _ in range(out_features)]

    def _matmul_vec(self, mat: list[list[float]], vec: list[float]) -> list[float]:
        return [sum(row[j] * vec[j] for j in range(len(vec))) for row in mat]

    def forward(self, x: list[float]) -> list[float]:
        base_out = self._matmul_vec(self.W0, x)
        if self.merged:
            return base_out
        # Low-rank path: B @ (A @ x) * (alpha / r)
        ax = self._matmul_vec(self.A, x)
        bax = self._matmul_vec(self.B, ax)
        return [b_val + self.scaling * lora_val for b_val, lora_val in zip(base_out, bax)]

    def merge_weights_for_inference(self) -> None:
        if self.merged:
            return
        for i in range(self.out_features):
            for j in range(self.in_features):
                delta_ij = sum(self.B[i][k] * self.A[k][j] for k in range(self.r))
                self.W0[i][j] += self.scaling * delta_ij
        self.merged = True

# 1. Parameter Count Savings on a 4096 x 4096 projection at rank r=16
d, k, r = 4096, 4096, 16
base_params = d * k
lora_params = r * (d + k)
print(f"[1] 4096x4096 Linear Projection Parameter Count:")
print(f"    Frozen W_0 Params:   {base_params:>10,} | Trainable LoRA (A+B) Params: {lora_params:>7,} ({100*lora_params/base_params:.2f}% of base!)")

# 2. Verify Step-0 Identity Invariant (When B = 0, LoRA output == Base output)
layer = LoRALinear(in_features=8, out_features=6, r=2, alpha=4.0)
x_in = [1.0, -0.5, 0.8, 0.2, -1.2, 0.4, 0.9, -0.3]
out_step0 = layer.forward(x_in)
base_only = layer._matmul_vec(layer.W0, x_in)
assert all(abs(a - b) < 1e-12 for a, b in zip(out_step0, base_only))
print("\n[2] Step-0 Identity Invariant Verified (B=0 -> ΔW=0): Output matches frozen W_0 to 1e-12!")

# 3. Simulate trained B weights & verify Zero-Latency Weight Folding (W_merged = W_0 + (α/r)BA)
for i in range(layer.out_features):
    for k_idx in range(layer.r):
        layer.B[i][k_idx] = (i - k_idx + 1) * 0.12

out_unmerged = layer.forward(x_in)
layer.merge_weights_for_inference()
out_merged = layer.forward(x_in)
max_diff = max(abs(a - b) for a, b in zip(out_unmerged, out_merged))
print("[3] Zero-Latency Inference Merge Verification:")
print("    Unmerged Forward:", [round(v, 5) for v in out_unmerged])
print("    Merged W_0*x:    ", [round(v, 5) for v in out_merged], f"(Max diff = {max_diff:.2e})")
▶ Interactive Wasm Lab

Lab 6.2: QLoRA 4-Bit NormalFloat (NF4) vs. Uniform INT4 Quantization Precision Benchmark

Compare reconstruction error on normally distributed neural network weights between QLoRA’s 16 NF4 quantile bins and uniform INT4.

import math
import random

# Official 16 4-bit NormalFloat (NF4) codebook quantiles from QLoRA (Dettmers et al., 2023)
NF4_CODEBOOK = [
    -1.0, -0.6961928, -0.52507305, -0.3949175, -0.28444138, -0.18477343, -0.09105004, 0.0,
     0.0795803, 0.1609302, 0.2461123, 0.33791524, 0.44070983, 0.562617, 0.72295684, 1.0
]
# Standard Uniform 4-bit codebook (-1.0 to +1.0 in 16 equal steps)
UNIFORM_INT4 = [-1.0 + (2.0 * i / 15.0) for i in range(16)]

def quantize_block(weights: list[float], codebook: list[float]) -> tuple[list[int], float]:
    absmax = max(abs(w) for w in weights) or 1.0
    indices = []
    for w in weights:
        norm_w = w / absmax
        best_idx = min(range(16), key=lambda idx: abs(norm_w - codebook[idx]))
        indices.append(best_idx)
    return indices, absmax

def dequantize_block(indices: list[int], absmax: float, codebook: list[float]) -> list[float]:
    return [codebook[idx] * absmax for idx in indices]

random.seed(42)
# Generate 2,048 Gaussian weights N(0, 0.02^2) typical of an LLM linear projection
weights = [random.gauss(0.0, 0.02) for _ in range(2048)]

idx_nf4, scale_nf4 = quantize_block(weights, NF4_CODEBOOK)
rec_nf4 = dequantize_block(idx_nf4, scale_nf4, NF4_CODEBOOK)
rmse_nf4 = math.sqrt(sum((w - r) ** 2 for w, r in zip(weights, rec_nf4)) / len(weights))

idx_uni, scale_uni = quantize_block(weights, UNIFORM_INT4)
rec_uni = dequantize_block(idx_uni, scale_uni, UNIFORM_INT4)
rmse_uni = math.sqrt(sum((w - r) ** 2 for w, r in zip(weights, rec_uni)) / len(weights))

print("4-BIT QUANTIZATION RECONSTRUCTION ERROR ON GAUSSIAN LLM WEIGHTS (N=2,048):")
print(f"  • Uniform INT4 RMSE:        {rmse_uni:.6f}")
print(f"  • QLoRA NormalFloat4 RMSE:  {rmse_nf4:.6f} ({100*(1 - rmse_nf4/rmse_uni):.1f}% lower quantization error!)")

Frequently Asked Staff LLM Interview Questions (Module 6)

How should I choose LoRA rank (r) and alpha (α), and which layers should I target? ▸

The QLoRA paper proved that targeting ALL linear layers in the Transformer block (q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj) is far more important than increasing rank r on attention alone. For most instruction/tool-calling tasks, r = 16 or r = 32 with α = 2r (e.g. α = 32 or 64) and lora_dropout = 0.05 is optimal. For large domain shifts or continued pre-training, use r = 64–128 with rank-stabilized rsLoRA scaling (α / sqrt(r)).

What is 4-bit NormalFloat (NF4) in QLoRA and why is it better than standard uniform INT4? ▸

Pre-trained neural network weights follow a zero-centered normal (Gaussian) distribution N(0, σ²). Standard uniform INT4 spaces its 16 quantization bins evenly across [-max, +max], wasting bins in the sparse tails and losing precision near zero where 70%+ of weights live. NF4 spaces its 16 quantization levels at equal-area quantiles of the standard normal distribution, making it information-theoretically optimal for Gaussian weights.

What is DoRA (Weight-Decomposed Low-Rank Adaptation) and when does it beat standard LoRA? ▸

DoRA (ICML 2024) decomposes pre-trained weights into a trainable scalar magnitude vector m ∈ ℝ^(1×k) and a directional matrix V = W_0 + BA normalized column-wise: W_DoRA = m · (W_0 + BA) / ||W_0 + BA||_c. This decoupled magnitude-direction update closely mirrors full fine-tuning gradient dynamics and outperforms standard LoRA at low ranks (r = 8 or 16).