TExcelTAD

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.

  1. 400,000 labelled loan applications with 60 numeric and categorical columns.
  2. 80 labelled photos of rare insects, with an ImageNet backbone available.
  3. A 13-billion-parameter language model to adapt to legal question answering with 3,000 examples, on one 24 GB GPU.
  4. A click-through model on a stream of 2 million events a day whose patterns change every few weeks.
  5. 2 million unlabelled audio recordings of machines, 300 labelled as faulty or not, no public model for this sound.
Answer
  1. Training from scratch: gradient-boosted trees or a small MLP on tabular data; pretrained backbones do not exist for such tables.
  2. Feature extraction with a linear head; then partial fine-tuning if it falls short, and active learning to spend any labelling budget.
  3. 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.
  4. Online learning with partial_fit, drift detection on the error stream, a replay buffer and a rollback guard.
  5. 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, N(0,1/nin)\mathcal{N}(0, 1/n_{in}), give for a tanh layer, and He initialisation, N(0,2/nin)\mathcal{N}(0, 2/n_{in}), for a ReLU layer? Why not initialise every weight to 0?

Answer

Xavier: 1/784=1/28≈0.0357\sqrt{1/784} = 1/28 \approx 0.0357. He: 2/784≈0.0505\sqrt{2/784} \approx 0.0505. 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

512×6+6=3078512 \times 6 + 6 = 3078. layer4 has 8,396,806−3,078=8,393,7288{,}396{,}806 - 3{,}078 = 8{,}393{,}728 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 (1,0)(1, 0), (3,4)(3, 4), (0,2)(0, 2), padded with a fourth token (9,9)(9, 9), attention mask (1,1,1,0)(1, 1, 1, 0). Compute the masked mean-pooled embedding e1\mathbf{e}_1 and its cosine similarity with e2=(2,1)\mathbf{e}_2 = (2, 1). What goes wrong if the mask is ignored?

Answer

e1=13((1,0)+(3,4)+(0,2))=(1.333,2)\mathbf{e}_1 = \frac{1}{3}\big((1, 0) + (3, 4) + (0, 2)\big) = (1.333, 2). Then e1⋅e2=2.667+2=4.667\mathbf{e}_1 \cdot \mathbf{e}_2 = 2.667 + 2 = 4.667, ∥e1∥=2.404\lVert \mathbf{e}_1 \rVert = 2.404, ∥e2∥=2.236\lVert \mathbf{e}_2 \rVert = 2.236, so the cosine is 4.667/5.375≈0.8684.667 / 5.375 \approx 0.868. Ignoring the mask averages in the padding vector, (3.25,3.75)(3.25, 3.75), so the embedding depends on how much padding the batch happened to need.

python · try it yourself
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 ηmax=2⋅10−5\eta_{max} = 2 \cdot 10^{-5}, Tw=100T_w = 100 warm-up steps and T=1000T = 1000 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: 2⋅10−5⋅50/100=10−52 \cdot 10^{-5} \cdot 50/100 = 10^{-5} for both. Step 550 is halfway through the decay: linear gives 2⋅10−5⋅450/900=10−52 \cdot 10^{-5} \cdot 450/900 = 10^{-5}, cosine gives 10−5(1+cos⁡(π/2))=10−510^{-5}(1 + \cos(\pi/2)) = 10^{-5}. At step 775 (three quarters of the decay) linear gives 5⋅10−65 \cdot 10^{-6} and cosine 10−5(1+cos⁡(3π/4))≈2.93⋅10−610^{-5}(1 + \cos(3\pi/4)) \approx 2.93 \cdot 10^{-6}: cosine stays high longer at first, then falls faster.

python · try it yourself
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 θA=(1,1)\theta_A = (1, 1) with Fisher information F=(4,0.01)F = (4, 0.01). During task B the weights move to θ=(1.5,3)\theta = (1.5, 3). Compute the EWC penalty λ2∑iFi(θi−θA,i)2\frac{\lambda}{2} \sum_i F_i (\theta_i - \theta_{A,i})^2 with λ=1\lambda = 1, and explain which weight EWC protects.

Answer

12(4⋅0.52+0.01⋅22)=12(1+0.04)=0.52\frac{1}{2}\big(4 \cdot 0.5^2 + 0.01 \cdot 2^2\big) = \frac{1}{2}(1 + 0.04) = 0.52. The first weight moved only 0.5 but costs 1.0, because task A's loss is sensitive to it (F1=4F_1 = 4); 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) 7×109×16=1127 \times 10^9 \times 16 = 112 GB, more than one 80 GB GPU. (b) frozen base 7×109×2=147 \times 10^9 \times 2 = 14 GB plus 20×106×16=0.3220 \times 10^6 \times 16 = 0.32 GB for the adapters: about 14.3 GB. Saved per task: a full 16-bit copy is 14 GB; the adapter is 20×106×220 \times 10^6 \times 2 bytes =40= 40 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 4096×40964096 \times 4096 query and value projections. How many parameters does LoRA with r=8r = 8 on both add, and what fraction of the 2 × 32 adapted matrices is that? With α=16\alpha = 16, what is the scale on BABA, and why does the model start out unchanged?

Answer

Per matrix r(din+dout)=8×8192=65,536r(d_{in} + d_{out}) = 8 \times 8192 = 65{,}536; for 2×32=642 \times 32 = 64 matrices, 4,194,3044{,}194{,}304. The matrices themselves hold 64×40962≈1.07×10964 \times 4096^2 \approx 1.07 \times 10^9 weights, so LoRA trains 0.39 % of them. The scale is α/r=2\alpha / r = 2. BB is initialised to zero, so BA=0BA = 0 and h=W0x\mathbf{h} = W_0\mathbf{x} 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

4+32/64=4.54 + 32/64 = 4.5 bits per weight; 7×109×4.5/8≈3.97 \times 10^9 \times 4.5 / 8 \approx 3.9 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 (d=768d = 768, 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 768×64+64768 \times 64 + 64, up 64×768+76864 \times 768 + 768, total 99,13699{,}136; times 12 layers, 1,189,6321{,}189{,}632. (b) 20×768=15,36020 \times 768 = 15{,}360. Neither can be merged: an adapter contains a non-linearity between its two layers, and a soft prompt lengthens the input. (LoRA's update BABA is linear and can be added to W0W_0.) 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: z0=(1,0)\mathbf{z}_0 = (1, 0) and z1=(0.8,0.6)\mathbf{z}_1 = (0.8, 0.6) from input A, z2=(0,1)\mathbf{z}_2 = (0, 1) and z3=(−0.6,0.8)\mathbf{z}_3 = (-0.6, 0.8) from input B. With τ=0.5\tau = 0.5, compute the loss ℓ0,1\ell_{0,1} of view 0, then check the mean NT-Xent loss over all four views with the program.

Answer

The similarities of z0\mathbf{z}_0 to z1,z2,z3\mathbf{z}_1, \mathbf{z}_2, \mathbf{z}_3 are 0.8,0,−0.60.8, 0, -0.6; divided by τ\tau: 1.6,0,−1.21.6, 0, -1.2. So

ℓ0,1=−log⁡e1.6e1.6+e0+e−1.2=−1.6+log⁡(4.953+1+0.301)≈0.233\ell_{0,1} = -\log \frac{e^{1.6}}{e^{1.6} + e^{0} + e^{-1.2}} = -1.6 + \log(4.953 + 1 + 0.301) \approx 0.233

Views 1 and 2 have losses 0.627 each, because their negatives are closer (z1⋅z2=0.6\mathbf{z}_1 \cdot \mathbf{z}_2 = 0.6); the mean is 0.430.

python · try it yourself
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): (0.95,0.03,0.02)(0.95, 0.03, 0.02), (0.60,0.35,0.05)(0.60, 0.35, 0.05), (0.10,0.88,0.02)(0.10, 0.88, 0.02), (0.02,0.01,0.97)(0.02, 0.01, 0.97), (0.40,0.30,0.30)(0.40, 0.30, 0.30). Which are added with threshold τ=0.9\tau = 0.9, and with which labels? What is the danger of lowering τ\tau to 0.5?

Answer

Example 1 with label 0 and example 4 with label 2; example 3 (0.88) just misses. At τ=0.5\tau = 0.5, 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 θ′←βθ′+(1−β)θ\theta' \leftarrow \beta \theta' + (1 - \beta)\theta with β=0.9\beta = 0.9. What is the teacher weight after each step? Why train the student to agree with the teacher rather than with itself?

Answer

0.9⋅0+0.1⋅1=0.10.9 \cdot 0 + 0.1 \cdot 1 = 0.1, then 0.9⋅0.1+0.1=0.190.9 \cdot 0.1 + 0.1 = 0.19, then 0.2710.271 (=1−0.93= 1 - 0.9^3). 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 p1=(0.50,0.45,0.05)\mathbf{p}_1 = (0.50, 0.45, 0.05), p2=(0.40,0.30,0.30)\mathbf{p}_2 = (0.40, 0.30, 0.30), p3=(0.70,0.15,0.15)\mathbf{p}_3 = (0.70, 0.15, 0.15). 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 1−pmax1 - p_{max}: 0.50, 0.60, 0.30, so x2\mathbf{x}_2. Margin p(1)−p(2)p_{(1)} - p_{(2)}: 0.05, 0.10, 0.55, so x1\mathbf{x}_1, the example torn between two classes. Entropy: 0.856, 1.089, 0.819, so x2\mathbf{x}_2, 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.

python · try it yourself
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 δ=0.05\delta = 0.05 and λ=1.5\lambda = 1.5, using the running mean that includes the current value. At which time does it raise the alarm? What happens with λ=3\lambda = 3?

Answer

The statistic mT−MTm_T - M_T jumps at each error and slowly decays on correct predictions; it first exceeds 1.5 at t=8t = 8 (1.655), after the third error in a row. A larger λ\lambda gives fewer false alarms but a later detection: with λ=3\lambda = 3 it would need more errors. The trade-off between detection delay and false alarms is the subject of the drift lesson.

python · try it yourself
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:
        break
t= 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 k=500k = 500 examples is filled from a stream of N=200,000N = 200{,}000. 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 k/N=500/200,000=0.0025k/N = 500 / 200{,}000 = 0.0025: 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) 2⋅78⋅2=3.52 \cdot \frac{7}{8} \cdot 2 = 3.5 GB per worker per step. (b) 5m+5≤0.2\frac{5}{m + 5} \le 0.2 means m+5≥25m + 5 \ge 25, so m≥20m \ge 20. (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 r=4r = 4 adapts a 1024×10241024 \times 1024 matrix. How many trainable parameters does it add?

  1. 4,096
  2. 8,192
  3. 1,048,576
  4. 4,194,304

Which probability vector does margin sampling query first?

  1. (0.9,0.05,0.05)(0.9, 0.05, 0.05)
  2. (0.48,0.47,0.05)(0.48, 0.47, 0.05)
  3. (0.4,0.3,0.3)(0.4, 0.3, 0.3)
  4. (0.7,0.2,0.1)(0.7, 0.2, 0.1)

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. 1
  2. 0.5
  3. 0.002
  4. 0

A pipeline has 4 stages and 12 micro-batches. What fraction of the time is each stage idle?

  1. 0.2
  2. 0.25
  3. 0.33
  4. 0.75

Which part of a checkpoint makes the resumed run use the same dropout masks and shuffles as the uninterrupted one?

  1. The model weights
  2. The optimiser state
  3. The RNG states (per rank) and the epoch number for the sampler
  4. The learning-rate scheduler