16 · Training diagnostics

Run it in Colab View the .ipynb

You are reading this notebook. To run it, open it in Colab with the button above - no install, no GPU needed for most of them - or clone the repository and open it in Jupyter.

  1. 16.1 · The four numbers
    1. In plain terms
  2. 16.2 · Something real to watch
  3. 16.3 · Five runs, five diagnoses
  4. 16.4 · The pattern reference
  5. 16.5 · Gradient norms and clipping
  6. 16.6 · Finding the learning rate
  7. 16.7 · When to stop
    1. Epoch counts that are actually right
  8. 16.8 · Loss is not the metric
  9. 16.9 · The run log
  10. Checkpoint

Training track · ~75 minutes · no GPU needed

You have now run three kinds of training: pre-training (13), supervised fine-tuning (11, 14) and preference tuning (15). Every one of them produces the same artefact — a stream of numbers that scroll past while you wait — and the skill that separates people who get working models from people who burn GPU hours is the ability to read that stream.

This notebook is that skill, and it is deliberately not about Qwen. The diagnostics are scale-free: a curve that means “learning rate too high” on a 70B model means the same thing on the 300-parameter network you are about to train here. So we train something tiny, in NumPy, in seconds, and produce real curves for every failure mode rather than drawings of them.

By the end you will be able to:

  1. name the four numbers worth watching, and what each one rules out;
  2. classify a run as healthy, undertrained, overfitting, stuck or diverged;
  3. say what gradient clipping does — and what it emphatically does not fix;
  4. find a learning rate with a range test instead of a guess;
  5. decide when to stop, and why “one more epoch” is usually wrong;
  6. explain why a falling loss is not evidence that the model got better.

Five loss curve shapes: healthy, undertrained, overfitting, stuck at chance, and diverged

# --- Setup: works on your laptop AND in Google Colab ------------------------
import os
import subprocess
import sys
from pathlib import Path

if "google.colab" in sys.modules:
    if not Path("/content/ROBT407LLM").exists():
        subprocess.run(["git", "clone", "--depth", "1",
                        "https://github.com/berdakh/ROBT407LLM.git",
                        "/content/ROBT407LLM"], check=True)
    os.chdir("/content/ROBT407LLM")
    subprocess.run([sys.executable, "-m", "pip", "install", "-q",
                    "-r", "requirements.txt"], check=True)

REPO_ROOT = next(p for p in [Path.cwd(), *Path.cwd().parents]
                 if (p / "src" / "qwen_workshop").is_dir())
sys.path.insert(0, str(REPO_ROOT / "src"))
print("repo root:", REPO_ROOT)
import json
import math

import numpy as np

rng = np.random.default_rng(613)

16.1 · The four numbers

Trainers log dozens of things. These four are the ones that carry information, and each one rules out a different class of bug:

Number Rules out The one thing to know
Train loss “is it learning at all” Falling train loss proves only that the model can fit this data
Validation loss “is it generalising” The only number that tracks what you actually want
Learning rate “is the step size sane” Log it. Schedulers change it under you.
Gradient norm “is anything exploding” Usually boring, and that is the point — a spike is a signal

Two rules that save most runs:

  1. Validation loss is the only number you may use to make decisions. Train loss going down is compatible with the model getting worse at everything you care about. Section 16.3 shows exactly that happening.
  2. Know your chance baseline before you start. For next-token prediction over a vocabulary of size V, a model that has learned nothing scores ln(V). For binary classification it is ln(2) ≈ 0.693. A loss sitting at the baseline is not slow learning, it is a bug.
VOCAB_BASELINES = {"char-level, ~100 chars": 100, "Qwen3 (V=151936)": 151_936}
for name, vocab in VOCAB_BASELINES.items():
    print(f"{name:<26} chance loss = ln({vocab}) = {math.log(vocab):.3f}")
print(f"{'binary (this notebook)':<26} chance loss = ln(2)      = {math.log(2):.3f}")

CHANCE = math.log(2)

That second row is worth remembering: a fresh Qwen3 scores about 11.9. When you see a pre-training run start near 11.9 and fall, that is the model learning the token frequencies. Notebook 13’s run starts near 4.6 instead, because its character-level vocabulary is about a hundred entries rather than 151,936 — same objective, different baseline. Compute your own: notebook 13 prints ln(VOCAB_SIZE) before training for exactly this reason.

In plain terms

  Think of it as
Train loss Your score on the practice papers you have been drilling.
Validation loss Your score on a paper you have never seen. The only one that counts.
Overfitting Memorising past papers. Perfect on those, lost on the real exam.
Early stopping Handing it in when you stop improving, not fiddling until the bell.
Gradient clipping A seatbelt: useless on an ordinary journey, decisive in the one crash.
Learning-rate schedule Starting slow, speeding up, slowing down to park.

The seatbelt is the one to remember, because clipping is routinely misunderstood as a brake. It is not. 16.5 measures what it actually does.

16.2 · Something real to watch

A two-layer tanh network on a problem no linear model can solve. Roughly 300 parameters, hand-written backprop, no dependencies beyond NumPy. It is not a language model — and for this notebook that is an advantage, because every curve below is computed in under a second, so you can change a number and see the consequence immediately.

def make_data(n, rng):
    """Two features, label = sign(x1 * x2). Not linearly separable."""
    X = rng.normal(size=(n, 2))
    y = ((X[:, 0] * X[:, 1]) > 0).astype(np.float64)
    return X + rng.normal(scale=0.15, size=X.shape), y


def init_params(hidden=16, seed=0):
    r = np.random.default_rng(seed)
    return {"W1": r.normal(scale=0.8, size=(2, hidden)), "b1": np.zeros(hidden),
            "W2": r.normal(scale=0.8, size=(hidden, 1)), "b2": np.zeros(1)}


def sigmoid(z):
    """Stable for both signs - the naive 1/(1+exp(-z)) overflows on big |z|."""
    return 0.5 * (1.0 + np.tanh(0.5 * z))


def loss_and_grads(p, X, y):
    """Binary cross-entropy and its gradients. Loss is in nats, like an LLM's."""
    n = len(y)
    h = np.tanh(X @ p["W1"] + p["b1"])
    z = (h @ p["W2"] + p["b2"]).ravel()
    loss = float(np.mean(np.logaddexp(0.0, z) - y * z))

    dz = (sigmoid(z) - y) / n
    grads = {"W2": h.T @ dz[:, None], "b2": np.array([dz.sum()])}
    dh = np.outer(dz, p["W2"].ravel()) * (1 - h**2)
    grads["W1"] = X.T @ dh
    grads["b1"] = dh.sum(0)
    return loss, grads


def grad_norm(grads):
    """Global L2 norm over all parameters - exactly what trainers report."""
    return float(np.sqrt(sum((g**2).sum() for g in grads.values())))


def train(X_train, y_train, X_val, y_val, lr, steps=400, every=20,
          clip=None, seed=0):
    """Full-batch gradient descent. Returns the history a trainer would log."""
    p = init_params(seed=seed)
    history = []
    clips_fired = 0
    for step in range(steps + 1):
        loss, grads = loss_and_grads(p, X_train, y_train)
        norm = grad_norm(grads)
        if clip is not None and norm > clip:
            clips_fired += 1
            for key in grads:
                grads[key] *= clip / norm
        if step % every == 0:
            val_loss, _ = loss_and_grads(p, X_val, y_val)
            history.append({"step": step, "train": loss, "val": val_loss,
                            "lr": lr, "grad_norm": norm,
                            "clips_fired": clips_fired})
        if not math.isfinite(loss):
            break
        for key in p:
            p[key] -= lr * grads[key]
    return p, history


X_small, y_small = make_data(40, rng)      # deliberately too little data
X_big, y_big = make_data(2000, rng)
X_val, y_val = make_data(400, rng)
print(f"train sets: {len(y_small)} and {len(y_big)} examples; validation: {len(y_val)}")

16.3 · Five runs, five diagnoses

Here is the function. Read it before you run it: every threshold in it is a judgement call, and the comments say what each one is for.

def diagnose(history, chance_loss):
    """Classify a run from its history. Order matters - check the fatal first."""
    train_losses = [h["train"] for h in history]
    val_losses = [h["val"] for h in history]
    steps = [h["step"] for h in history]

    # 1. Diverged: nothing else is worth checking.
    if not all(math.isfinite(v) for v in train_losses + val_losses):
        return "DIVERGED (nan/inf) - lower the learning rate"
    if max(train_losses) > 10 * chance_loss:
        return (f"DIVERGED - loss reached {max(train_losses):.1f}, far above the "
                f"{chance_loss:.2f} you get for free. Lower the learning rate.")

    # 2. Stuck at the baseline: a bug, not slow learning.
    if train_losses[-1] > 0.95 * chance_loss:
        return (f"NOT LEARNING - train loss {train_losses[-1]:.3f} is still at "
                f"chance ({chance_loss:.3f}). Check LR, labels, loss masking.")

    # 3. Overfitting: validation turned around. 10% above its own minimum is
    #    past the noise floor for this problem; tune per task.
    best = min(range(len(val_losses)), key=lambda i: val_losses[i])
    if best < len(val_losses) - 1 and val_losses[-1] > val_losses[best] * 1.10:
        return (f"OVERFITTING - validation bottomed at step {steps[best]} "
                f"({val_losses[best]:.3f}) and rose to {val_losses[-1]:.3f}. "
                f"Stop at {steps[best]}.")

    # 4. Still descending at the end: you stopped too early.
    tail = train_losses[-max(2, len(train_losses) // 4):]
    if (tail[0] - tail[-1]) / max(tail[0], 1e-9) > 0.05:
        return "UNDERTRAINED - still falling at the last step; train longer"

    return "HEALTHY - converged, train/val gap stable"


RUNS = {
    "lr far too low": dict(X=X_small, y=y_small, lr=0.003, steps=400, every=20),
    "short run":      dict(X=X_small, y=y_small, lr=0.3, steps=400, every=20),
    "lr far too high": dict(X=X_small, y=y_small, lr=30.0, steps=400, every=20),
    "too little data": dict(X=X_small, y=y_small, lr=0.3, steps=3000, every=100),
    "enough data":    dict(X=X_big, y=y_big, lr=0.3, steps=4000, every=200),
}

histories = {}
for name, cfg in RUNS.items():
    _, histories[name] = train(cfg["X"], cfg["y"], X_val, y_val,
                               lr=cfg["lr"], steps=cfg["steps"], every=cfg["every"])
    print(f"{name:<17} {diagnose(histories[name], CHANCE)}")

Five real runs, five correct diagnoses, and not one of them a drawing. Notice what the diagnoses are not based on: in four of the five, train loss went down. Train loss going down tells you almost nothing.

The fourth run is the one to stare at. Print it.

print(f"{'step':>6}{'train':>9}{'val':>9}{'gap':>9}{'grad norm':>11}")
for row in histories["too little data"][::5]:
    print(f"{row['step']:>6}{row['train']:>9.4f}{row['val']:>9.4f}"
          f"{row['val'] - row['train']:>+9.4f}{row['grad_norm']:>11.4f}")

Train loss falls monotonically from 0.976 to 0.036 — a 96% reduction, which in isolation looks like a triumph. Validation loss bottoms out early and then climbs steadily. Everything after the bottom was damage, done with a loss curve that looked perfect the whole time.

The gradient norm column is also doing something interesting: it shrinks toward zero. A model confidently fitting 40 points it has memorised has nothing left to be wrong about, so there is no gradient. Tiny gradient norms late in a small-data run are a memorisation signature, not convergence.

Now compare the run that had enough data.

print(f"{'step':>6}{'train':>9}{'val':>9}{'gap':>9}")
for row in histories["enough data"][::4]:
    print(f"{row['step']:>6}{row['train']:>9.4f}{row['val']:>9.4f}"
          f"{row['val'] - row['train']:>+9.4f}")

Both curves flatten together and the gap stays small — about 0.02, against 0.65 in the small-data run. Fifty times more data, and the generalisation gap nearly disappears. This is why “get more data” is the boring correct answer to overfitting, and why regularisation is the consolation prize.

Two details worth not skipping over:

  • The gap grows slowly from 0.014 to 0.030, and validation loss bottoms around step 2,400 before edging up. Even this run is mildly past its optimum by the end — diagnose still calls it healthy because the rise is under its 10% threshold, which is a threshold, not a law. Exercise 1 is about exactly this.
  • A negative gap — validation loss below train loss — alarms people and usually should not. With dropout active in training and off in evaluation it is expected; without dropout, a small negative gap means the validation set drew a slightly easier sample. Only a large one means you have mixed up your splits.

Exercise 1. diagnose has four hard-coded thresholds: 10 * chance_loss, 0.95, 1.10 and 0.05. Pick one, find a run where it gives the wrong answer (change the learning rate, the data size or the number of steps), and say what you would use instead. Hint: the 0.05 tail-slope test is the most fragile — what does every=1000 do to it?

16.4 · The pattern reference

Keep this table next to any real training run.

Shape Diagnosis Fix
Both falling, gap stable Healthy Nothing. Let it run.
Both falling at the last step Undertrained More steps or epochs
Train ↓, val ↑ Overfitting Stop at the val minimum; more data; more regularisation
Both flat at ln(V) Not learning LR, label/mask bug, frozen parameters
Loss → nan/inf, or climbing Diverged Lower LR; check for inf in the data
Falls then jumps, repeatedly LR too high for the late phase Add a decay schedule
Sawtooth with epoch period Data order effect Shuffle between epochs
Sudden drop at an epoch boundary Memorisation beginning You are at the start of overfitting
Train loss above val loss, persistently Dropout, or a leak Expected with dropout; otherwise check the split

The last row has a subtlety worth knowing: dropout is active during training and off during evaluation, so a healthy run with dropout routinely reports train loss above validation loss. People spend hours debugging this.

16.5 · Gradient norms and clipping

Gradient clipping rescales the gradient when its global norm exceeds a threshold. Notebook 13 used clip_grad_norm_(model.parameters(), 1.0), which is the near-universal default.

It is also the most misunderstood knob in training, so let us establish what it does by measurement rather than assertion. Start with the diverging run — the obvious candidate for “clipping will save this”.

print(f"{'clip':>6}{'final train':>13}{'final val':>11}"
      f"{'max grad norm':>15}{'clips fired':>13}")
for clip in (None, 1.0, 0.1):
    _, hist = train(X_small, y_small, X_val, y_val, lr=30.0,
                    steps=400, every=100, clip=clip)
    print(f"{str(clip):>6}{hist[-1]['train']:>13.4f}{hist[-1]['val']:>11.4f}"
          f"{max(h['grad_norm'] for h in hist):>15.3f}"
          f"{hist[-1]['clips_fired']:>13}")

Clipping at 1.0 does not rescue it — the final validation loss is worse than with no clipping at all (14.7 against 10.4). The clips fired column says why: it fired on 52 of 401 steps, on the minority where the diverging weights happened to produce a big gradient. That is not a correction, it is an intermittent interruption, and interrupting one step in eight of a diverging run changes where it lands without making it converge.

The problem was never a large gradient. Every logged norm sits below 1.0: this is a sane gradient multiplied by an insane learning rate, and no threshold on the gradient can see that.

Clipping at 0.1 does rescue the run, and the column shows how — it fires on 141 of 401 steps, capping each of those to a step of length lr × clip = 3 regardless of what the gradient said. At that point it is not a safety valve any more; it is a step-size cap doing the learning rate’s job, badly. The honest fix for all three rows is lr=0.3.

Gradient clipping is not a fix for a bad learning rate. If clipping improves your run, check the norms: either they were genuinely spiking, or you have disguised a learning-rate problem.

So what is it for? Rare, catastrophic batches. One pathological example in one batch, a single step at full learning rate, and a model that was training fine is destroyed. Here is that exact event, twice — once unprotected, once clipped.

X_outlier = np.array([[40.0, -40.0], [-40.0, 40.0]])   # extreme and mislabelled
y_outlier = np.array([1.0, 1.0])

for clip in (None, 1.0):
    p = init_params(seed=0)
    for _ in range(50):                                 # 50 ordinary steps
        _, grads = loss_and_grads(p, X_small, y_small)
        norm = grad_norm(grads)
        if clip is not None and norm > clip:
            for key in grads:
                grads[key] *= clip / norm
        for key in p:
            p[key] -= 0.3 * grads[key]
    before, _ = loss_and_grads(p, X_val, y_val)

    _, grads = loss_and_grads(p, X_outlier, y_outlier)  # then one bad batch
    norm = grad_norm(grads)
    if clip is not None and norm > clip:
        for key in grads:
            grads[key] *= clip / norm
    for key in p:
        p[key] -= 0.3 * grads[key]
    after, _ = loss_and_grads(p, X_val, y_val)

    print(f"clip={str(clip):<5} bad-batch grad norm {norm:>6.2f} | "
          f"val {before:.4f} -> {after:.4f}")

A gradient norm of 24.5 where the run had been producing norms under 1.0. Unclipped, that one step raises validation loss by 0.34 — about half of everything the previous 50 steps earned, thrown away in a single update. Clipped at 1.0, the damage is 0.01, thirty times smaller.

This is why you log the gradient norm even though it is boring: boring is the useful state, and the exception is the whole signal. In a real run, norms that are stable and then spike mean bad data, not a bad model — go and look at the batch.

Exercise 2. Change y_outlier to [0.0, 0.0], so the extreme points are now labelled consistently with sign(x1 * x2). Does the spike go away? Print the per-parameter norms ({k: np.sqrt((v**2).sum()) for k, v in grads.items()}) for both labellings and for an ordinary batch, and explain which parameter the spike lives in and why. The answer is not the one most people predict.

16.6 · Finding the learning rate

The learning rate matters more than every other hyperparameter combined, and you do not have to guess it. Run a range test: train briefly at logarithmically spaced learning rates and look at where it breaks.

print(f"{'lr':>9}{'train':>9}{'val':>9}  verdict")
for lr in (3e-4, 3e-3, 3e-2, 3e-1, 3e0, 3e1):
    _, hist = train(X_small, y_small, X_val, y_val, lr=lr, steps=300, every=150)
    train_loss, val_loss = hist[-1]["train"], hist[-1]["val"]
    if not math.isfinite(train_loss) or train_loss > 2 * CHANCE:
        verdict = "diverging"
    elif train_loss > 0.95 * CHANCE:
        verdict = "too slow to tell"
    else:
        verdict = "learning"
    print(f"{lr:>9.4f}{train_loss:>9.4f}{val_loss:>9.4f}  {verdict}")

The picture is unmistakable: below 0.003 nothing measurable happens in 300 steps, 0.03 through 3 all learn, and 30 is a wreck. The usual rule of thumb is the largest rate that is still stable, divided by two or three — which here would give about 1.

And the rule of thumb is beaten by the data. The best validation loss in the sweep is at 0.3, not at the largest stable rate: lr=3 reaches a much lower train loss (0.043 against 0.158) and a much worse validation loss (0.70 against 0.35). It is fitting those 40 points harder and generalising worse.

Use the rule of thumb to pick the range. Pick inside it on validation loss, never on training loss.

For real fine-tuning the ranges are well established, so a range test is a confirmation rather than a search:

Run Typical LR Why
Pre-training from scratch 1e-3 … 6e-4 Random weights, nothing to destroy
Full fine-tune 1e-5 … 5e-5 Pretrained weights are worth protecting
LoRA 1e-4 … 3e-4 Only the adapter moves, so it can move faster
DPO / preference tuning 5e-7 … 5e-6 Tiny. Preference tuning drifts easily.

DPO’s rate being 100× lower than LoRA’s surprises people every time. The reason is section 15.8: the objective can be satisfied by wrecking the model in a particular direction, so you take small steps and watch the reward levels.

Pair the rate with a schedule: warm up over the first few percent of steps (large early steps on random Adam state are destabilising), then decay to near zero. Notebook 13 used OneCycleLR, which does both.

16.7 · When to stop

Early stopping, in full. There is no more to it than this.

def early_stop(history, patience=3, key="val"):
    """Return (best_step, best_value, stopped_at). stopped_at is None if the
    run ended before patience ran out.

    patience counts *evaluations* without improvement, not steps. If you
    evaluate every 500 steps, patience=3 means 1,500 steps of damage.
    """
    best_value, best_index = float("inf"), 0
    for i, row in enumerate(history):
        if row[key] < best_value:
            best_value, best_index = row[key], i
        elif i - best_index >= patience:
            return history[best_index]["step"], best_value, row["step"]
    return history[best_index]["step"], best_value, None


for patience in (1, 3, 10):
    best_step, best_val, stopped = early_stop(histories["too little data"], patience)
    print(f"patience={patience:>2}: best val {best_val:.4f} at step {best_step}, "
          f"would have stopped at step {stopped}")

final = histories["too little data"][-1]
print(f"\nran to completion instead: val {final['val']:.4f} at step {final['step']}")

Every patience setting finds the same optimum — step 300, val 0.354 — and differs only in how much compute it burns confirming it (stopping at step 400, 600 or 1,300 respectively). Running to completion instead ends at 0.689, which is 95% worse than the checkpoint it already had in hand at step 300.

Two things follow, and both are about plumbing rather than theory:

  • Keep the best checkpoint, not the last one. load_best_model_at_end=True in TrainingArguments. Without it, early stopping detects the problem and then hands you the damaged model anyway.
  • Patience is in evaluations, not steps. With eval_steps=500 and patience=3 you permit 1,500 steps past the optimum.

Epoch counts that are actually right

Run Epochs What more does
Pre-training <1 (single pass over a huge corpus) Repeats start to memorise
LoRA SFT, 50–500 examples 2–3 10 epochs on 50 examples is pure memorisation
LoRA SFT, 10k+ examples 1–2 —
DPO 1 2+ reliably degrades; see 15.8

Notebook 11’s twelve examples will happily run twenty epochs and produce a model that reproduces all twelve verbatim and cannot do anything else. That is not a bug in LoRA; it is this table.

16.8 · Loss is not the metric

You can minimise loss and ship a worse model. Four reasons, which is why every one of these runs needs a metric that is not loss.

print(f"{'loss (nats)':>13}{'perplexity':>13}  reading")
for loss, reading in [
    (11.93, "untrained Qwen3 (ln 151936)"),
    (3.00, "bad"),
    (2.00, "usable small model"),
    (1.50, "good"),
    (0.05, "memorised the training set"),
]:
    print(f"{loss:>13.2f}{math.exp(loss):>13.1f}  {reading}")

Perplexity is just exp(loss) — “how many tokens is the model effectively choosing between”. It is the standard number for language models and it is more intuitive than nats, but it is the same number, so it inherits every limitation:

  1. It is not comparable across tokenizers. Different vocabulary, different perplexity, same model quality. Published perplexities are comparable only within one tokenizer.
  2. It measures the training objective, not the task. A model can have lower perplexity and follow instructions worse.
  3. Preference tuning’s loss means something else entirely. DPO loss near zero means the pairs are classified confidently, which is compatible with the degenerate drift of 15.8.
  4. Contamination makes it meaningless. If your evaluation text appeared in pre-training, the perplexity is a memory measurement.

So pair the loss with something behavioural. Cheapest useful version: a fixed list of prompts, run before and after, read by a human. Ten prompts, five minutes, and it catches the failures loss cannot see.

BEHAVIOURAL_PROBES = [
    ("task", "The thing you actually trained for"),
    ("task, rephrased", "Same task, wording the training data never used"),
    ("adjacent task", "Related but untrained - did you break it?"),
    ("general knowledge", "Unrelated. Catastrophic forgetting check."),
    ("instruction following", "'Answer in exactly three words.' Still obeyed?"),
    ("refusal", "Something it should decline. Still declines?"),
    ("format", "Does structured output still parse?"),
    ("length", "Has it become verbose? (DPO's favourite failure)"),
    ("repetition", "Long generation - does it loop?"),
    ("out of scope", "Nonsense input. Graceful, or confidently wrong?"),
]
for name, purpose in BEHAVIOURAL_PROBES:
    print(f"  [{name:<21}] {purpose}")

Rows 3, 4 and 6 are the ones that earn their keep, because they are the failures that a loss curve is structurally incapable of showing you: you did not train on them, so nothing in the objective was ever measuring them.

16.9 · The run log

A training run you cannot reproduce is an anecdote. The fix costs one cell: write down everything that could have changed the result, in a file next to the weights.

def run_log(name, config, history, notes=""):
    """Everything needed to explain or repeat a run."""
    best_step, best_val, stopped = early_stop(history, patience=3)
    return {
        "name": name,
        "config": config,
        "data": {"train_examples": config.get("train_examples"),
                 "val_examples": config.get("val_examples")},
        "result": {
            "final_train_loss": round(history[-1]["train"], 4),
            "final_val_loss": round(history[-1]["val"], 4),
            "best_val_loss": round(best_val, 4),
            "best_step": best_step,
            "max_grad_norm": round(max(h["grad_norm"] for h in history), 4),
        },
        "diagnosis": diagnose(history, CHANCE),
        "early_stop_would_fire_at": stopped,
        "notes": notes,
    }


log = run_log(
    "too little data",
    {"lr": 0.3, "steps": 3000, "hidden": 16, "seed": 0,
     "train_examples": len(y_small), "val_examples": len(y_val)},
    histories["too little data"],
    notes="Classic overfit. Keep the step-300 checkpoint, not the last one.",
)
print(json.dumps(log, indent=2))

The checklist behind that dict, for a real run:

  • Data: which files, which split, how many examples, the dedup commit
  • Model: exact base model and revision — main moves
  • Hyperparameters: LR, schedule, batch size × accumulation, epochs, β, LoRA rank and target modules
  • Seed, and the library versions (pip freeze)
  • Hardware — results differ between bf16 on an A100 and fp16 on a T4
  • The curves, and your diagnosis in one sentence

The expensive mistake this prevents is not forgetting a hyperparameter. It is having two runs, one good and one bad, and no way to tell what differed.

Exercise 3. Run train twice with the same arguments but different seed, and record both with run_log. How large is the seed-to-seed difference in best_val_loss? Now state the rule it implies for comparing two hyperparameter settings — specifically, how much better must one be before you believe it?

Checkpoint

  1. Name the four numbers and what each one rules out.
  2. What is the chance loss for Qwen3, and what does a run that sits there mean?
  3. Your train loss falls 96% and the model gets worse. Where do you look?
  4. Why did clipping at 1.0 fail to rescue the lr=30 run?
  5. What is gradient clipping actually for, then?
  6. Describe the range test, and the rule for picking from its output.
  7. Why is load_best_model_at_end=True not optional?
  8. Give three reasons a lower perplexity does not mean a better model.
  9. Which behavioural probes can a loss curve never replace, and why not?

➡️ Where next: that is the end of the training track. Back to 12_capstone_daily_assistant.ipynb if you skipped it, or take a fine-tune of your own all the way through: notebook 14 for the data, 11 for the SFT run, 15 for preferences, and this notebook open beside the training log.


Back to top

ROBT407LLM workshop materials. Code is MIT licensed; prose is CC BY 4.0. Model weights are governed by their own licences - check each model card.