Exercises
Twenty-two exercises across the whole course, most of them small enough to do on paper. Try each one before opening the answer. Five answers include a short NumPy program that checks the hand computation; you can edit and run it.
| # | Exercise | Practises |
|---|---|---|
| 1 | Match the project to the strategy | Introduction, Choosing a Strategy |
| 2 | Initialisation scales | Training from Scratch |
| 3 | When transfer hurts | Transfer Learning |
| 4 | What stage 1 and stage 2 train | Transfer Learning with ResNet-18, Frozen and Partial Fine-Tuning |
| 5 | A leak in feature extraction | Feature Extraction |
| 6 | Mean pooling with padding | Sentence Embeddings |
| 7 | Warm-up and decay | Fine-Tuning Recipe |
| 8 | An EWC penalty | Catastrophic Forgetting |
| 9 | Memory for full fine-tuning and LoRA | Full vs PEFT, LoRA with PEFT |
| 10 | Counting LoRA parameters | LoRA |
| 11 | What 4 bits cost | QLoRA |
| 12 | Adapter or soft prompt? | Adapters and Prompt Tuning |
| 13 | Choose a pretext task | Self-Supervised Pretraining |
| 14 | NT-Xent by hand | Contrastive Learning |
| 15 | Which pseudo-labels are kept? | Pseudo-Labelling |
| 16 | A mean teacher | Consistency and Teacher-Student |
| 17 | Three query scores | Active Learning Strategies, The Labelling Loop |
| 18 | Prequential accuracy | Online Learning |
| 19 | Page-Hinkley on an error stream | Concept Drift |
| 20 | Reservoir and rollback | Replay and Rollback |
| 21 | All-reduce and the bubble | Data Parallelism, Model Parallelism |
| 22 | A checkpoint that resumes | DDP and Checkpointing |
Exercise 1: Match the project to the strategy
Pick a first strategy for each project and say what you would add.
- 400,000 labelled loan applications with 60 numeric and categorical columns.
- 80 labelled photos of rare insects, with an ImageNet backbone available.
- A 13-billion-parameter language model to adapt to legal question answering with 3,000 examples, on one 24 GB GPU.
- A click-through model on a stream of 2 million events a day whose patterns change every few weeks.
- 2 million unlabelled audio recordings of machines, 300 labelled as faulty or not, no public model for this sound.
Answer
- Training from scratch: gradient-boosted trees or a small MLP on tabular data; pretrained backbones do not exist for such tables.
- Feature extraction with a linear head; then partial fine-tuning if it falls short, and active learning to spend any labelling budget.
- QLoRA: the 16-bit base alone is 26 GB, too much for 24 GB, while the 4-bit base is about 6.5 GB; LoRA adapters train on top.
- Online learning with
partial_fit, drift detection on the error stream, a replay buffer and a rollback guard. - Self-supervised pretraining on the 2 million recordings, then fine-tune (or extract features) with the 300 labels; add pseudo-labelling.
Exercise 2: Initialisation scales
A layer maps 784 inputs to 256 units. What standard deviation does Xavier initialisation, , give for a tanh layer, and He initialisation, , for a ReLU layer? Why not initialise every weight to 0?
Answer
Xavier: . He: . With all weights 0, every hidden unit computes the same output and receives the same gradient, so the units stay identical forever; random weights break that symmetry, and the variance scale keeps activations from shrinking or exploding from layer to layer.
Exercise 3: When transfer hurts
A team pretrains a CNN on satellite images of fields and transfers it to dermatology photos. With 500 labelled photos, the transferred model scores 0.71 on validation, and the same CNN trained from scratch on the 500 photos scores 0.74. Name the effect, give two likely reasons, and say what to try.
Answer
Negative transfer: the pretrained starting point is worse than random. The source domain is far from the target (top-down textures of crops versus close-up skin), and the higher layers encode source-specific features that the small target set cannot unlearn. Try transferring only the lower layers (re-initialise the top), a backbone pretrained on a closer domain (or on generic photos), self-supervised pretraining on unlabelled skin images, and always keep the from-scratch baseline in the comparison.
Exercise 4: What stage 1 and stage 2 train
In the ResNet-18 lesson, stage 1 replaced the 1000-class fc layer by nn.Linear(512, 6) and froze everything else; stage 2 also unfroze layer4. The printed trainable counts were 3,078 and 8,396,806. Check the first number, find the number of parameters in layer4, and say why stage 2 should use a smaller learning rate for layer4 than for the head.
Answer
. layer4 has parameters, about three quarters of the whole network (11,179,590). The head starts from random weights and must move far; layer4 already holds useful features and should only be nudged, so a large learning rate there would destroy what pretraining learned (discriminative learning rates, as in partial fine-tuning).
Exercise 5: A leak in feature extraction
A notebook embeds all 5,000 images with a frozen backbone, fits PCA to 50 components on all 5,000 embeddings, then runs 5-fold cross-validation of logistic regression on the PCA features. Is the CV score honest? Would it be honest without the PCA step?
Answer
PCA was fitted on all rows, including each fold's validation rows, so the CV score is slightly optimistic: a (mild, unsupervised) leak. Put PCA inside the pipeline, make_pipeline(PCA(50), LogisticRegression()), so it is refitted per fold. Embedding all images once is fine: the backbone is frozen and was never fitted on these images, so it is a fixed function like a hand-written feature, and computing it for every row leaks nothing.
Exercise 6: Mean pooling with padding
A sentence has three real tokens with vectors , , , padded with a fourth token , attention mask . Compute the masked mean-pooled embedding and its cosine similarity with . What goes wrong if the mask is ignored?
Answer
. Then , , , so the cosine is . Ignoring the mask averages in the padding vector, , so the embedding depends on how much padding the batch happened to need.
import numpy as np
H = np.array([[1.0, 0.0], [3.0, 4.0], [0.0, 2.0], [9.0, 9.0]]) # token vectors; the last one is padding
mask = np.array([1, 1, 1, 0])
e1 = (H * mask[:, None]).sum(0) / mask.sum() # mean over real tokens only
e2 = np.array([2.0, 1.0])
cos = e1 @ e2 / (np.linalg.norm(e1) * np.linalg.norm(e2))
print("mean-pooled e1:", e1.round(4), "| with the padding token:", H.mean(0).round(4))
print(f"cosine(e1, e2) = {cos:.4f}")mean-pooled e1: [1.3333 2. ] | with the padding token: [3.25 3.75]
cosine(e1, e2) = 0.8682
Exercise 7: Warm-up and decay
A fine-tuning run has , warm-up steps and steps in total. Compute the learning rate at steps 50, 550 and 775 for linear decay and for cosine decay after the warm-up.
Answer
Step 50 is in the warm-up: for both. Step 550 is halfway through the decay: linear gives , cosine gives . At step 775 (three quarters of the decay) linear gives and cosine : cosine stays high longer at first, then falls faster.
import math
def lr(t, eta_max=2e-5, warmup=100, total=1000, kind="linear"):
if t < warmup:
return eta_max * t / warmup
if kind == "linear":
return eta_max * (total - t) / (total - warmup)
return eta_max / 2 * (1 + math.cos(math.pi * (t - warmup) / (total - warmup)))
for t in [50, 100, 550, 775, 1000]:
print(f"step {t:4d}: linear {lr(t):.2e} cosine {lr(t, kind='cosine'):.2e}")step 50: linear 1.00e-05 cosine 1.00e-05
step 100: linear 2.00e-05 cosine 2.00e-05
step 550: linear 1.00e-05 cosine 1.00e-05
step 775: linear 5.00e-06 cosine 2.93e-06
step 1000: linear 0.00e+00 cosine 0.00e+00
Exercise 8: An EWC penalty
After task A the weights are with Fisher information . During task B the weights move to . Compute the EWC penalty with , and explain which weight EWC protects.
Answer
. The first weight moved only 0.5 but costs 1.0, because task A's loss is sensitive to it (); the second moved 2 and costs only 0.04. EWC lets unimportant weights move freely and holds important ones near their task-A values.
Exercise 9: Memory for full fine-tuning and LoRA
Using 16 bytes per parameter for full fine-tuning with AdamW in mixed precision, and 2 bytes per frozen 16-bit parameter, estimate the memory (weights, gradients, optimiser state; no activations) for a model of 7 billion parameters with (a) full fine-tuning and (b) LoRA training 20 million adapter parameters. How much does each task's saved result take?
Answer
(a) GB, more than one 80 GB GPU. (b) frozen base GB plus GB for the adapters: about 14.3 GB. Saved per task: a full 16-bit copy is 14 GB; the adapter is bytes MB in 16-bit. (PEFT overview counts about 108 GB for a typical "7B" model, which has slightly fewer than 7 billion parameters.)
Exercise 10: Counting LoRA parameters
A transformer has 32 layers with query and value projections. How many parameters does LoRA with on both add, and what fraction of the 2 × 32 adapted matrices is that? With , what is the scale on , and why does the model start out unchanged?
Answer
Per matrix ; for matrices, . The matrices themselves hold weights, so LoRA trains 0.39 % of them. The scale is . is initialised to zero, so and exactly at the start: training begins from the pretrained model.
Exercise 11: What 4 bits cost
QLoRA stores the frozen base in 4-bit codes, one 32-bit scale per block of 64 weights. How many bits per weight is that, and how large is a 7-billion-parameter base? Why are blocks used instead of one scale per matrix?
Answer
bits per weight; GB (double quantization, which quantizes the scales themselves, brings the overhead down to about 0.127 bits). With one absmax scale per matrix a single outlier sets the scale, and almost every ordinary weight falls on the few code values near zero; per-block scales keep an outlier's damage within its 64 weights.
Exercise 12: Adapter or soft prompt?
A BERT-base model (, 12 layers) gets (a) one bottleneck adapter with bottleneck size 64 in each layer, or (b) prompt tuning with 20 virtual tokens. Count the trainable parameters of each (ignore the head). Which can be merged into the weights after training?
Answer
(a) Per adapter: down , up , total ; times 12 layers, . (b) . Neither can be merged: an adapter contains a non-linearity between its two layers, and a soft prompt lengthens the input. (LoRA's update is linear and can be added to .) Both add inference cost; prompt tuning's is longer sequences.
Exercise 13: Choose a pretext task
For each data set, propose a self-supervised pretext task and say what it forces the network to learn: (a) server log lines, (b) chest X-rays, (c) hourly electricity consumption of 10,000 meters.
Answer
(a) Masked token prediction: hide 15 % of the tokens of each log line and predict them; the model learns the grammar of log messages and which fields go together. (b) Contrastive learning (two augmented crops of the same X-ray must match) or masked patch reconstruction; it learns anatomy-level features. Avoid augmentations that change the diagnosis (heavy colour changes are harmless, flipping left and right is not, since the heart is on one side). (c) Predict the next day from the past week, or masked spans of the series; it learns daily and weekly patterns. In every case, check by a downstream evaluation (linear probe) that the pretext task helps: rotation prediction, for example, can be useless.
Exercise 14: NT-Xent by hand
Two inputs give four unit-length views: and from input A, and from input B. With , compute the loss of view 0, then check the mean NT-Xent loss over all four views with the program.
Answer
The similarities of to are ; divided by : . So
Views 1 and 2 have losses 0.627 each, because their negatives are closer (); the mean is 0.430.
import numpy as np
# 2 inputs -> 4 views: z0, z1 are views of input A; z2, z3 views of input B (unit vectors)
Z = np.array([[1.0, 0.0], [0.8, 0.6], [0.0, 1.0], [-0.6, 0.8]])
tau = 0.5
S = Z @ Z.T / tau # cosine similarities / tau
np.fill_diagonal(S, -np.inf) # k != i
pos = {0: 1, 1: 0, 2: 3, 3: 2}
losses = [-(S[i, pos[i]] - np.log(np.exp(S[i]).sum())) for i in range(4)]
print("similarities of z0:", (Z @ Z.T)[0].round(2))
print("loss per view:", np.round(losses, 4))
print(f"NT-Xent (mean over the 4 views): {np.mean(losses):.4f}")similarities of z0: [ 1. 0.8 0. -0.6]
loss per view: [0.2333 0.6271 0.6271 0.2333]
NT-Xent (mean over the 4 views): 0.4302
Exercise 15: Which pseudo-labels are kept?
A classifier gives these probabilities for five unlabelled examples (classes 0, 1, 2): , , , , . Which are added with threshold , and with which labels? What is the danger of lowering to 0.5?
Answer
Example 1 with label 0 and example 4 with label 2; example 3 (0.88) just misses. At , example 2 (0.60) and example 3 join too. The danger is confirmation bias: a wrong pseudo-label becomes a training label, the model fits it, grows more confident in the mistake, and spreads it to similar examples. Keep the threshold high, check pseudo-label accuracy on a labelled validation set, and stop when it falls.
Exercise 16: A mean teacher
A student weight is 0.0 at the start and then takes the values 1.0, 1.0, 1.0 after three steps. The teacher starts equal to the student and follows with . What is the teacher weight after each step? Why train the student to agree with the teacher rather than with itself?
Answer
, then , then (). The teacher is a smoothed average of recent students, so its predictions are more stable and usually more accurate than any single student's; consistency targets from it are less noisy than the student's own, which would only reinforce the student's current mistakes.
Exercise 17: Three query scores
A 3-class model predicts , , . Which example does least-confidence sampling query, which does margin sampling query, and which does entropy sampling query? Then: why are the 50 top-scoring examples of a batch often a poor batch?
Answer
Least confidence : 0.50, 0.60, 0.30, so . Margin : 0.05, 0.10, 0.55, so , the example torn between two classes. Entropy: 0.856, 1.089, 0.819, so , spread over all three. Margin looks only at the top two classes, entropy at all of them. In a batch, the top-scoring examples are often near-duplicates from the same uncertain region, so labelling all 50 teaches little more than labelling a few; mix uncertainty with diversity (clustering, or a distance penalty), as in the labelling loop.
import numpy as np
P = np.array([[0.50, 0.45, 0.05],
[0.40, 0.30, 0.30],
[0.70, 0.15, 0.15]])
top2 = np.sort(P, axis=1)[:, ::-1][:, :2]
least_conf = 1 - top2[:, 0]
margin = top2[:, 0] - top2[:, 1]
entropy = -(P * np.log(P)).sum(1)
for i in range(3):
print(f"x{i + 1}: least confidence {least_conf[i]:.2f} margin {margin[i]:.2f} entropy {entropy[i]:.3f}")
print("query by least confidence:", f"x{least_conf.argmax() + 1}",
"| by margin:", f"x{margin.argmin() + 1}", "| by entropy:", f"x{entropy.argmax() + 1}")x1: least confidence 0.50 margin 0.05 entropy 0.856
x2: least confidence 0.60 margin 0.10 entropy 1.089
x3: least confidence 0.30 margin 0.55 entropy 0.819
query by least confidence: x2 | by margin: x1 | by entropy: x2
Exercise 18: Prequential accuracy
An online classifier sees a stream of 8 examples. Before learning from each, its prediction is right on examples 1, 2, 4, 5, 6, 8 and wrong on 3 and 7. What is the prequential accuracy after 4 and after 8 examples? Why is it not optimistic, although every example is also used for training?
Answer
After 4: 3 right out of 4, 0.75. After 8: 6 out of 8, 0.75. Each example is predicted by the model before it learns from that example (test-then-train), so every prediction is on unseen data. It is an average over the whole history, though; a fading factor or a sliding window shows the current accuracy when the stream drifts.
Exercise 19: Page-Hinkley on an error stream
An error stream (1 = wrong) is 0, 0, 1, 0, 0, 1, 1, 1, 1, 1. Run Page-Hinkley with and , using the running mean that includes the current value. At which time does it raise the alarm? What happens with ?
Answer
The statistic jumps at each error and slowly decays on correct predictions; it first exceeds 1.5 at (1.655), after the third error in a row. A larger gives fewer false alarms but a later detection: with it would need more errors. The trade-off between detection delay and false alarms is the subject of the drift lesson.
errors = [0, 0, 1, 0, 0, 1, 1, 1, 1, 1] # 1 = the model got this example wrong
delta, lam = 0.05, 1.5
n = mean = m = m_min = 0.0
for t, x in enumerate(errors, 1):
n += 1
mean += (x - mean) / n # running mean including x_t
m += x - mean - delta
m_min = min(m_min, m)
flag = " <- drift" if m - m_min > lam else ""
print(f"t={t:2d} x={x} mean={mean:.3f} m={m:+.3f} m_min={m_min:+.3f} m-m_min={m - m_min:.3f}{flag}")
if flag:
breakt= 1 x=0 mean=0.000 m=-0.050 m_min=-0.050 m-m_min=0.000
t= 2 x=0 mean=0.000 m=-0.100 m_min=-0.100 m-m_min=0.000
t= 3 x=1 mean=0.333 m=+0.517 m_min=-0.100 m-m_min=0.617
t= 4 x=0 mean=0.250 m=+0.217 m_min=-0.100 m-m_min=0.317
t= 5 x=0 mean=0.200 m=-0.033 m_min=-0.100 m-m_min=0.067
t= 6 x=1 mean=0.333 m=+0.583 m_min=-0.100 m-m_min=0.683
t= 7 x=1 mean=0.429 m=+1.105 m_min=-0.100 m-m_min=1.205
t= 8 x=1 mean=0.500 m=+1.555 m_min=-0.100 m-m_min=1.655 <- drift
Exercise 20: Reservoir and rollback
(a) A reservoir buffer of examples is filled from a stream of . What is the probability that the 1,000th example is in the buffer at the end, and that the last one is? (b) An online model's accuracy on a fixed guard set is 0.91 before a batch update and 0.78 after. What should the system do, and what must it have kept to do it?
Answer
(a) Both : reservoir sampling keeps every example with the same probability, whatever its position. (b) Reject the update and roll back to the previous version: a drop of 0.13 on the guard set is far beyond normal noise and points to a bad batch (corrupted labels, a broken feature). The system must keep versioned model snapshots (weights and optimiser state), the guard set itself, and a log of which batch caused the drop so it can be inspected.
Exercise 21: All-reduce and the bubble
(a) Eight workers all-reduce a 2 GB gradient with a ring. How much does each send per step? (b) A pipeline has 6 stages. How many micro-batches keep the bubble at or below 20 %? (c) In a tensor-parallel MLP, why is the first matrix split by columns and the second by rows?
Answer
(a) GB per worker per step. (b) means , so . (c) Column-splitting the first matrix gives each device complete hidden units, so the element-wise activation needs no communication; row-splitting the second matrix then gives partial outputs that one all-reduce adds up.
Exercise 22: A checkpoint that resumes
A colleague's checkpoint contains only model.state_dict() (saved from the DDP wrapper) and the epoch number. Training used AdamW, a cosine schedule, dropout and a DistributedSampler. List what is missing or wrong, and what the resumed run will do differently.
Answer
Missing: the optimiser state (Adam's moments and step count, so the first resumed steps behave like a fresh Adam), the scheduler state (the learning rate jumps back to the start of the schedule unless it is recomputed from the step), every rank's RNG state (different dropout masks) and the sampler epoch, unless set_epoch is called with the restored epoch (otherwise the shuffles repeat). Wrong: the weights were saved from the wrapper, so every key starts with module.; save model.module.state_dict(). Also write atomically (temporary file, then os.replace) from rank 0 only. The resumed run trains, but it is a different run and its losses will not match the uninterrupted one.
Test yourself
LoRA with adapts a matrix. How many trainable parameters does it add?
- 4,096
- 8,192
- 1,048,576
- 4,194,304
Which probability vector does margin sampling query first?
A reservoir of 100 examples is filled from a stream of 50,000. What is the chance that the very first example is still in it at the end?
- 1
- 0.5
- 0.002
- 0
A pipeline has 4 stages and 12 micro-batches. What fraction of the time is each stage idle?
- 0.2
- 0.25
- 0.33
- 0.75
Which part of a checkpoint makes the resumed run use the same dropout masks and shuffles as the uninterrupted one?
- The model weights
- The optimiser state
- The RNG states (per rank) and the epoch number for the sampler
- The learning-rate scheduler