Skip to content
ml-recall

Topic notes

Fine-tuning & PEFT

Adapting a pretrained model to a task — full fine-tuning (BERT heads, T5 text-to-text, SFT batches) and parameter-efficient methods such as LoRA, QLoRA, adapters, prefix and prompt tuning.

3-min read AI-checked

Practise 29 questions Take a test

Key ideas

Formulas

Worked example

A 7B model with 32 layers and dmodel=4096d_{model} = 4096; LoRA with r=8r = 8 on WqW_q and WvW_v:

In code

import torch
import torch.nn as nn

class LoRALinear(nn.Module):
    def __init__(self, base, r=8, alpha=16):
        super().__init__()
        self.base = base.requires_grad_(False)                     # frozen W0 and bias
        self.A = nn.Parameter(torch.randn(r, base.in_features) * 0.01)
        self.B = nn.Parameter(torch.zeros(base.out_features, r))   # B = 0, so BA = 0 at start
        self.s = alpha / r
    def forward(self, x):
        return self.base(x) + self.s * (x @ self.A.T @ self.B.T)
layer, x = LoRALinear(nn.Linear(512, 512)), torch.randn(4, 512)
print(torch.equal(layer(x), layer.base(x)))                        # True: starts at W0
print(sum(p.numel() for p in layer.parameters() if p.requires_grad))  # 8192 = 8 * (512 + 512)

Common pitfalls

References

  1. Dive into Deep Learning — Sec. 11.9.1.2 Fine-Tuning BERT, 11.9.2.2 Fine-Tuning T5
  2. Hugging Face LLM Course — Ch. 3 Fine-tuning a pretrained model, Processing the data (Dynamic padding)
  3. Hu et al. (2021), LoRA: Low-Rank Adaptation of Large Language Models — Sec. 3 Aren't Existing Solutions Good Enough? (adapter latency), 4.1 Low-Rank-Parametrized Update Matrices, 4.2 Applying LoRA to Transformer
  4. Dettmers et al. (2023), QLoRA: Efficient Finetuning of Quantized LLMs — Sec. 3 QLoRA Finetuning (4-bit NormalFloat, Double Quantization, Paged Optimizers); Sec. 4 QLoRA vs. Standard Finetuning
  5. Houlsby et al. (2019), Parameter-Efficient Transfer Learning for NLP — Abstract and Sec. 1 Introduction (frozen base, no forgetting); Sec. 2.1 Instantiation for Transformer Networks (Figure 2)
  6. Lester et al. (2021), The Power of Scale for Parameter-Efficient Prompt Tuning — Sec. 2 Prompt Tuning, 3.1 Closing the Gap, 4 Comparison to Similar Approaches
  7. PyTorch documentation: torch.nn.CrossEntropyLoss — Parameters, ignore_index (default -100)
  8. Wikipedia: Catastrophic interference — Introduction; Proposed solutions (Rehearsal, Elastic weight consolidation)