Training & Fine-tuning
Open up the optimizer, the learning-rate schedule and the data pipeline that turn a random model into a useful one, then adapt a trained model with fine-tuning and LoRA without breaking what it knows. Every update rule is computed by hand and checked against PyTorch, and every memory bill is arithmetic you can redo.
- Advanced
- 4 units, 12 lessons, 155 exercises
- Python with PyTorch
- Builds on AI Engineering: NumPy & PyTorch, How LLMs Work
Unit 01 · 3 lessons
How weights move
Compute every optimizer step by hand, then read a loss curve
- 01SGD and momentum
Noisy gradients, and a velocity that remembers them
- 02Adam and AdamW
A step size per weight, and weight decay done right
- BOSSRead the loss curve
Warmup, decay, clipping, and diagnosing a run from its log
Read the unit guide
The gradient says which way is downhill. The optimizer decides how far to go, and that decision matters as much as the gradient. Snippets in this roadmap assume import math, import torch, import torch.nn as nn, import torch.nn.functional as F and from torch import optim.
A mini-batch gradient is a noisy estimate of the true one: right on average, off every time. The noise falls with the square root of the batch size, so four times the batch buys half the noise. Momentum keeps a velocity, v = 0.9 * v + g, and steps along it. Gradients that agree pile up (a steady gradient is multiplied by up to 10), gradients that flip sign cancel. Adding momentum therefore acts like a larger learning rate.
Adam keeps two running averages per weight: m of the gradient and v of its square, each corrected for having started at zero. The step is lr * m_hat / sqrt(v_hat), so every weight moves about lr per step whatever the scale of its gradients. Under Adam the learning rate is a distance, not a multiplier.
Weight decay shrinks every weight a little per step. Put inside the gradient, Adam's division swallows it. AdamW applies it to the weight directly, w -= lr * decay * w, so every weight decays by the same fraction. That is the only difference between the two.
A schedule computes the learning rate from the step: warm up from zero over the first steps, while the gradients are wild and the averages are young, then decay (in a straight line or along a cosine) so the end of training settles. Measure decay progress from the end of the warmup, not from step zero.
Clipping caps the norm of the whole gradient, keeping its direction, and goes between backward() and step(). Read curves before changing anything: a training loss that climbs to nan is divergence (steps too large), flat from the start means nothing is updating, and training falling while validation rises is overfitting.
Unit 02 · 3 lessons
Data pipelines
Turn text into batches the model learns the right thing from
- 01Examples for a language model
Templates, padding, masks and the labels that are not scored
- 02Batches
Collate, pad to the longest, bucket by length, accumulate
- BOSSThe data is the model
Audit a fine-tuning set before touching a hyperparameter
Read the unit guide
A fine-tuning example for a language model is one token sequence: the prompt followed by the answer you want. Chat models wrap each turn in role markers, special tokens that say who is speaking and where a turn ends. Each model family has its own template, and the text you serve must be formatted exactly like the text you trained on.
The model predicts every next token, but you choose which predictions are scored. Labels are the ids shifted by one, and any position you do not want to learn from gets the label -100, the value PyTorch's cross-entropy skips by default. Mask the prompt (the model need not learn to write the question) and mask the padding (or the loss is flattered by thousands of trivially easy tokens).
A batch must be a rectangle, so short rows are padded and an attention mask marks the real tokens with 1. The collate_fn of a DataLoader builds each batch: pad to the longest row in this batch, not to the model's maximum. Batching rows of similar length (bucketing) cuts the padding further, but keep the batch order shuffled. Snippets assume pad_sequence and DataLoader are imported.
When the batch you want does not fit in memory, accumulate: call backward() on several small batches, each loss divided by their number, and step once. The gradient equals the big batch's, the memory is the small batch's, and the effective batch size is the product.
Most failed fine-tunes are data problems. Remove duplicates and near-copies before splitting, split by source so one conversation never lands on both sides, and check that no eval example is in the training set: an eval set that overlaps training measures memory. Look at the label mix, read fifty random examples yourself, and remember that a public benchmark may already be inside the base model.
More data helps until the learning curve flattens. After that, fix quality, not quantity.
Unit 03 · 3 lessons
Fine-tuning
Adapt a pretrained model without breaking it or your memory budget
- 01What to train
Forgetting, small learning rates, and how much to unfreeze
- 02LoRA
Learn a low-rank change beside a frozen weight matrix
- BOSSFine-tune on one GPU
Work out the memory bill of training, then cut it line by line
Read the unit guide
Fine-tuning starts from weights that already work and moves them toward a new task. Nothing in the new loss protects the old abilities, so weights drift and the model forgets: catastrophic forgetting. The defences are small steps (a learning rate far below a from-scratch one), few of them, freezing what you want kept, and mixing some old-task data into the new.
How much to train is a dial. Train only a new head when data is scarce and the task is close. Unfreeze the top layers when you have more data or the task has shifted. Train everything only with plenty of data. A frozen layer still runs in the forward pass; it just never changes, and it needs no gradient and no optimizer state.
LoRA freezes a weight matrix W and learns its change as a product of two small matrices: A of shape (r, inputs) and B of shape (outputs, r). The layer computes W x + (alpha / r) * B A x. Trainable values per matrix: r × (inputs + outputs), often around 1% of the original. A starts random and B starts at zero, so the model begins exactly as pretrained. After training, W + (alpha / r) * B A can be merged into one ordinary matrix, or the adapter kept apart and swapped per task.
Training memory is a bill with four lines: weights, gradients (one per trainable weight), optimizer state (two per trainable weight for Adam) and activations (kept from the forward pass for the backward one, growing with batch size and sequence length). Full fine-tuning in 32-bit floats costs 16 bytes per parameter before activations.
Each trick cuts one line and costs something. Freezing or LoRA removes gradients and optimizer state for the frozen part, and limits what can change. Half precision halves a line and loses numeric range. A base quantised to 4 bits costs half a byte per weight, must stay frozen, and loses a little quality. Gradient checkpointing drops stored activations and recomputes them, paying in time.
Unit 04 · 3 lessons
Doing it for real
Decide when to train, measure what you trained, and run it safely
- 01Prompt, retrieve or fine-tune
Pick the cheapest tool that closes the gap
- 02Evaluating a fine-tune
Held-out sets, the metric that matters, and catching forgetting
- BOSSA training run, start to finish
Seeds, checkpoints, early stopping and a post-mortem
Read the unit guide
Try the cheap tools first. A prompt fixes an instruction gap: say what you want and show examples. Retrieval fixes a knowledge gap: paste the current document into the prompt. Fine-tuning fixes a behaviour gap: a format, a tone or a narrow skill the model should produce without being told every time. Fine-tuning does not reliably store facts and cannot keep up with facts that change.
Good reasons to fine-tune: thousands of examples of a narrow task, a long prompt you are paying for on every request, a style that drifts under prompting. Bad reasons: missing facts, a live record the model should look up, or fifty examples.
Build the eval set before you train and never train on it. Training loss only says the model fits what it saw. Eval loss is a proxy too: exp(loss) is perplexity, the number of equally likely tokens the model is choosing among. Rank checkpoints by the metric users care about, and score the base model on the same cases.
A fine-tune can gain on its task and lose everywhere else, so keep a second, general set to catch forgetting. Small eval sets are noisy: on 50 examples one example is two points. Every choice made by looking at the eval score leaks a little of it, so hold a test set back for the end.
A run you can trust: fix the seeds, overfit one tiny batch first, log loss, learning rate and gradient norm, and save checkpoints as you go. To resume exactly, a checkpoint needs the model, the optimizer state (Adam's averages), the scheduler's position and the step count. Stop when the eval loss has not improved for a set number of evaluations, and ship the best checkpoint, not the last.
Learn Training & Fine-tuning on your phone.
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.