← All courses ← Course home

Lesson 02 of 12 · Phase 1 Foundations

Non-convex optimisation

Training is not a clean bowl. Learn the geometry you will actually hit: saddles, sharp minima, exploding steps, and why clip exists.

Agent brief (llms.md)

Convex optimisation would be kinder. Language-model loss is not convex. You will still use first-order methods because the replica that matters is the one you can run, not the one you can solve in closed form.

Topics

Adam keeps a biased first moment and a biased second moment of the gradient. The epsilon in the denominator is not decoration. When a second-moment entry is tiny, the effective step is huge. That is one real source of training instability.

Coding


import math
import torch

def adam_step(p, g, m, v, t, lr=3e-4, beta1=0.9, beta2=0.95, eps=1e-8, wd=0.1):
    m = beta1 * m + (1 - beta1) * g
    v = beta2 * v + (1 - beta2) * (g * g)
    m_hat = m / (1 - beta1 ** t)
    v_hat = v / (1 - beta2 ** t)
    p = p * (1 - lr * wd) - lr * m_hat / (torch.sqrt(v_hat) + eps)
    return p, m, v

def cosine_lr(step, total, base, warmup):
    if step < warmup:
        return base * step / max(1, warmup)
    progress = (step - warmup) / max(1, total - warmup)
    return base * 0.5 * (1.0 + math.cos(math.pi * progress))

Run a toy non-convex scalar, f(x) = x^4 - x^2, from several starts. Plot the path. Then run a two-layer MLP on a noisy spiral and log grad norms. You want to see a spike and a clip, on purpose.

Assignment

Opinion checkpoint

Write this down. Optimiser choice is not a personality test. If you cannot name the buffers and the failure mode, you are not ready to debug a 100M pretrain. Ship the lab, then earn the opinion.

Papers you may name by title when you write notes: none required this week. You will meet training instability again when you pretrain in week 5.

Next: Build a transformer from scratch (TinyGPT).

Key concepts

  • Language-model training is non-convex first-order search.
  • Adam stores biased moments. Epsilon and warmup are load-bearing.
  • Grad clip is a stability tool, not a style choice.
  • Log grad norms and loss. Do not invent smoothness you did not measure.

Takeaways

  • Implement the updates. Reading the names is sightseeing.
  • A broken eps or a missing warmup is a real outage later.
  • Keep three seeds on the toy so you do not overfit a story.