Sub topic 1
Choosing an Open-Weight Base Model
This chapter assumes basic Python and PyTorch, a high-level view of transformers, and basic matrix multiplication and rank. You should also know how to run a Hugging Face model for inference.
Prerequisites
You need a task definition, representative examples, and a deployment target. Decide whether the model must run locally, on one GPU, or through a hosted service. Check the model license before training or redistributing it. “Open-weight” means that the model parameters are available to download. It does not necessarily mean that the license permits every commercial or research use.
Choose a base model whose language, context length, tokenizer, and instruction style match your task. A smaller model may be cheaper to train and serve, while a larger model may require fewer examples to reach the desired quality.
Why Full Fine-Tuning Is Expensive
Full fine-tuning updates every parameter in the model. Training must store the parameters, gradients, optimizer states, and temporary activations. For Adam-style optimization, optimizer states can use several times the memory of the parameters. Checkpoints also contain the entire model, so each task produces a large copy.
LoRA reduces this cost by freezing the original model and learning a small update beside it.
The Low-Rank Idea Behind LoRA
Many task-specific changes do not need an independent value for every entry in a large weight matrix. LoRA approximates the change with two smaller matrices. If the original weight has shape out_features × in_features, choose a much smaller rank r and learn matrices B and A with shapes out_features × r and r × in_features.
How the LoRA Update Works
For a weight matrix W, LoRA uses:
W' = W + (alpha / r) BA
W remains frozen. Only A and B receive gradients. Initializing B to zero makes the adapter initially behave like the base model.
import torch
W = torch.randn(4, 6)
A = torch.randn(2, 6) * 0.01
B = torch.zeros(4, 2)
alpha = 8
r = 2
W_delta = (alpha / r) * (B @ A)
W_prime = W + W_delta
print(W_prime.shape)Rank, Alpha, Dropout, and Target Modules
| Setting | Role | Typical effect |
|---|---|---|
| `r` | Size of the low-rank update | Higher capacity and memory use |
| `alpha` | Scales the update | Larger effective update |
| `dropout` | Drops adapter inputs during training | Can reduce overfitting |
| Target modules | Chooses layers that receive adapters | Controls quality, cost, and behavior |
Common targets are the attention projections q_proj, k_proj, v_proj, and o_proj. Start with a modest rank and inspect held-out results before increasing it.
Exercise
Why does setting B to zero preserve the base model at the start of training?
Show answer
Because the initial update (alpha / r)BA is the zero matrix, so W' equals the frozen W.