Reference

Code snippets

18 code blocks from 14 lessons, in one place. Each one links back to the section that explains it.

The learning problem: generalization, bias-variance and regularization

ML foundations

Show the code (73 lines)

Python

import math
import random
from fractions import Fraction as Fr


def solve(A, b):
    """Gaussian elimination in exact fractions, so there is no round-off."""
    n = len(A)
    M = [row[:] + [b[i]] for i, row in enumerate(A)]
    for c in range(n):
        p = next(r for r in range(c, n) if M[r][c] != 0)
        M[c], M[p] = M[p], M[c]
        for r in range(c + 1, n):
            f = M[r][c] / M[c][c]
            for k in range(c, n + 1):
                M[r][k] -= f * M[c][k]
    w = [Fr(0)] * n
    for i in range(n - 1, -1, -1):
        w[i] = (M[i][n] - sum(M[i][k] * w[k] for k in range(i + 1, n))) / M[i][i]
    return w


def basis(x, degree):
    t = Fr(x) * 2 - 1                      # rescale x from [0, 1] to [-1, 1]
    return [t ** j for j in range(degree + 1)]


def fit(xs, ys, degree, lam):
    """Ridge-penalised polynomial fit; the intercept is not penalised."""
    rows = [basis(x, degree) for x in xs]
    p = degree + 1
    A = [[sum(r[i] * r[j] for r in rows) + (Fr(lam) if i == j and i > 0 else 0)
          for j in range(p)] for i in range(p)]
    b = [sum(r[i] * Fr(y) for r, y in zip(rows, ys)) for i in range(p)]
    return solve(A, b)


def mse(w, xs, ys):
    pred = lambda x: float(sum(a * b for a, b in zip(w, basis(x, len(w) - 1))))
    return sum((pred(x) - y) ** 2 for x, y in zip(xs, ys)) / len(xs)


def noisy_sine(x, rng):
    return math.sin(2 * math.pi * x) + rng.gauss(0, 0.3)


rng = random.Random(0)
xt = [(i + rng.random()) / 15 for i in range(15)]      # 15 training points, spread over [0, 1]
yt = [noisy_sine(x, rng) for x in xt]
xv = [rng.random() for _ in range(18)]                 # 18 validation points
yv = [noisy_sine(x, rng) for x in xv]

print("degree sweep, lambda = 1e-8")
for d in (1, 3, 5, 9, 12):
    w = fit(xt, yt, d, 1e-8)
    print(d, round(mse(w, xt, yt), 3), round(mse(w, xv, yv), 3))

print("degree 12, lambda sweep")
for lam in (1e-8, 1e-2, 1e-1, 1, 10):
    w = fit(xt, yt, 12, lam)
    print(lam, round(mse(w, xt, yt), 3), round(mse(w, xv, yv), 3))

print("learning curves, lambda = 1e-8, 200 validation points")
rng = random.Random(1000)
pool = [(i + rng.random()) / 60 for i in range(60)]
rng.shuffle(pool)
ypool = [noisy_sine(x, rng) for x in pool]
xv2 = [rng.random() for _ in range(200)]
yv2 = [noisy_sine(x, rng) for x in xv2]
for d in (1, 9):
    for n in (15, 30, 60):
        w = fit(pool[:n], ypool[:n], d, 1e-8)
        print(d, n, round(mse(w, pool[:n], ypool[:n]), 3), round(mse(w, xv2, yv2), 3))

Linear models, loss functions and gradient descent

ML foundations

Show the code (277 lines)

Python

import itertools
import math
import random
import statistics
from fractions import Fraction as Fr


def sigmoid(z):
    if z >= 0:
        return 1 / (1 + math.exp(-z))
    e = math.exp(z)
    return e / (1 + e)


# 1. Normal equation, exact: fit y = b + w*x to three points
xs, ys = [Fr(1), Fr(2), Fr(3)], [Fr(2), Fr(4), Fr(5)]
n, sx, sxx = len(xs), sum(xs), sum(x * x for x in xs)
sy, sxy = sum(ys), sum(x * y for x, y in zip(xs, ys))
det = n * sxx - sx * sx
b, w = (sxx * sy - sx * sxy) / det, (n * sxy - sx * sy) / det
res = [y - (b + w * x) for x, y in zip(xs, ys)]
print("1. normal equation: b =", b, "w =", w, "residuals =", [str(r) for r in res],
      "sum =", sum(res), "sum x*r =", sum(x * r for x, r in zip(xs, res)),
      "mse =", sum(r * r for r in res) / n)


# 2. Outliers: mean versus median, and OLS versus least absolute deviations
data = [1, 2, 3, 4, 100]
print("2a. mean", statistics.fmean(data), "median", statistics.median(data))
X6 = [Fr(i) for i in range(1, 7)]
Y6 = [Fr(2 * i) for i in range(1, 7)]
Y6[5] = Fr(40)                                   # one corrupted label: 12 became 40


def ols(xs, ys):
    n, sx, sy = len(xs), sum(xs), sum(ys)
    sxx, sxy = sum(x * x for x in xs), sum(x * y for x, y in zip(xs, ys))
    d = n * sxx - sx * sx
    return (sxx * sy - sx * sxy) / d, (n * sxy - sx * sy) / d


def lad(xs, ys):
    """Least absolute deviations: an optimum passes through two data points."""
    best = None
    for i, j in itertools.combinations(range(len(xs)), 2):
        w = (ys[j] - ys[i]) / (xs[j] - xs[i])
        b = ys[i] - w * xs[i]
        cost = sum(abs(y - (b + w * x)) for x, y in zip(xs, ys))
        if best is None or cost < best[0]:
            best = (cost, b, w)
    return best


b_o, w_o = ols(X6, Y6)
cost, b_l, w_l = lad(X6, Y6)
print("2b. OLS: intercept %.3f slope %s, prediction at x=1 is %.3f" % (b_o, w_o, b_o + w_o))
print("2c. LAD: intercept %s slope %s, total absolute error %s" % (b_l, w_l, cost))


# 3. One logistic gradient step by hand, for y = 1 and y = 0
for y in (1, 0):
    x, w, b, lr = [1, 2], [0.0, 0.0], 0.0, 0.1
    p = sigmoid(sum(a * c for a, c in zip(w, x)) + b)
    w = [a - lr * (p - y) * c for a, c in zip(w, x)]
    b -= lr * (p - y)
    z2 = sum(a * c for a, c in zip(w, x)) + b
    loss = lambda q: -(y * math.log(q) + (1 - y) * math.log(1 - q))
    print("3. y=%d: p=0.5 -> w=%s b=%.2f z=%.2f p=%.3f, loss 0.693 -> %.3f"
          % (y, [round(a, 2) for a in w], b, z2, sigmoid(z2), loss(sigmoid(z2))))


# 4. Why not squared error on a sigmoid: gradient with respect to the logit z, label y = 1
print("4. z, p, cross-entropy gradient, squared-error gradient")
for z in (-6, -2, 0, 2):
    p = sigmoid(z)
    print("  ", z, round(p, 5), round(p - 1, 5), round((p - 1) * p * (1 - p), 5))


# 5. Losses as a function of the margin m = y * f(x), y in {-1, +1}
print("5. margin, hinge, log loss, squared")
for m in (-2, -1, 0, 1, 2):
    print("  ", m, max(0, 1 - m), round(math.log(1 + math.exp(-m)), 3), (1 - m) ** 2)

# 6. Learning rate on J(w) = w^2, gradient 2w, start at w = 1
print("6. learning rate: w after 0..5 steps")
for lr in (0.1, 0.5, 1.0, 1.1):
    w, trace = 1.0, [1.0]
    for _ in range(5):
        w -= lr * 2 * w
        trace.append(round(w, 4))
    print("  ", lr, trace)


# 7. Feature scaling: steps of gradient descent on least squares (quadratic, so exact)
def make(seed, n=200):
    r = random.Random(seed)
    X = [[r.random(), r.random() * 100] for _ in range(n)]
    y = [3 * a + 0.05 * c + r.gauss(0, 0.1) for a, c in X]
    return X, y


def moments(X, y):
    n = len(X)
    H = [[sum(r[i] * r[j] for r in X) / n for j in range(2)] for i in range(2)]
    c = [sum(r[i] * t for r, t in zip(X, y)) / n for i in range(2)]
    return H, c


def steps_to_converge(H, c, tol=1e-6, cap=10**7):
    a, bb, d = H[0][0], H[0][1], H[1][1]
    mid, rad = (a + d) / 2, math.sqrt(((a - d) / 2) ** 2 + bb * bb)
    lo, hi = mid - rad, mid + rad                  # eigenvalues of X'X/n
    lr = 1 / (lo + hi)                             # best fixed step for this quadratic
    det = a * d - bb * bb
    star = [(d * c[0] - bb * c[1]) / det, (a * c[1] - bb * c[0]) / det]
    w = [0.0, 0.0]
    for k in range(cap):
        e = [w[0] - star[0], w[1] - star[1]]
        gap = e[0] * (a * e[0] + bb * e[1]) + e[1] * (bb * e[0] + d * e[1])
        if gap < tol:
            return k, hi / lo
        w = [w[0] - lr * 2 * (a * e[0] + bb * e[1]), w[1] - lr * 2 * (bb * e[0] + d * e[1])]
    return None, hi / lo


def center(X):
    mu = [statistics.fmean(col) for col in zip(*X)]
    return [[v - m for v, m in zip(r, mu)] for r in X]


def standardize(X):
    cols = list(zip(*X))
    mu = [statistics.fmean(c) for c in cols]
    sd = [statistics.pstdev(c) for c in cols]
    return [[(v - m) / s for v, m, s in zip(r, mu, sd)] for r in X]


results = {"raw": [], "centred": [], "standardised": []}
for seed in range(20):
    X, y = make(seed)
    yc = [t - statistics.fmean(y) for t in y]
    for name, Z, t in (("raw", X, y), ("centred", center(X), yc), ("standardised", standardize(X), yc)):
        results[name].append(steps_to_converge(*moments(Z, t)))
print("7. median steps and condition number over 20 seeds (range of steps)")
for name, rows in results.items():
    ks = [k for k, _ in rows]
    print("  ", name, statistics.median(ks), "cond %.3g" % statistics.median(c for _, c in rows),
          "range", min(ks), max(ks))


# 8. Plain GD, momentum and Adam on f(w) = 0.1*w1^2 + 2*w2^2, start (5, 3)
def f(w):
    return 0.1 * w[0] ** 2 + 2 * w[1] ** 2


def grad(w):
    return [0.2 * w[0], 4 * w[1]]


def run(step, cap=20000, tol=1e-6):
    w, st = [5.0, 3.0], {}
    for k in range(cap):
        if f(w) < tol:
            return k
        w = step(w, st)
        if not f(w) < 1e12:
            return None
    return None


def gd(lr):
    return lambda w, st: [a - lr * g for a, g in zip(w, grad(w))]


def momentum(lr, beta):
    def step(w, st):
        v = st.get("v", [0.0, 0.0])
        st["v"] = [beta * vi + g for vi, g in zip(v, grad(w))]
        return [a - lr * vi for a, vi in zip(w, st["v"])]
    return step


def adam(lr, b1=0.9, b2=0.999, eps=1e-8):
    def step(w, st):
        t = st["t"] = st.get("t", 0) + 1
        g = grad(w)
        m = st["m"] = [b1 * a + (1 - b1) * gi for a, gi in zip(st.get("m", [0, 0]), g)]
        v = st["v"] = [b2 * a + (1 - b2) * gi * gi for a, gi in zip(st.get("v", [0, 0]), g)]
        return [wi - lr * (mi / (1 - b1 ** t)) / (math.sqrt(vi / (1 - b2 ** t)) + eps)
                for wi, mi, vi in zip(w, m, v)]
    return step


LRS = (0.01, 0.03, 0.05, 0.1, 0.2, 0.3, 0.45, 0.5, 0.7, 1.0)


def best(make_step, settings):
    """Fewest steps over a grid of settings, skipping runs that diverge or stall."""
    runs = [(run(make_step(*s)), s) for s in settings]
    return min((k, s) for k, s in runs if k is not None)


print("8. fewest steps until f < 1e-6 over a grid of learning rates (and betas)")
print("   GD:", best(gd, [(lr,) for lr in LRS]))
print("   momentum:", best(momentum, [(lr, b) for lr in LRS for b in (0.5, 0.8, 0.9, 0.95)]))
print("   Adam:", best(adam, [(lr,) for lr in LRS]))
print("   momentum, beta 0.9, across lr:", {lr: run(momentum(lr, 0.9)) for lr in (0.01, 0.05, 0.3)})


def final_loss(step, n=200):
    w, st = [5.0, 3.0], {}
    for _ in range(n):
        w = step(w, st)
    return f(w)


print("   f after 200 steps of GD: eta=0.5 ->", final_loss(gd(0.5)), " eta=0.51 ->", "%.3g" % final_loss(gd(0.51)))
print("   (the steep factor is 1 - 4*eta: -1 at 0.5, so it oscillates; -1.04 at 0.51, so it diverges)")
print("   only the learning rate was searched for Adam; its betas stayed at 0.9 and 0.999")

# 9. Adam's first step is about lr whatever the gradient scale (b1 = 0.9, b2 = 0.999)
print("9. Adam first step at lr=0.001")
for g in (0.001, 1.0, 100.0):
    m_hat = (0.1 * g) / (1 - 0.9)
    v_hat = (0.001 * g * g) / (1 - 0.999)
    print("  ", g, 0.001 * m_hat / (math.sqrt(v_hat) + 1e-8))

# 10. Separable data: the weight never stops growing without a penalty
X1, Y1 = [-2, -1, 1, 2], [0, 0, 1, 1]
for lam in (0.0, 0.1):
    w, seen = 0.0, {}
    for t in range(1, 100001):
        g = sum((sigmoid(w * x) - y) * x for x, y in zip(X1, Y1)) / 4 + lam * w
        w -= 0.5 * g
        if t in (10, 100, 1000, 10000, 100000):
            seen[t] = round(w, 3)
    print("10. L2 =", lam, seen)
print("odds ratio for w = 0.7:", round(math.exp(0.7), 2))


# 11. Curvature (second difference) of each loss in the logit z, label y = 1
def curvature(F, z, h=1e-3):
    return (F(z + h) - 2 * F(z) + F(z - h)) / h ** 2


print("11. curvature in z: squared error on a sigmoid, cross-entropy")
for z in (-6, -4, -2, 0, 2):
    print("  ", z, round(curvature(lambda t: 0.5 * (1 - sigmoid(t)) ** 2, z), 5),
          round(curvature(lambda t: -math.log(sigmoid(t)), z), 5))


# 12. Two strongly correlated features: the coefficients move, the prediction does not
def fit2(seed, n=50):
    r = random.Random(seed)
    x1 = [r.uniform(50, 150) for _ in range(n)]
    x2 = [0.9 * a + r.gauss(0, 1) for a in x1]            # a second measure of nearly the same thing
    y = [3 * a + r.gauss(0, 5) for a in x1]               # only x1 truly matters
    cols = [[1.0] * n, x1, x2]
    A = [[sum(p * q for p, q in zip(u, v)) for v in cols] for u in cols]
    rhs = [sum(p * t for p, t in zip(u, y)) for u in cols]
    for c in range(3):                                    # Gaussian elimination, floats
        p = max(range(c, 3), key=lambda i: abs(A[i][c]))
        A[c], A[p], rhs[c], rhs[p] = A[p], A[c], rhs[p], rhs[c]
        for i in range(c + 1, 3):
            m = A[i][c] / A[c][c]
            A[i] = [u - m * v for u, v in zip(A[i], A[c])]
            rhs[i] -= m * rhs[c]
    w = [0.0] * 3
    for i in (2, 1, 0):
        w[i] = (rhs[i] - sum(A[i][k] * w[k] for k in range(i + 1, 3))) / A[i][i]
    return w


print("12. coefficients (intercept, x1, x2) and prediction at x1=100, x2=90")
for seed in (1, 2, 3):
    w = fit2(seed)
    print("  ", seed, [round(v, 2) for v in w], round(w[0] + 100 * w[1] + 90 * w[2], 1))

Decision trees, random forests and gradient boosting

Trees, ensembles and classical models

Show the code (362 lines)

Python

import math
import random
import statistics
from fractions import Fraction as Fr


# ---------- A small CART regression tree, a forest and a boosting loop (squared error) ----------
def best_split(X, y, idx, feats, min_leaf):
    """Greedy search: the (feature, threshold) that most lowers the sum of squared errors."""
    n = len(idx)
    tot, tot2 = sum(y[i] for i in idx), sum(y[i] ** 2 for i in idx)
    parent, best = tot2 - tot * tot / n, None
    for f in feats:
        order = sorted(idx, key=lambda i: X[i][f])
        s = s2 = 0.0
        for k in range(1, n):
            v = y[order[k - 1]]
            s, s2 = s + v, s2 + v * v
            a, b = X[order[k - 1]][f], X[order[k]][f]
            if k < min_leaf or n - k < min_leaf or a == b:
                continue
            gain = parent - ((s2 - s * s / k) + ((tot2 - s2) - (tot - s) ** 2 / (n - k)))
            if best is None or gain > best[0] + 1e-12:
                best = (gain, f, (a + b) / 2)
    return best


def grow(X, y, idx, depth, max_depth, min_leaf, max_features, rng, imp=None):
    mean = sum(y[i] for i in idx) / len(idx)
    if depth == max_depth or len(idx) < 2 * min_leaf or all(y[i] == y[idx[0]] for i in idx):
        return mean
    d = len(X[0])
    feats = range(d) if max_features >= d else rng.sample(range(d), max_features)
    best = best_split(X, y, idx, feats, min_leaf)
    if best is None or best[0] <= 1e-12:
        return mean
    gain, f, thr = best
    if imp is not None:
        imp[f] += gain
    left = [i for i in idx if X[i][f] <= thr]
    right = [i for i in idx if X[i][f] > thr]
    return (f, thr, grow(X, y, left, depth + 1, max_depth, min_leaf, max_features, rng, imp),
            grow(X, y, right, depth + 1, max_depth, min_leaf, max_features, rng, imp))


def predict(tree, x):
    while isinstance(tree, tuple):
        tree = tree[2] if x[tree[0]] <= tree[1] else tree[3]
    return tree


def fit_tree(X, y, max_depth=10**9, min_leaf=1, max_features=10**9, rng=None, imp=None):
    return grow(X, y, list(range(len(X))), 0, max_depth, min_leaf, max_features, rng or random.Random(0), imp)


def fit_forest(X, y, B, max_features, rng, imp=None):
    """B trees on bootstrap samples; returns the trees and each tree's out-of-bag row indices."""
    n, trees, oobs = len(X), [], []
    for _ in range(B):
        boot = [rng.randrange(n) for _ in range(n)]
        seen = set(boot)
        trees.append(grow(X, y, boot, 0, 10**9, 1, max_features, rng, imp))
        oobs.append([i for i in range(n) if i not in seen])
    return trees, oobs


def forest_mean(trees, x):
    return statistics.fmean(predict(t, x) for t in trees)


def boost(X, y, Xv, yv, lr, rounds, depth):
    """Gradient boosting for squared error: each tree fits the residuals. Returns validation MSE per round."""
    F0 = statistics.fmean(y)
    F, Fv = [F0] * len(X), [F0] * len(Xv)
    curve = [mse(Fv, yv)]
    for _ in range(rounds):
        tree = fit_tree(X, [t - p for t, p in zip(y, F)], max_depth=depth)
        F = [p + lr * predict(tree, x) for p, x in zip(F, X)]
        Fv = [p + lr * predict(tree, x) for p, x in zip(Fv, Xv)]
        curve.append(mse(Fv, yv))
    return curve


def mse(pred, y):
    return statistics.fmean((a - b) ** 2 for a, b in zip(pred, y))


def gini(counts):
    n = sum(counts)
    return 1 - sum(Fr(c, n) ** 2 for c in counts)


def entropy(counts):
    n = sum(counts)
    return -sum((c / n) * math.log2(c / n) for c in counts if c)


def med(values):
    return round(statistics.median(values), 3)


D = 6


def f_lin(x):
    return 2 * x[0] + 2 * x[1] + x[2] + x[3] + x[4] + x[5]


def f_irr(x):
    return 3 * (x[0] > 0.3) + 2 * math.sin(6 * x[1]) + x[2] * (x[3] > 0)


def make(seed, n, fn, noise):
    r = random.Random(seed)
    X = [[r.uniform(-1, 1) for _ in range(D)] for _ in range(n)]
    return X, [fn(x) + r.gauss(0, noise) for x in X]


def circle(seed, n, flip=0.15):
    r = random.Random(seed)
    X = [[r.uniform(-1, 1), r.uniform(-1, 1)] for _ in range(n)]
    y = [int(a * a + b * b < 0.5) for a, b in X]
    return X, [1 - t if r.random() < flip else t for t in y]


def acc(model, X, y):
    return statistics.fmean((predict(model, x) >= 0.5) == t for x, t in zip(X, y))


# 1. Splits by hand: Gini and entropy gain
for name, parent, kids in (("5/5 -> (4,1),(1,4)", (5, 5), ((4, 1), (1, 4))),
                           ("6/4 -> (5,0),(1,4)", (6, 4), ((5, 0), (1, 4)))):
    n = sum(parent)
    g = gini(parent) - sum(Fr(sum(k), n) * gini(k) for k in kids)
    e = entropy(parent) - sum(sum(k) / n * entropy(k) for k in kids)
    print("1.", name, "gini parent", gini(parent), "child ginis", [str(gini(k)) for k in kids],
          "gini gain", g, "entropy gain %.4f" % e)

# 2. Greedy is myopic: on XOR no first split helps, yet two splits are perfect
pts = [(a, b, int(a != b)) for a in (0, 1) for b in (0, 1) for _ in range(5)]
for f in (0, 1):
    kids = [[p[2] for p in pts if p[f] == v] for v in (0, 1)]
    gain = gini((10, 10)) - Fr(1, 2) * sum(gini((len(k) - sum(k), sum(k))) for k in kids)
    print("2. XOR split on feature", f, "gain", gain)
for v in (0, 1):                                  # split on feature 0 anyway, then on feature 1
    side = [p for p in pts if p[0] == v]
    kids = [[p[2] for p in side if p[1] == w] for w in (0, 1)]
    print("   child gini", gini((len(side) - sum(p[2] for p in side), sum(p[2] for p in side))),
          "-> grandchildren", [str(gini((len(k) - sum(k), sum(k)))) for k in kids])

# 3. Depth and leaf size on a noisy circle (15% of labels flipped: best possible accuracy 0.85)
print("3. median train and validation accuracy over 20 seeds")
for label, kw in (("depth 1", dict(max_depth=1)), ("depth 2", dict(max_depth=2)), ("depth 4", dict(max_depth=4)),
                  ("depth 8", dict(max_depth=8)), ("no limit", {}), ("leaf >= 10", dict(min_leaf=10)),
                  ("leaf >= 20", dict(min_leaf=20))):
    tr, va = [], []
    for s in range(20):
        X, y = circle(s, 200)
        Xv, yv = circle(1000 + s, 2000)
        m = fit_tree(X, y, **kw)
        tr.append(acc(m, X, y))
        va.append(acc(m, Xv, yv))
    print("  ", label, med(tr), med(va))

# 4. The variance formula, exactly: rho sigma^2 + (1 - rho) sigma^2 / B
for rho, B in ((Fr(1, 2), 4), (Fr(3, 10), 10)):
    total = sum(1 if i == j else rho for i in range(B) for j in range(B))     # 1' Sigma 1, unit variances
    print("4. rho", rho, "B", B, "variance of the mean", total / B ** 2, "formula", rho + (1 - rho) / B)

# 5. Real trees: variance over 30 training sets, bagging versus a random forest
R, B = 30, 100
Xt, _ = make(999, 40, f_lin, 0)
truth = [f_lin(x) for x in Xt]
print("5. 30 training sets of 200 rows; variance of the prediction at 40 fixed points (noise variance 1)")
for name, mf in (("bagging (all 6 features)", 6), ("random forest (2 of 6)", 2)):
    P = []                                   # P[s][b][j]: tree b of training set s at test point j
    for s in range(R):
        X, y = make(s, 200, f_lin, 1.0)
        trees, _ = fit_forest(X, y, B, mf, random.Random(10000 + s))
        P.append([[predict(t, x) for x in Xt] for t in trees])
    J = range(len(Xt))
    ens = lambda s, j, k: statistics.fmean(P[s][b][j] for b in range(k))
    sigma2 = statistics.fmean(statistics.pvariance([P[s][b][j] for s in range(R)]) for b in range(B) for j in J)
    row = {k: statistics.fmean(statistics.pvariance([ens(s, j, k) for s in range(R)]) for j in J) for k in (1, 5, 25, 100)}
    rho = (row[100] - sigma2 / B) / (sigma2 * (1 - 1 / B))
    bias2 = statistics.fmean((statistics.fmean(ens(s, j, B) for s in range(R)) - truth[j]) ** 2 for j in J)
    print("   %s: one-tree variance %.3f, implied rho %.3f, squared bias %.3f" % (name, sigma2, rho, bias2))
    print("     trees -> variance:", {k: round(v, 3) for k, v in row.items()},
          "| formula:", {k: round(rho * sigma2 + (1 - rho) * sigma2 / k, 3) for k in row},
          "| floor rho*sigma2 = %.3f" % (rho * sigma2))

# 6. Out-of-bag: about 36.8% of rows are left out of each bootstrap, and they give a free estimate
print("6a. expected out-of-bag fraction", {n: round((1 - 1 / n) ** n, 4) for n in (10, 100, 1000)}, "limit 1/e = %.4f" % math.exp(-1))
oob_acc, val_acc = [], []
for s in range(20):
    X, y = circle(s, 200)
    Xv, yv = circle(1000 + s, 2000)
    trees, oobs = fit_forest(X, y, 100, 1, random.Random(s))
    votes = [[] for _ in X]
    for t, oob in zip(trees, oobs):
        for i in oob:
            votes[i].append(predict(t, X[i]))
    oob_acc.append(statistics.fmean((statistics.fmean(v) >= 0.5) == t for v, t in zip(votes, y) if v))
    val_acc.append(statistics.fmean((forest_mean(trees, x) >= 0.5) == t for x, t in zip(Xv, yv)))
print("6b. 100-tree forest, 20 datasets: median OOB accuracy %.3f, validation %.3f, median gap %.3f"
      % (statistics.median(oob_acc), statistics.median(val_acc), statistics.median(abs(a - b) for a, b in zip(oob_acc, val_acc))))

# 7. Gradient boosting by hand (squared error), exact; then the log-loss gradient by finite differences
xs, ys, eta = [1, 2, 3, 4, 5, 6], [Fr(v) for v in (1, 3, 2, 6, 7, 9)], Fr(1, 2)
F = [sum(ys) / 6] * 6
print("7a. F0 =", F[0], "mse", sum((t - p) ** 2 for t, p in zip(ys, F)) / 6)
for rnd in (1, 2):
    res = [t - p for t, p in zip(ys, F)]
    best = None
    for k in range(1, 6):                      # stump: split after the k-th point, leaves are the residual means
        lm, rm = sum(res[:k]) / k, sum(res[k:]) / (6 - k)
        sse = sum((v - lm) ** 2 for v in res[:k]) + sum((v - rm) ** 2 for v in res[k:])
        if best is None or sse < best[0]:
            best = (sse, k, lm, rm)
    _, k, lm, rm = best
    F = [p + eta * (lm if i < k else rm) for i, p in enumerate(F)]
    print("   round %d: residuals %s, split after x=%d, leaves %s and %s, new F %s, mse %s"
          % (rnd, [str(v) for v in res], xs[k - 1], lm, rm, [str(v) for v in F],
             sum((t - p) ** 2 for t, p in zip(ys, F)) / 6))
sigmoid = lambda z: 1 / (1 + math.exp(-z))
for y1 in (1, 0):
    loss = lambda z: -(y1 * math.log(sigmoid(z)) + (1 - y1) * math.log(1 - sigmoid(z)))
    print("7b. y=%d: numerical d(loss)/dF at F=0.7: %.6f, p - y = %.6f"
          % (y1, (loss(0.7 + 1e-6) - loss(0.7 - 1e-6)) / 2e-6, sigmoid(0.7) - y1))

# 8. Learning rate, rounds and depth (validation MSE; noise floor 1.0), median of 6 datasets
print("8. best validation MSE, the round it happens at, and MSE after 800 rounds")
for lr, depth in ((1.0, 1), (0.1, 1), (0.01, 1), (0.1, 3)):
    curves = []
    for s in range(6):
        X, y = make(s, 200, f_lin, 1.0)
        Xv, yv = make(500 + s, 1000, f_lin, 1.0)
        curves.append(boost(X, y, Xv, yv, lr, 800, depth))
    print("   lr %-4s depth %d: best %.3f at round %s, after 800 rounds %.3f"
          % (lr, depth, statistics.median(min(c) for c in curves), statistics.median(c.index(min(c)) for c in curves),
             statistics.median(c[-1] for c in curves)))


# 9. Which model, on which data? Validation MSE, median of 6 datasets of 200 rows
def ols(X, y):
    A = [[1.0] + x for x in X]
    k = len(A[0])
    M = [[sum(r[i] * r[j] for r in A) for j in range(k)] + [sum(r[i] * t for r, t in zip(A, y))] for i in range(k)]
    for c in range(k):
        p = max(range(c, k), key=lambda i: abs(M[i][c]))
        M[c], M[p] = M[p], M[c]
        for i in range(k):
            if i != c:
                m = M[i][c] / M[c][c]
                M[i] = [a - m * b for a, b in zip(M[i], M[c])]
    return [M[i][k] / M[i][i] for i in range(k)]


for label, fn, noise in (("linear truth, noise 1.0 (floor 1.0)", f_lin, 1.0),
                         ("steps and a sine, noise 0.5 (floor 0.25)", f_irr, 0.5)):
    out = {}
    for s in range(6):
        X, y = make(s, 200, fn, noise)
        Xv, yv = make(500 + s, 1000, fn, noise)
        w = ols(X, y)
        out.setdefault("linear", []).append(mse([w[0] + sum(a * b for a, b in zip(w[1:], x)) for x in Xv], yv))
        out.setdefault("one deep tree", []).append(mse([predict(fit_tree(X, y), x) for x in Xv], yv))
        for name, mf in (("bagged trees", 6), ("forest, 2 of 6", 2)):
            trees, _ = fit_forest(X, y, 50, mf, random.Random(s))
            out.setdefault(name, []).append(mse([forest_mean(trees, x) for x in Xv], yv))
        c = boost(X[:150], y[:150], X[150:], y[150:], 0.1, 300, 3)     # pick the rounds on the last 50 rows
        out.setdefault("boosting", []).append(boost(X, y, Xv, yv, 0.1, max(c.index(min(c)), 1), 3)[-1])
    print("9.", label, {k: med(v) for k, v in out.items()})

# 10. Trees cannot extrapolate
X = [[i / 10] for i in range(101)]
w = ols(X, [2 * v[0] for v in X])
print("10. trained on x in [0, 10] with y = 2x; at x = 15 the tree says", predict(fit_tree(X, [2 * v[0] for v in X]), [15]),
      "and the line says", round(w[0] + w[1] * 15, 3))


# 11. Importance: impurity (training) versus permutation (validation), and a correlated copy
def signal_data(seed, n):
    r = random.Random(seed)
    X, y = [], []
    for _ in range(n):
        s = r.random() < 0.5
        y.append(int(s if r.random() < 0.75 else not s))
        X.append([1.0 if s else 0.0, r.random(), r.random()])     # a binary signal and two noise columns
    return X, y


def forest_acc(trees, X, y):
    return statistics.fmean((forest_mean(trees, x) >= 0.5) == t for x, t in zip(X, y))


def shuffled(X, cols, rng):
    perm = list(range(len(X)))
    rng.shuffle(perm)
    out = [x[:] for x in X]
    for k, p in enumerate(perm):
        for j in cols:
            out[k][j] = X[p][j]
    return out


shares, drops, tr_acc, va_acc, alone, copy_a, copy_b, both = [], [], [], [], [], [], [], []
for s in range(20):
    X, y = signal_data(s, 300)
    Xv, yv = signal_data(100 + s, 1000)
    rng, imp = random.Random(s), [0.0] * 3
    trees, _ = fit_forest(X, y, 50, 2, random.Random(s), imp)
    shares.append([v / sum(imp) for v in imp])
    base = forest_acc(trees, Xv, yv)
    drops.append([base - forest_acc(trees, shuffled(Xv, [j], rng), yv) for j in range(3)])
    tr_acc.append(forest_acc(trees, X, y))
    va_acc.append(base)
    X4, Xv4 = [x + [x[0]] for x in X], [x + [x[0]] for x in Xv]         # add an exact copy of the signal
    trees4, _ = fit_forest(X4, y, 50, 2, random.Random(s))
    base4 = forest_acc(trees4, Xv4, yv)
    copy_a.append(base4 - forest_acc(trees4, shuffled(Xv4, [0], rng), yv))
    copy_b.append(base4 - forest_acc(trees4, shuffled(Xv4, [3], rng), yv))
    both.append(base4 - forest_acc(trees4, shuffled(Xv4, [0, 3], rng), yv))
    alone.append(drops[-1][0])
col = lambda rows: [med(r[j] for r in rows) for j in range(3)]
print("11a. columns: binary signal, noise, noise. Impurity importance share (training):", col(shares))
print("     permutation drop on validation:", col(drops), "| forest train accuracy %.3f, validation %.3f"
      % (statistics.median(tr_acc), statistics.median(va_acc)))
print("11b. permuting the signal: alone %.3f; with a copy, the original %.3f and the copy %.3f; both together %.3f"
      % tuple(statistics.median(v) for v in (alone, copy_a, copy_b, both)))


# 12. Missing values: let the split choose a side, or fill in the mean
def gaps(seed, n):
    r = random.Random(seed)
    X, y = [], []
    for _ in range(n):
        label = int(r.random() < 0.5)
        X.append(None if r.random() < (0.4 if label else 0.05) else r.gauss(0.5 * label, 1))   # missingness is a signal
        y.append(label)
    return X, y


def one_split(X, y, Xv, yv, learn_side):
    """Best one-question model on X; returns validation accuracy. Missing goes left or right, or is mean-filled."""
    mean = statistics.fmean(x for x in X if x is not None)
    prep = (lambda v: v) if learn_side else (lambda v: mean if v is None else v)
    rule = lambda x, thr, left_if_missing, lc: lc if (left_if_missing if x is None else x <= thr) else 1 - lc
    cuts = sorted({x for x in X if x is not None})[::5]
    options = [(t, m, lc) for t in cuts for m in ((True, False) if learn_side else (True,)) for lc in (0, 1)]
    best = max(options, key=lambda o: sum(rule(prep(x), *o) == t for x, t in zip(X, y)))
    return statistics.fmean(rule(prep(x), *best) == t for x, t in zip(Xv, yv))


learned, filled = [], []
for s in range(20):
    X, y = gaps(s, 500)
    Xv, yv = gaps(100 + s, 5000)
    learned.append(one_split(X, y, Xv, yv, True))
    filled.append(one_split(X, y, Xv, yv, False))
print("12. one-split model, validation accuracy: side learned for missing %.3f, mean-filled %.3f"
      % (statistics.median(learned), statistics.median(filled)))

k-NN, k-means, PCA, SVM and naive Bayes: the classical toolkit

Trees, ensembles and classical models

Show the code (319 lines)

Python

import math
import random
import statistics
from fractions import Fraction as Fr

d2 = lambda a, b: math.dist(a, b) ** 2
med = lambda v: round(statistics.median(v), 3)
mean_pt = lambda pts: [sum(c) / len(pts) for c in zip(*pts)]

def blobs(centers, n, sd, rng):
    X = [[rng.gauss(m, sd) for m in c] for c in centers for _ in range(n)]
    return X, [lab for lab in range(len(centers)) for _ in range(n)]

def purity(lab, y):                       # share of points in the majority true class of their cluster (noise = one cluster)
    return sum(max(sum(l == c and t == k for l, t in zip(lab, y)) for k in set(y)) for c in set(lab)) / len(y)

# ---------- 1. k-NN: distance concentration, the choice of k, noise columns, scale ----------
def disc(seed, n, flip=0.0, noise_scales=()):          # label 1 inside a disc; optional extra noise columns
    r = random.Random(seed)
    X = [[r.uniform(-1, 1), r.uniform(-1, 1)] for _ in range(n)]
    y = [int(a * a + b * b < 0.5) ^ (r.random() < flip) for a, b in X]
    return [x + [r.uniform(-1, 1) * s for s in noise_scales] for x in X], y

def knn_acc(Xtr, ytr, Xte, yte, ks):
    hits = dict.fromkeys(ks, 0)
    for x, t in zip(Xte, yte):
        order = sorted(range(len(Xtr)), key=lambda i: d2(x, Xtr[i]))
        for k in ks:
            hits[k] += (sum(ytr[i] for i in order[:k]) * 2 > k) == t
    return {k: h / len(yte) for k, h in hits.items()}

print("1a. 200 uniform points in [0,1]^d, median over 10 queries")
for d in (2, 10, 100, 1000):
    r = random.Random(d)
    P = [[r.random() for _ in range(d)] for _ in range(200)]
    runs = []
    for _ in range(10):
        q = [r.random() for _ in range(d)]
        ds = [math.dist(q, p) for p in P]
        runs.append(min(ds) / max(ds))
    print("   d=%-5d nearest/farthest %.3f" % (d, med(runs)))

res = {k: [] for k in (1, 5, 15, 51)}
for s in range(40):
    for k, a in knn_acc(*disc(s, 200, 0.15), *disc(100 + s, 1000, 0.15), tuple(res)).items():
        res[k].append(a)
print("1b. disc with 15% flipped labels (ceiling 0.85), 200 train rows, median validation accuracy by k:",
      {k: med(v) for k, v in res.items()})
print("1c. 5-NN validation accuracy on a clean disc plus extra columns of uniform noise (median of 40 datasets)")
for label, scales in (("no extra columns", ()), ("2 noise columns", (1,) * 2), ("8 noise columns", (1,) * 8),
                      ("32 noise columns", (1,) * 32), ("1 noise column, scale 1", (1,)), ("1 noise column, scale 100", (100,))):
    print("   %-28s %.3f" % (label, med(knn_acc(*disc(s, 200, 0, scales), *disc(100 + s, 300, 0, scales), (5,))[5] for s in range(40))))

# ---------- 2. k-means, DBSCAN, single linkage, silhouette ----------
def kmeans(X, k, rng, plus=True):
    C = [rng.choice(X)] if plus else rng.sample(X, k)
    while plus and len(C) < k:                                    # k-means++: next centre drawn with weight D(x)^2
        C.append(rng.choices(X, weights=[min(d2(x, c) for c in C) for x in X])[0])
    C, hist = [c[:] for c in C], []
    for _ in range(100):
        lab = [min(range(k), key=lambda j: d2(x, C[j])) for x in X]                    # assign
        hist.append(sum(d2(x, C[l]) for x, l in zip(X, lab)))
        new = [mean_pt([x for x, l in zip(X, lab) if l == j]) if j in lab else C[j] for j in range(k)]   # update
        if new == C:
            break
        C = new
    return C, lab, hist

def best_of(X, k, starts=5):
    return min((kmeans(X, k, random.Random(s)) for s in range(starts)), key=lambda t: t[2][-1])

def dbscan(X, eps, m):
    n, lab, cid = len(X), [None] * len(X), -1
    nb = [[j for j in range(n) if d2(X[i], X[j]) <= eps * eps] for i in range(n)]
    for i in range(n):
        if lab[i] is not None or len(nb[i]) < m:
            continue
        cid += 1
        lab[i], stack = cid, [i]
        while stack:
            for j in nb[stack.pop()]:
                if lab[j] is None:
                    lab[j] = cid
                    if len(nb[j]) >= m:
                        stack.append(j)
    return [-1 if l is None else l for l in lab]

def single_linkage(X, k):                                         # merge the closest pair of clusters until k remain
    parent, comps = list(range(len(X))), len(X)

    def find(a):
        while parent[a] != a:
            a = parent[a] = parent[parent[a]]
        return a
    for _, i, j in sorted((d2(X[i], X[j]), i, j) for i in range(len(X)) for j in range(i)):
        if find(i) != find(j):
            parent[find(i)] = find(j)
            comps -= 1
            if comps == k:
                break
    return [find(i) for i in range(len(X))]

def silhouette(X, lab):
    out = []
    for i, x in enumerate(X):
        by = {}
        for j, z in enumerate(X):
            if j != i:
                by.setdefault(lab[j], []).append(math.dist(x, z))
        a = statistics.fmean(by.pop(lab[i]))
        out.append((min(statistics.fmean(v) for v in by.values()) - a) / max(a, min(statistics.fmean(v) for v in by.values())))
    return statistics.fmean(out)

xs, C = [Fr(v) for v in (1, 2, 4, 9, 10, 12)], [Fr(1), Fr(2)]     # 2a. the loop by hand, exact
for it in range(1, 5):
    lab = [min((0, 1), key=lambda j: abs(x - C[j])) for x in xs]
    new = [sum(x for x, l in zip(xs, lab) if l == j) / lab.count(j) for j in (0, 1)]
    print("2a. iteration", it, "centres", [str(c) for c in C], "assign", lab,
          "J", sum((x - C[l]) ** 2 for x, l in zip(xs, lab)), "-> new centres", [str(c) for c in new])
    if new == C:
        break
    C = new

X, _ = blobs([(0, 0), (4, 0), (8, 0), (0, 5), (4, 5)], 50, 0.8, random.Random(1))      # 2b. initialisation, 5 blobs
runs = {}
for name, plus in (("random start", False), ("k-means++", True)):
    for s in range(500):
        hist = kmeans(X, 5, random.Random(s), plus)[2]
        assert all(a >= b - 1e-9 for a, b in zip(hist, hist[1:])), "J must never increase"
        runs.setdefault(name, []).append(hist[-1])
best = min(min(v) for v in runs.values())
for name, v in runs.items():
    print("2b. %-12s one start per run, 500 runs: median J %.1f, worst %.1f, within 1%% of the best J seen (%.1f): %.2f of runs"
          % (name, statistics.median(v), max(v), best, sum(j <= 1.01 * best for j in v) / len(v)))
print("    J never rose in any iteration of the 1,000 runs (asserted)")

X, _ = blobs([(0, 0), (6, 0), (0, 6), (6, 6)], 50, 1.0, random.Random(2))               # 2c. choosing k, 4 blobs
print("2c. k: inertia (best of 5 starts), silhouette")
for k in range(2, 9):
    _, lab, hist = best_of(X, k)
    print("   %d: %8.1f  %.3f" % (k, hist[-1], silhouette(X, lab)))

def rings(seed, n=150):
    r = random.Random(seed)
    ang = [r.uniform(0, 2 * math.pi) for _ in range(2 * n)]
    return ([[(1 + 2 * (i >= n)) * f(a) + r.gauss(0, 0.1) for f in (math.cos, math.sin)] for i, a in enumerate(ang)],
            [int(i >= n) for i in range(2 * n)])

out = {"k-means": [], "single linkage": [], 0.3: [], 0.5: [], 0.8: []}                  # 2d. failures
for s in range(30):
    X, y = rings(s)
    out["k-means"].append(purity(best_of(X, 2)[1], y))
    out["single linkage"].append(purity(single_linkage(X, 2), y))
    for eps in (0.3, 0.5, 0.8):
        db = dbscan(X, eps, 5)
        out[eps].append((len(set(db) - {-1}), db.count(-1), purity(db, y)))
print("2d. two rings (radii 1 and 3, 150 points each), median of 30 datasets: purity k-means %.3f, single linkage %.3f"
      % (med(out["k-means"]), med(out["single linkage"])))
for eps in (0.3, 0.5, 0.8):
    print("    DBSCAN eps %.1f, min_samples 5: clusters %s, noise points %s, purity %.3f" % ((eps,) + tuple(med(c) for c in zip(*out[eps]))))

raw, std, alone, share = [], [], 0, []
for s in range(30):
    r = random.Random(s)
    X, y = blobs([(0,), (4,)], 100, 1.0, r)
    X = [[a[0], r.gauss(0, 50)] for a in X]                      # column 2 is pure noise, in large units
    mu, sd = mean_pt(X), [statistics.pstdev(c) for c in zip(*X)]
    raw.append(purity(best_of(X, 2, 3)[1], y))
    std.append(purity(best_of([[(v - m) / q for v, m, q in zip(x, mu, sd)] for x in X], 2, 3)[1], y))
    X, y = blobs([(0, 0), (8, 0)], 100, 1.0, random.Random(s))
    lab = best_of(X + [[0.0, 100.0]], 2)[1]                      # one outlier far above the first blob
    alone += lab.count(lab[-1]) == 1
    share.append(max(lab[:200].count(0), lab[:200].count(1)) / 200)
print("    column 2 pure noise with sd 50, blobs 4 apart in column 1: median purity raw %.3f, standardised %.3f" % (med(raw), med(std)))
print("    two blobs 8 apart plus one outlier at (0, 100), k=2: outlier alone in its own cluster in %d of 30 datasets; "
      "median share of the 200 blob points in the larger cluster %.2f" % (alone, med(share)))

# ---------- 3. PCA: centre, covariance, eigenvectors, project ----------
def jacobi_eigh(A):                       # eigenvalues (descending) and eigenvectors (rows) of a symmetric matrix
    n, A = len(A), [r[:] for r in A]
    V = [[float(i == j) for j in range(n)] for i in range(n)]
    for _ in range(60):
        if sum(A[i][j] ** 2 for i in range(n) for j in range(n) if i != j) < 1e-24:
            break
        for p in range(n):
            for q in range(p + 1, n):
                if A[p][q] == 0:
                    continue
                th = (A[q][q] - A[p][p]) / (2 * A[p][q])
                t = (1 if th >= 0 else -1) / (abs(th) + math.sqrt(th * th + 1))
                c = 1 / math.sqrt(t * t + 1)
                s = t * c
                for M in (A, V):                                   # rotate columns p and q
                    for k in range(n):
                        M[k][p], M[k][q] = c * M[k][p] - s * M[k][q], s * M[k][p] + c * M[k][q]
                for k in range(n):                                 # rotate rows p and q of A
                    A[p][k], A[q][k] = c * A[p][k] - s * A[q][k], s * A[p][k] + c * A[q][k]
    order = sorted(range(n), key=lambda i: -A[i][i])
    return [A[i][i] for i in order], [[V[k][i] for k in range(n)] for i in order]

def pca(X):                               # centre, covariance with n - 1, eigen-decompose
    mu = mean_pt(X)
    Xc = [[v - m for v, m in zip(x, mu)] for x in X]
    S = [[sum(r[i] * r[j] for r in Xc) / (len(X) - 1) for j in range(len(mu))] for i in range(len(mu))]
    return (mu, Xc) + jacobi_eigh(S)

raw = [(8, 18), (9, 19), (10, 21), (10, 22), (11, 20), (12, 20)]                   # 3a. by hand, exact
mu = [Fr(sum(p[i] for p in raw), 6) for i in (0, 1)]
Xc = [[Fr(p[i]) - mu[i] for i in (0, 1)] for p in raw]
S = [[sum(r[i] * r[j] for r in Xc) / 5 for j in (0, 1)] for i in (0, 1)]
print("3a. mean", [str(m) for m in mu], "covariance (n - 1)", [[str(v) for v in r] for r in S])
for lam, v in ((3, (1, 1)), (1, (1, -1))):
    print("    S @ %s = %s, which is %d times the vector" % (v, [str(S[i][0] * v[0] + S[i][1] * v[1]) for i in (0, 1)], lam))
print("    scores on (1,1)/sqrt2, times sqrt2:", [str(r[0] + r[1]) for r in Xc],
      "| squared error of the 1-component fit", sum((r[0] - r[1]) ** 2 / 2 for r in Xc), "= (n - 1) x dropped eigenvalue =", 5 * 1)

r = random.Random(3)                                                                # 3b. five columns, two hidden factors
U = [(1, 1, 0.5, 0, 0), (0, 0, 0.5, 1, 1)]
F = [(r.gauss(0, 3), r.gauss(0, 2)) for _ in range(500)]
X = [[f[0] * U[0][j] + f[1] * U[1][j] + r.gauss(0, 0.5) for j in range(5)] for f in F]
_, Xc, vals, vecs = pca(X)
ratios = [v / sum(vals) for v in vals]
print("3b. eigenvalues", [round(v, 3) for v in vals], "ratios", [round(v, 3) for v in ratios],
      "cumulative", [round(sum(ratios[:k + 1]), 3) for k in range(5)])
for k in (1, 2, 3):
    sse = sum(d2(x, [sum(sum(a * b for a, b in zip(x, v)) * v[j] for v in vecs[:k]) for j in range(5)]) for x in Xc)
    print("    keep %d: squared error / (n - 1) = %.4f, sum of dropped eigenvalues = %.4f" % (k, sse / 499, sum(vals[k:])))

r = random.Random(4)                                                                # 3c. units matter
X = [[a, 0.8 * a + r.gauss(0, 0.6), r.gauss(0, 1000)] for a in (r.gauss(0, 1) for _ in range(500))]
sd = [statistics.pstdev(c) for c in zip(*X)]
for label, data in (("raw", X), ("standardised", [[(v - m) / q for v, m, q in zip(x, mean_pt(X), sd)] for x in X])):
    vals, vecs = pca(data)[2:]
    print("3c. %-12s PC1 share %.6f, PC1 loadings %s" % (label, vals[0] / sum(vals), [round(abs(c), 3) for c in vecs[0]]))

def hidden(seed, n):                      # column 1: big noise; column 2: the class signal, in a small-variance direction
    rr = random.Random(seed)
    y = [rr.randrange(2) for _ in range(n)]
    return [[rr.gauss(0, 10), 2 * t - 1 + rr.gauss(0, 0.3)] for t in y], y

acc = {"PC1 only": [], "PC2 only": [], "both columns": []}
for s in range(30):
    (X, y), (Xv, yv) = hidden(s, 150), hidden(100 + s, 300)
    mu, _, vals, vecs = pca(X)
    proj = lambda data, v: [[sum((a - m) * b for a, m, b in zip(x, mu, v))] for x in data]
    for i, name in ((0, "PC1 only"), (1, "PC2 only")):
        acc[name].append(knn_acc(proj(X, vecs[i]), y, proj(Xv, vecs[i]), yv, (5,))[5])
    acc["both columns"].append(knn_acc(X, y, Xv, yv, (5,))[5])
print("    5-NN validation accuracy when the signal sits in the low-variance direction:", {k: med(v) for k, v in acc.items()})

# ---------- 4. Support vector machine: hinge loss, margin, kernels ----------
def svm_fit(X, y, lam, epochs, rng):      # stochastic subgradient descent on lam/2 |w|^2 + mean hinge loss; bias = constant column
    w, t = [0.0] * (len(X[0]) + 1), 0
    for _ in range(epochs):
        for i in rng.sample(range(len(X)), len(X)):
            t += 1
            eta, x = 1 / (lam * t), X[i] + [1.0]
            hit = y[i] * sum(a * b for a, b in zip(w, x)) < 1
            w = [(1 - eta * lam) * a + (eta * y[i] * b if hit else 0.0) for a, b in zip(w, x)]
    return w

score = lambda w, x: sum(a * b for a, b in zip(w, x)) + w[-1]
two_class = lambda seed, n: (lambda X, y: (X, [2 * t - 1 for t in y]))(*blobs([(-1.5, 0), (1.5, 0)], n, 1.0, random.Random(seed)))
print("4a. linear SVM, two blobs centred at (-1.5, 0) and (1.5, 0), 200 train points, lam = 1 / (C n), median of 15 datasets")
for C in (0.01, 0.1, 1, 10):
    rows = []
    for s in range(15):
        (X, y), (Xv, yv) = two_class(s, 100), two_class(50 + s, 1000)
        w = svm_fit(X, y, 1 / (C * len(X)), 30, random.Random(s))
        m = [t * score(w, x) for x, t in zip(X, y)]
        rows.append((2 / math.hypot(*w[:2]), sum(v <= 1 for v in m), statistics.fmean(t * score(w, x) > 0 for x, t in zip(Xv, yv))))
    q = [med(c) for c in zip(*rows)]
    print("   C=%-5g margin width 2/|w| %.2f, points with margin <= 1: %3d, validation accuracy %.3f" % ((C,) + tuple(q)))

lift = lambda D: [x + [x[0] ** 2 + x[1] ** 2] for x in D]
res = {"linear": [], "with x1^2 + x2^2": [], "majority class": []}
for s in range(30):
    (Xd, yd), (Xe, ye) = disc(s, 300), disc(100 + s, 1000)
    yd, ye = [2 * t - 1 for t in yd], [2 * t - 1 for t in ye]
    for name, f in (("linear", lambda D: D), ("with x1^2 + x2^2", lift)):
        w = svm_fit(f(Xd), yd, 0.01, 20, random.Random(s))
        res[name].append(statistics.fmean(t * score(w, x) > 0 for x, t in zip(f(Xe), ye)))
    res["majority class"].append(max(ye.count(1), ye.count(-1)) / len(ye))
print("    disc data, validation accuracy of a linear SVM:", {k: med(v) for k, v in res.items()})

# ---------- 5. Naive Bayes ----------
words = ("buy", "free", "meeting")
train = {"spam": ["buy free free", "free buy"], "ham": ["meeting", "buy meeting meeting", "free meeting"]}
prior = {c: Fr(len(d), 5) for c, d in train.items()}
count = {c: [sum(t.split().count(w) for t in d) for w in words] for c, d in train.items()}
for alpha in (0, 1):
    theta = {c: [Fr(n + alpha, sum(v) + alpha * 3) for n in v] for c, v in count.items()}
    for msg in ("free buy", "meeting free"):
        sc = {c: prior[c] * math.prod(theta[c][words.index(w)] for w in msg.split()) for c in prior}
        print("5a. alpha=%d '%s': spam score %s, ham score %s, P(spam) = %s" % (alpha, msg, sc["spam"], sc["ham"], sc["spam"] / sum(sc.values())))

def nb_fit(X, y):
    return [[(sum(x[j] for x, t in zip(X, y) if t == c) + 1) / (y.count(c) + 2) for j in range(len(X[0]))] for c in (0, 1)]

def nb_p1(th, x):                         # P(class 1 | x) from the sum of per-feature log likelihood ratios
    lo = sum(math.log((th[1][j] if v else 1 - th[1][j]) / (th[0][j] if v else 1 - th[0][j])) for j, v in enumerate(x))
    return 1 / (1 + math.exp(-lo))

def votes(seed, n):                       # 8 binary features, each equal to the label with probability 0.65, independent given it
    r = random.Random(seed)
    y = [r.randrange(2) for _ in range(n)]
    return [[t if r.random() < 0.65 else 1 - t for _ in range(8)] for t in y], y

print("5b. 8 binary features, each agrees with the label 65% of the time, independent given the label; 50 datasets")
res = {}
for s in range(50):
    (X, y), (Xv, yv) = votes(s, 300), votes(100 + s, 3000)
    for name, f in (("8 distinct features", lambda x: x), ("each copied 3 times", lambda x: x * 3),
                    ("first feature copied 20 times", lambda x: x + x[:1] * 19)):
        th = nb_fit([f(x) for x in X], y)
        p = [nb_p1(th, f(x)) for x in Xv]
        res.setdefault(name, []).append((statistics.fmean((q > 0.5) == t for q, t in zip(p, yv)), statistics.fmean(max(q, 1 - q) for q in p)))
for name, v in res.items():
    print("   %-30s accuracy %.3f, mean stated confidence %.3f" % ((name,) + tuple(med(c) for c in zip(*v))))

Neural networks and backpropagation: gradients, checks and initialisation

Deep learning and transformers

Show the code (233 lines)

Python

import itertools
import math
import random
import statistics
import time

T0 = time.time()


def matvec(W, v):
    return [sum(w * x for w, x in zip(row, v)) for row in W]


def softmax(z):
    m = max(z)
    e = [math.exp(a - m) for a in z]
    s = sum(e)
    return [a / s for a in e]


def rms(v):
    return math.sqrt(sum(a * a for a in v) / len(v))


# ---- a 2-layer network: x -> ReLU(W1 x + b1) -> softmax(W2 a1 + b2) ----
def forward(P, x, mask=None):
    W1, b1, W2, b2 = P
    z1 = [s + b for s, b in zip(matvec(W1, x), b1)]
    a1 = [max(0.0, z) for z in z1]
    if mask:
        a1 = [a * m for a, m in zip(a1, mask)]
    z2 = [s + b for s, b in zip(matvec(W2, a1), b2)]
    return z1, a1, z2, softmax(z2)


def loss_of(P, x, y):
    return -math.log(forward(P, x)[3][y])


def backward(P, x, y, cache, mask=None):
    W1, b1, W2, b2 = P
    z1, a1, z2, p = cache
    dz2 = [pk - (1.0 if k == y else 0.0) for k, pk in enumerate(p)]
    dW2 = [[d * a for a in a1] for d in dz2]
    da1 = [sum(W2[k][j] * dz2[k] for k in range(len(dz2))) for j in range(len(a1))]
    if mask:
        da1 = [d * m for d, m in zip(da1, mask)]
    dz1 = [d if z > 0 else 0.0 for d, z in zip(da1, z1)]
    dW1 = [[d * xi for xi in x] for d in dz1]
    return [dW1, dz1, dW2, dz2], dz2, da1, dz1


def cells(T):
    for t in T:
        if isinstance(t[0], list):
            for row in t:
                for j in range(len(row)):
                    yield row, j
        else:
            for j in range(len(t)):
                yield t, j


def numeric_grad(P, x, y, h=1e-5):
    out = []
    for c, j in cells(P):
        old = c[j]
        c[j] = old + h
        up = loss_of(P, x, y)
        c[j] = old - h
        dn = loss_of(P, x, y)
        c[j] = old
        out.append((up - dn) / (2 * h))
    return out


def rel_err(a, n):
    return abs(a - n) / max(abs(a), abs(n), 1e-8)


print("== 1. Worked example: 2 inputs, 2 ReLU units, 2 classes, label y = class 1 ==")
P = [[[0.5, 0.25], [-1.0, 0.5]], [0.0, -0.5], [[1.0, 0.5], [-1.0, -0.25]], [0.0, 0.0]]
x, y = [1.0, 2.0], 1
cache = forward(P, x)
z1, a1, z2, p = cache
G, dz2, da1, dz1 = backward(P, x, y, cache)
print("z1", z1, "a1", a1, "z2", z2)
print("p", [round(v, 4) for v in p], "loss", round(loss_of(P, x, y), 4))
print("dz2 = p - y", [round(v, 4) for v in dz2])
print("dW2", [[round(v, 4) for v in r] for r in G[2]], "db2", [round(v, 4) for v in G[3]])
print("da1 = W2^T dz2", [round(v, 4) for v in da1], " dz1 = da1 * 1[z1>0]", [round(v, 4) for v in dz1])
print("dW1", [[round(v, 4) for v in r] for r in G[0]], "db1", [round(v, 4) for v in G[1]])
flat = [g for c, j in cells(G) for g in [c[j]]]
num = numeric_grad(P, x, y)
print("gradient check, 12 parameters, central difference h=1e-5: max abs diff %.1e, max relative error %.1e"
      % (max(abs(a - n) for a, n in zip(flat, num)), max(rel_err(a, n) for a, n in zip(flat, num))))
# the same check on three plausible bugs
def check(G_bad):
    f = [g for c, j in cells(G_bad) for g in [c[j]]]
    return max(rel_err(a, n) for a, n in zip(f, num))
no_mask = [[[d * xi for xi in x] for d in da1], da1, G[2], G[3]]
flipped = [[[-v for v in r] for r in G[0]], [-v for v in G[1]], [[-v for v in r] for r in G[2]], [-v for v in G[3]]]
W2 = P[2]
wrong = [W2[0][0] * dz2[0] + W2[0][1] * dz2[1], W2[1][0] * dz2[0] + W2[1][1] * dz2[1]]  # rows, not columns
dz1_t = [d if z > 0 else 0.0 for d, z in zip(wrong, z1)]
wrongT = [[[d * xi for xi in x] for d in dz1_t], dz1_t, G[2], G[3]]
print("bug: ReLU mask forgotten      -> max relative error %.2f" % check(no_mask))
print("bug: sign of p - y flipped    -> max relative error %.2f" % check(flipped))
print("bug: W2 used where W2^T needed -> max relative error %.2f" % check(wrongT))
lr = 0.1
Q = [[r[:] for r in P[0]], P[1][:], [r[:] for r in P[2]], P[3][:]]
for (c, j), (g, k) in zip(cells(Q), cells(G)):
    c[j] -= lr * g[k]
print("after one step lr=0.1: loss %.4f -> %.4f" % (loss_of(P, x, y), loss_of(Q, x, y)))

print("\n== 2. Why a non-linearity ==")
rng = random.Random(0)
A1 = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(4)]
c1 = [rng.gauss(0, 1) for _ in range(4)]
A2 = [[rng.gauss(0, 1) for _ in range(4)] for _ in range(2)]
c2 = [rng.gauss(0, 1) for _ in range(2)]
A = [[sum(A2[i][k] * A1[k][j] for k in range(4)) for j in range(3)] for i in range(2)]
cc = [sum(A2[i][k] * c1[k] for k in range(4)) + c2[i] for i in range(2)]
worst = 0.0
for _ in range(5):
    v = [rng.gauss(0, 1) for _ in range(3)]
    two = [s + b for s, b in zip(matvec(A2, [s + b for s, b in zip(matvec(A1, v), c1)]), c2)]
    one = [s + b for s, b in zip(matvec(A, v), cc)]
    worst = max(worst, max(abs(a - b) for a, b in zip(two, one)))
print("two stacked linear layers vs one layer (A2 A1)x + (A2 c1 + c2): max difference %.1e" % worst)
pts = [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 0)]
best = 0
grid = [i / 4 for i in range(-12, 13)]
for w1, w2, b in itertools.product(grid, repeat=3):
    best = max(best, sum((w1 * a + w2 * c + b > 0) == bool(t) for (a, c), t in pts))
print("XOR: best linear rule found on a 25^3 grid classifies %d of 4" % best)
xor_out = []
for (a, c), t in pts:
    h1, h2 = max(0, a + c), max(0, a + c - 1)
    xor_out.append(h1 - 2 * h2)
print("XOR with hidden relu(a+c), relu(a+c-1), output h1 - 2 h2:", xor_out)

print("parameters of 784 -> 128 -> 10:", 128 * (784 + 1) + 10 * (128 + 1))

print("\n== 3. Derivatives and saturation ==")
sig = lambda z: 1 / (1 + math.exp(-z))
for z in (0, 2, 5, 10):
    print("z=%2d sigmoid' %.2e   tanh' %.2e" % (z, sig(z) * (1 - sig(z)), 1 - math.tanh(z) ** 2))
print("best-case product of 10 sigmoid derivatives: 0.25**10 = %.2e" % 0.25 ** 10)
gelu = lambda z: z * 0.5 * (1 + math.erf(z / math.sqrt(2)))
print("GELU at -3, -1, 0, 1, 3:", [round(gelu(z), 4) for z in (-3, -1, 0, 1, 3)])

print("\n== 4. Signal through 20 layers of width 64 (8 random inputs, rms of the activations) ==")
def deep(act, std_fn, depth=20, width=64, seed=0):
    rng = random.Random(seed)
    Ws = [[[rng.gauss(0, std_fn(width)) for _ in range(width)] for _ in range(width)] for _ in range(depth)]
    fwd, bwd = [], []
    for _ in range(8):
        a = [rng.gauss(0, 1) for _ in range(width)]
        zs = []
        acts = [a]
        for W in Ws:
            z = matvec(W, a)
            a = [act(v) for v in z]
            zs.append(z)
            acts.append(a)
        fwd.append([rms(v) for v in acts])
        g = [1.0] * width  # d(sum of last activations)/d(last activations)
        norms = [rms(g)]
        for l in range(depth - 1, -1, -1):
            dz = [gi * (1 - math.tanh(z) ** 2 if act is math.tanh else (sig(z) * (1 - sig(z)) if act is sig else (1.0 if z > 0 else 0.0))) for gi, z in zip(g, zs[l])]
            g = [sum(Ws[l][i][j] * dz[i] for i in range(width)) for j in range(width)]
            norms.append(rms(g))
        bwd.append(norms[::-1])
    mean = lambda rows, i: statistics.mean(r[i] for r in rows)
    return [mean(fwd, i) for i in (1, 5, 10, 20)], mean(bwd, 0) / mean(bwd, 20), (mean(fwd, 20) / mean(fwd, 1)) ** (1 / 19)
relu = lambda v: max(0.0, v)
rows = [
    ("tanh, std 0.01", math.tanh, lambda n: 0.01),
    ("tanh, Xavier sqrt(1/n)", math.tanh, lambda n: math.sqrt(1 / n)),
    ("tanh, std 1.0", math.tanh, lambda n: 1.0),
    ("sigmoid, Xavier sqrt(1/n)", sig, lambda n: math.sqrt(1 / n)),
    ("ReLU, std 0.01", relu, lambda n: 0.01),
    ("ReLU, Xavier sqrt(1/n)", relu, lambda n: math.sqrt(1 / n)),
    ("ReLU, He sqrt(2/n)", relu, lambda n: math.sqrt(2 / n)),
    ("ReLU, 2x He sqrt(8/n)", relu, lambda n: math.sqrt(8 / n)),
]
print("activation rms at layers 1, 5, 10, 20 | gradient rms at input / at output | activation factor per layer | gradient factor per layer")
for name, act, sd in rows:
    f, b, pl = deep(act, sd)
    print("%-26s %s | %.2e | %.3f | %.3f" % (name, ["%.2e" % v for v in f], b, pl, b ** (1 / 20)))

print("same gradient ratio with weight seeds 0, 1, 2:")
for name, act, sd in rows:
    print("  %-26s %s" % (name, ["%.1e" % deep(act, sd, seed=k)[1] for k in (0, 1, 2)]))


# ---- a small data set: two moons ----
def moons(n, noise, rng):
    X, Y = [], []
    for i in range(n):
        c, t = i % 2, rng.uniform(0, math.pi)
        px, py = (math.cos(t), math.sin(t)) if c == 0 else (1 - math.cos(t), 0.5 - math.sin(t))
        X.append([px + rng.gauss(0, noise), py + rng.gauss(0, noise)])
        Y.append(c)
    return X, Y

def init(rng, H, d=2, k=2, out_scale=1.0):
    return [[[rng.gauss(0, math.sqrt(2 / d)) for _ in range(d)] for _ in range(H)], [0.0] * H,
            [[rng.gauss(0, math.sqrt(2 / H) * out_scale) for _ in range(H)] for _ in range(k)], [0.0] * k]

def evaluate(P, X, Y):
    L, ok = 0.0, 0
    for x, y in zip(X, Y):
        p = forward(P, x)[3]
        L -= math.log(max(p[y], 1e-12))
        ok += p.index(max(p)) == y
    return L / len(X), ok / len(X)

print("\n== 5. Initial loss and overfitting a tiny batch (two-moons data) ==")
rng = random.Random(3)
Xs, Ys = moons(200, 0.35, rng)
for scale in (1.0, 0.01):
    print("initial loss on 200 points, output weights x%s: mean over 8 seeds %.3f" % (scale, statistics.fmean(evaluate(init(random.Random(s), 16, out_scale=scale), Xs, Ys)[0] for s in range(8))))
Xt, Yt = Xs[:4], Ys[:4]
Pt = init(random.Random(0), 16)
for ep in range(300):
    for x, y in zip(Xt, Yt):
        G = backward(Pt, x, y, forward(Pt, x))[0]
        for (c, j), (g, k) in zip(cells(Pt), cells(G)):
            c[j] -= 0.5 * g[k] / 4
print("4 points, 300 epochs, lr 0.5: loss %.4f, accuracy %.2f" % evaluate(Pt, Xt, Yt))
print("total %.1f s" % (time.time() - T0))

Training deep networks: normalisation, regularisation, AdamW and debugging

Deep learning and transformers

Show the code (211 lines)

Python

import math
import random
import statistics
import time

T0 = time.time()


def matvec(W, v):
    return [sum(w * x for w, x in zip(row, v)) for row in W]


def softmax(z):
    m = max(z)
    e = [math.exp(a - m) for a in z]
    s = sum(e)
    return [a / s for a in e]


# ---- a 2-layer network: x -> ReLU(W1 x + b1) -> softmax(W2 a1 + b2) ----
def forward(P, x, mask=None):
    W1, b1, W2, b2 = P
    z1 = [s + b for s, b in zip(matvec(W1, x), b1)]
    a1 = [max(0.0, z) for z in z1]
    if mask:
        a1 = [a * m for a, m in zip(a1, mask)]
    z2 = [s + b for s, b in zip(matvec(W2, a1), b2)]
    return z1, a1, z2, softmax(z2)


def backward(P, x, y, cache, mask=None):
    W1, b1, W2, b2 = P
    z1, a1, z2, p = cache
    dz2 = [pk - (1.0 if k == y else 0.0) for k, pk in enumerate(p)]
    dW2 = [[d * a for a in a1] for d in dz2]
    da1 = [sum(W2[k][j] * dz2[k] for k in range(len(dz2))) for j in range(len(a1))]
    if mask:
        da1 = [d * m for d, m in zip(da1, mask)]
    dz1 = [d if z > 0 else 0.0 for d, z in zip(da1, z1)]
    dW1 = [[d * xi for xi in x] for d in dz1]
    return [dW1, dz1, dW2, dz2], dz2, da1, dz1


def cells(T):
    for t in T:
        if isinstance(t[0], list):
            for row in t:
                for j in range(len(row)):
                    yield row, j
        else:
            for j in range(len(t)):
                yield t, j


print("\n== 1. Clipping ==")
def clip_norm(g, max_norm):
    n = math.sqrt(sum(v * v for v in g))
    s = max_norm / n if n > max_norm else 1.0
    return [v * s for v in g], n
for g in ([3.0, 4.0], [0.3, 0.4]):
    out, n = clip_norm(g, 1.0)
    print("gradient", g, "has norm %.1f; clipped to max norm 1:" % n, [round(v, 3) for v in out])
for clip in (None, 1.0):
    w, path = 3.0, []
    for _ in range(6):
        g = 4 * w ** 3
        if clip:
            g = clip_norm([g], clip)[0][0]
        w -= 0.1 * g
        path.append(w)
    print("f(w)=w^4, lr 0.1, start 3, clip", clip, ["%.3g" % v for v in path])

print("\n== 2. Batch norm vs layer norm ==")
eps = 1e-5
def bn(X):
    cols = list(zip(*X))
    mu = [statistics.fmean(c) for c in cols]
    var = [statistics.pvariance(c) for c in cols]
    return [[(v - m) / math.sqrt(s + eps) for v, m, s in zip(r, mu, var)] for r in X]
def ln(X):
    out = []
    for r in X:
        m, s = statistics.fmean(r), statistics.pvariance(r)
        out.append([(v - m) / math.sqrt(s + eps) for v in r])
    return out
X = [[1.0, 2.0, 3.0], [2.0, 0.0, 4.0], [0.0, 1.0, 5.0], [3.0, 3.0, 3.5]]
X2 = [r[:] for r in X]
X2[3] = [30.0, -9.0, 8.0]
print("row 0 unchanged input; other row replaced")
print("  batch norm row 0:", [round(v, 3) for v in bn(X)[0]], "->", [round(v, 3) for v in bn(X2)[0]])
print("  layer norm row 0:", [round(v, 3) for v in ln(X)[0]], "->", [round(v, 3) for v in ln(X2)[0]])
print("  batch norm with batch of 1:", bn([[5.0, 6.0, 7.0]]))
rng = random.Random(1)
for B in (2, 8, 32, 128):
    means = [statistics.fmean(rng.gauss(0, 1) for _ in range(B)) for _ in range(4000)]
    print("  batch size %3d: spread (sd) of the batch mean of N(0,1) data %.3f (1/sqrt(B) = %.3f)" % (B, statistics.pstdev(means), 1 / math.sqrt(B)))

print("\n== 3. Dropout arithmetic ==")
rng = random.Random(2)
for p in (0.2, 0.5):
    s = [(0.0 if rng.random() < p else 1 / (1 - p)) * 3.0 for _ in range(200000)]
    print("p=%.1f: a=3.0 -> mean of dropped activation %.3f, sd %.3f" % (p, statistics.fmean(s), statistics.pstdev(s)))

print("\n== 4. Adam with L2 versus AdamW (w held at 1, decay 0.01, lr 0.001, loss gradient alternating +G, -G) ==")
def mean_update(G, wd, decoupled, steps=4000, lr=0.001, b1=0.9, b2=0.999, e=1e-8):
    m = v = 0.0
    ups = []
    for t in range(1, steps + 1):
        g = G if t % 2 else -G
        if not decoupled:
            g += wd * 1.0
        m, v = b1 * m + (1 - b1) * g, b2 * v + (1 - b2) * g * g
        u = lr * (m / (1 - b1 ** t)) / (math.sqrt(v / (1 - b2 ** t)) + e)
        ups.append(u + (lr * wd * 1.0 if decoupled else 0.0))
    return statistics.fmean(ups[steps // 2:])


print("extra shrinkage of w per step caused by the decay term (mean over the last 2000 steps):")
for G in (0.0, 0.001, 0.01, 0.1, 1.0, 100.0):
    print("  loss gradient scale %-6s Adam+L2 %.2e   AdamW %.2e" % (G, mean_update(G, 0.01, False) - mean_update(G, 0.0, False), mean_update(G, 0.01, True) - mean_update(G, 0.0, True)))


def lr_at(t, total=1000, warm=100, peak=1e-3, floor=0.0):
    if t < warm:
        return peak * (t + 1) / warm
    c = (t - warm) / (total - warm)
    return floor + 0.5 * (peak - floor) * (1 + math.cos(math.pi * c))
print("warmup 100 + cosine to 0 over 1000 steps, peak 1e-3:", [(t, "%.3g" % lr_at(t)) for t in (0, 49, 99, 100, 325, 550, 775, 999)])

print("\n== 5. NaN sources ==")
try:
    math.exp(1000)
except OverflowError as ex:
    print("exp(1000) in Python raises:", ex)
print("array libraries return inf instead, and inf/inf =", float("inf") / float("inf"), "; 0*inf =", 0.0 * float("inf"))
z = [1000.0, 0.0]
lse = max(z) + math.log(sum(math.exp(v - max(z)) for v in z))
print("softmax of [1000, 0] with the max subtracted:", softmax(z), "; loss for class 1 = logsumexp - z[1] =", lse - z[1])
print("naive softmax then log of an underflowed probability: log(exp(-1000)) ->", end=" ")
try:
    print(math.log(math.exp(-1000.0)))
except ValueError as ex:
    print("ValueError:", ex)
print("ln(2) = %.4f, ln(10) = %.4f" % (math.log(2), math.log(10)))

# ---- section 6: a small network trained on two moons ----
def moons(n, noise, rng):
    X, Y = [], []
    for i in range(n):
        c, t = i % 2, rng.uniform(0, math.pi)
        px, py = (math.cos(t), math.sin(t)) if c == 0 else (1 - math.cos(t), 0.5 - math.sin(t))
        X.append([px + rng.gauss(0, noise), py + rng.gauss(0, noise)])
        Y.append(c)
    return X, Y

def init(rng, H, d=2, k=2, out_scale=1.0):
    return [[[rng.gauss(0, math.sqrt(2 / d)) for _ in range(d)] for _ in range(H)], [0.0] * H,
            [[rng.gauss(0, math.sqrt(2 / H) * out_scale) for _ in range(H)] for _ in range(k)], [0.0] * k]

def evaluate(P, X, Y):
    L, ok = 0.0, 0
    for x, y in zip(X, Y):
        p = forward(P, x)[3]
        L -= math.log(max(p[y], 1e-12))
        ok += p.index(max(p)) == y
    return L / len(X), ok / len(X)

def fit(seed, wd=0.0, drop=0.0, epochs=300, lr=0.5, H=16, ntrain=30):
    rng = random.Random(seed)
    Xtr, Ytr = moons(ntrain, 0.35, rng)
    Xva, Yva = moons(200, 0.35, rng)
    Xte, Yte = moons(1000, 0.35, rng)
    P = init(rng, H)
    best = (1e9, None, 0)
    for ep in range(epochs):
        acc = None
        for x, y in zip(Xtr, Ytr):
            mask = [0.0 if rng.random() < drop else 1 / (1 - drop) for _ in range(H)] if drop else None
            G = backward(P, x, y, forward(P, x, mask), mask)[0]
            acc = G if acc is None else [[[a + b for a, b in zip(r1, r2)] for r1, r2 in zip(t1, t2)] if isinstance(t1[0], list) else [a + b for a, b in zip(t1, t2)] for t1, t2 in zip(acc, G)]
        n = len(Xtr)
        for (c, j), (g, k) in zip(cells(P), cells(acc)):
            c[j] -= lr * g[k] / n
        for t in (P[0], P[2]):  # weight decay on weights, not biases
            for row in t:
                for j in range(len(row)):
                    row[j] -= lr * wd * row[j]
        vl = evaluate(P, Xva, Yva)[0]
        if vl < best[0]:
            best = (vl, [[r[:] for r in P[0]], P[1][:], [r[:] for r in P[2]], P[3][:]], ep + 1)
    return evaluate(P, Xtr, Ytr), evaluate(P, Xte, Yte), evaluate(best[1], Xte, Yte), best[2]

print("\n== 6. Two moons, 30 training points, 16 hidden units, full-batch GD lr 0.5, 300 epochs, 8 seeds ==")
t0 = time.time()
res = {}
for name, kw in (("no regularisation", {}), ("weight decay 0.01", {"wd": 0.01}), ("dropout 0.3", {"drop": 0.3})):
    res[name] = [fit(s, **kw) for s in range(8)]
print("%-22s %10s %10s %10s %10s" % ("setting", "train loss", "test loss", "test acc", "test@best-val"))
for name, rs in res.items():
    print("%-22s %10.3f %10.3f %10.3f %10.3f" % (name, statistics.fmean(r[0][0] for r in rs), statistics.fmean(r[1][0] for r in rs), statistics.fmean(r[1][1] for r in rs), statistics.fmean(r[2][0] for r in rs)))
base = res["no regularisation"]
print("early stopping (best validation epoch) vs last epoch, test loss, per seed:")
print("  best epoch", [r[3] for r in base])
print("  last", [round(r[1][0], 3) for r in base])
print("  best", [round(r[2][0], 3) for r in base])
for name in ("weight decay 0.01", "dropout 0.3"):
    print("%s beats no regularisation (test loss) on %d of 8 seeds" % (name, sum(a[1][0] < b[1][0] for a, b in zip(res[name], base))))
print("early stopping beats last epoch on %d of 8 seeds" % sum(r[2][0] < r[1][0] for r in base))
print("section 6 took %.1f s" % (time.time() - t0))

print("total %.1f s" % (time.time() - T0))

CNNs, ResNets, transfer learning and recurrent networks, with RMSNorm and label smoothing

Deep learning and transformers

Show the code (199 lines)

Python

import math
import random
import statistics
import time

T0 = time.time()


def conv_out(n, k, s=1, p=0):
    """Output length along one axis, p padding on EACH side."""
    return (n + 2 * p - k) // s + 1


def conv_params(k_h, k_w, c_in, c_out, bias=True):
    return k_h * k_w * c_in * c_out + (c_out if bias else 0)


print("== 1. Shapes and parameter counts ==")
print("7x7 input, 3x3 kernel, stride 1, pad 0 ->", conv_out(7, 3), "; stride 2 ->", conv_out(7, 3, 2))
print("8x8, 3x3, pad 1, stride 1 ->", conv_out(8, 3, 1, 1), "; stride 2 ->", conv_out(8, 3, 2, 1))
print("10, kernel 3, stride 2, pad 1 ->", conv_out(10, 3, 2, 1), "(9/2 rounds down to 4, plus 1)")
print("227, kernel 11, stride 4, pad 0 ->", conv_out(227, 11, 4, 0))
print("image 8 high x 6 wide, kernel 3 high x 5 wide, pad (1, 2), stride 1 ->", conv_out(8, 3, 1, 1), "high x", conv_out(6, 5, 1, 2), "wide")
print("3x3 conv, 3 -> 64 channels: %d parameters" % conv_params(3, 3, 3, 64))
print("5x5 conv, 16 -> 32 channels: %d parameters" % conv_params(5, 5, 16, 32))
print("1x1 conv, 256 -> 64 channels: %d parameters" % conv_params(1, 1, 256, 64))
n_in, n_out = 32 * 32 * 3, 32 * 32 * 64
print("a dense layer from a 32x32x3 image to a 32x32x64 map: %d weights + %d biases" % (n_in * n_out, n_out))
print("the 3x3 conv giving the same output shape (pad 1): %d parameters, about %.0f times fewer" % (conv_params(3, 3, 3, 64), (n_in * n_out + n_out) / conv_params(3, 3, 3, 64)))
print("transfer learning head: 512 features to 2 classes = %d parameters" % (512 * 2 + 2))
print("pooling parameters: 0; 2x2 stride 2 pooling on 8x8 ->", conv_out(8, 2, 2), "x", conv_out(8, 2, 2), ", channels unchanged")


def conv2d(img, ker):
    kh, kw = len(ker), len(ker[0])
    H, W = len(img), len(img[0])
    return [[sum(ker[a][b] * img[i + a][j + b] for a in range(kh) for b in range(kw)) for j in range(W - kw + 1)] for i in range(H - kh + 1)]


def maxpool1d(v, k=2, s=2):
    return [max(v[i:i + k]) for i in range(0, len(v) - k + 1, s)]


print("\n== 2. Equivariance and pooling ==")
ker = [[1.0, 0.0, -1.0], [2.0, 0.0, -2.0], [1.0, 0.0, -1.0]]
img = [[0.0] * 8 for _ in range(8)]
for r, c in ((2, 2), (2, 3), (3, 2), (3, 3), (4, 3)):
    img[r][c] = 1.0
shifted = [[0.0] * 8 for _ in range(8)]
for r in range(7):
    for c in range(8):
        shifted[r + 1][c] = img[r][c]
a, b = conv2d(img, ker), conv2d(shifted, ker)
same = all(abs(a[i][j] - b[i + 1][j]) < 1e-12 for i in range(5) for j in range(6))
print("shifting the input down 1 row shifts the 6x6 output down 1 row:", same)
print("sample output row:", a[2], "-> shifted:", b[3])
for pos in range(1, 6):
    v = [0.0] * 8
    v[pos] = 1.0
    print("  pixel at %d -> max-pool(2, stride 2) %s" % (pos, maxpool1d(v)))
print("pooling: the pixel moved from 2 to 3 changes nothing, 3 to 4 changes the output; invariance only holds for shifts inside a window")

print("\n== 3. Receptive field ==")
def receptive_field(layers):
    r, j = 1, 1
    for k, s in layers:
        r += (k - 1) * j
        j *= s
    return r
for name, L in (("3 x (3x3, stride 1)", [(3, 1)] * 3), ("one 7x7", [(7, 1)]), ("3 x (3x3, stride 2)", [(3, 2)] * 3),
                ("3x3 conv, then 2x2 pool stride 2", [(3, 1), (2, 2)]), ("2x2 pool stride 2, then 3x3 conv", [(2, 2), (3, 1)])):
    print("  %-34s receptive field %d" % (name, receptive_field(L)))
C = 64
print("weights, C = 64 channels in and out: one 7x7 = %d, three 3x3 = %d" % (49 * C * C, 27 * C * C))


def matvec(W, v):
    return [sum(w * x for w, x in zip(r, v)) for r in W]


def norm(v):
    return math.sqrt(sum(a * a for a in v))


print("\n== 4. Gradient through a deep stack, plain versus residual ==")
print("scalar: y = x + F(x) has dy/dx = 1 + F'(x); with F'(x) = -0.5 that is 0.5, with F' = 0 it is 1")
def grad_ratio(depth, residual, seed, n=16):
    rng = random.Random(seed)
    Ws = [[[rng.gauss(0, 1 / math.sqrt(n)) for _ in range(n)] for _ in range(n)] for _ in range(depth)]
    x = [rng.gauss(0, 1) for _ in range(n)]
    h, acts = x, []
    for W in Ws:
        z = matvec(W, h)
        t = [math.tanh(v) for v in z]
        acts.append((h, t))
        h = [a + b for a, b in zip(h, t)] if residual else t
    g = [1.0 / math.sqrt(n)] * n
    for W, (hin, t) in zip(reversed(Ws), reversed(acts)):
        dz = [gi * (1 - ti * ti) for gi, ti in zip(g, t)]
        WT = [list(col) for col in zip(*W)]
        branch = matvec(WT, dz)
        g = [a + b for a, b in zip(g, branch)] if residual else branch
    return norm(g)
for depth in (10, 50):
    for res in (False, True):
        r = [grad_ratio(depth, res, s) for s in range(20)]
        print("  depth %2d %-8s mean gradient norm at the input, for unit norm at the output, over 20 seeds: %.3g" % (depth, "residual" if res else "plain", statistics.fmean(r)))

print("\n== 5. Recurrent gradients ==")
def rnn_grad(w, T, x=0.1):
    h, d = 0.0, 1.0
    for _ in range(T):
        h = math.tanh(w * h + x)
        d *= w * (1 - h * h)
    return d
for w in (0.9, 1.5, 3.0):
    print("  scalar tanh RNN, w = %.1f, input 0.1: |dh_T/dh_0| at T = 10, 50, 100: %s" % (w, ["%.3g" % abs(rnn_grad(w, T)) for T in (10, 50, 100)]))
for w in (1.5, 3.0):
    h = 0.0
    for _ in range(500):
        h = math.tanh(w * h + 0.1)
    print("  w = %.1f, constant input 0.1: the state settles at h = %.3f, where 1 - h^2 = %.3f and w(1 - h^2) = %.3f" % (w, h, 1 - h * h, w * (1 - h * h)))
for w in (0.9, 1.5):
    print("  with zero input the state stays at 0 and tanh' = 1, so the derivative is w^T: w = %.1f, T = 10, 50, 100: %s" % (w, ["%.3g" % w ** T for T in (10, 50, 100)]))
for f in (0.99, 0.9, 0.5):
    print("  product of %.2f forget gates over T = 10, 50, 100: %s" % (f, ["%.3g" % f ** T for T in (10, 50, 100)]))

def sig(z):
    return 1 / (1 + math.exp(-z))
def lstm_scalar(P, xs, c0, h0=0.0):
    c, h = c0, h0
    fs = []
    for x in xs:
        i = sig(P["xi"] * x + P["hi"] * h + P["bi"])
        f = sig(P["xf"] * x + P["hf"] * h + P["bf"])
        o = sig(P["xo"] * x + P["ho"] * h + P["bo"])
        g = math.tanh(P["xg"] * x + P["hg"] * h + P["bg"])
        c = f * c + i * g
        h = o * math.tanh(c)
        fs.append(f)
    return c, fs
rng = random.Random(4)
T = 30
xs = [rng.gauss(0, 1) for _ in range(T)]
for scale, bf in ((0.1, 3.0), (1.0, 3.0), (1.0, 0.0)):
    P = {k: rng.gauss(0, 1) * scale for k in ("xi", "hi", "xf", "hf", "xo", "ho", "xg", "hg")}
    P.update(bi=0.0, bo=0.0, bg=0.0, bf=bf)
    c0 = 0.5
    cT, fs = lstm_scalar(P, xs, c0)
    eps = 1e-6
    fd = (lstm_scalar(P, xs, c0 + eps)[0] - lstm_scalar(P, xs, c0 - eps)[0]) / (2 * eps)
    prod = 1.0
    for f in fs:
        prod *= f
    print("  scalar LSTM T=30, weight scale %.1f, forget bias %.0f: dc_T/dc_0 (finite difference) %.4g; product of forget gates %.4g" % (scale, bf, fd, prod))

print("\n== 6. Parameter counts, input d = 10, hidden h = 20 ==")
d, h = 10, 20
print("  vanilla RNN, one bias: %d; two biases (nn.RNN keeps bias_ih and bias_hh too): %d" % (h * (d + h + 1), h * (d + h + 2)))
print("  LSTM, one bias per gate (textbook): %d; two biases (PyTorch): %d" % (4 * (d * h + h * h + h), 4 * h * (d + h + 2)))
print("  GRU, two biases (PyTorch): %d; textbook (one bias): %d" % (3 * h * (d + h + 2), 3 * (d * h + h * h + h)))

print("\n== 7. LayerNorm versus RMSNorm ==")
def layer_norm(x, eps=1e-5):
    m = statistics.fmean(x)
    v = statistics.pvariance(x)
    return [(a - m) / math.sqrt(v + eps) for a in x]
def rms_norm(x, eps=1e-5):
    r = math.sqrt(eps + statistics.fmean(a * a for a in x))
    return [a / r for a in x]
x = [1.0, 2.0, 3.0, 6.0]
print("  x =", x)
print("  layer norm:", [round(v, 3) for v in layer_norm(x)], "mean %.3f" % statistics.fmean(layer_norm(x)))
print("  RMS norm  :", [round(v, 3) for v in rms_norm(x)], "mean %.3f" % statistics.fmean(rms_norm(x)))
xs10 = [10 * a for a in x]
print("  both unchanged by x -> 10x:", max(abs(a - b) for a, b in zip(layer_norm(x), layer_norm(xs10))) < 1e-4, max(abs(a - b) for a, b in zip(rms_norm(x), rms_norm(xs10))) < 1e-4)
xp = [a + 5 for a in x]
print("  after adding 5 to every entry: layer norm output unchanged:", max(abs(a - b) for a, b in zip(layer_norm(x), layer_norm(xp))) < 1e-9, "; RMS norm output becomes", [round(v, 3) for v in rms_norm(xp)])

print("\n== 8. Label smoothing ==")
K, eps_ls = 10, 0.1
q = [1 - eps_ls + eps_ls / K] + [eps_ls / K] * (K - 1)
print("  K = 10, epsilon = 0.1 -> target:", [round(v, 3) for v in q[:3]], "... sum", round(sum(q), 6))
H = -sum(v * math.log(v) for v in q)
print("  smallest achievable smoothed cross-entropy (entropy of the target): %.4f; hard-label floor: 0" % H)
print("  logit gap at that optimum: ln(0.91/0.01) = %.3f" % math.log(q[0] / q[1]))
for gap in (2.0, 4.511, 8.0, 12.0):
    pz = [math.exp(gap)] + [1.0] * (K - 1)
    s = sum(pz)
    p = [v / s for v in pz]
    hard = -math.log(p[0])
    smooth = -sum(qi * math.log(pi) for qi, pi in zip(q, p))
    print("  logit gap %5.2f: p_true %.4f  hard loss %.4f  smoothed loss %.4f  gradient on true logit hard %.4f smoothed %.4f" % (gap, p[0], hard, smooth, p[0] - 1, p[0] - q[0]))

print("\n== 9. Augmentation arithmetic ==")
print("  32x32 image padded by 4 each side: %d distinct 32x32 crops; with a left-right flip %d" % ((2 * 4 + 1) ** 2, 2 * (2 * 4 + 1) ** 2))
print("  a 3x3 patch flipped left-right:", [r[::-1] for r in [[1, 2, 3], [4, 5, 6], [7, 8, 9]]])

print("\ntotal %.1f s" % (time.time() - T0))

Transformers, large language models, sampling and fine-tuning

Deep learning and transformers

Show the code (263 lines)

Python

import math
import random
import time

T0 = time.time()


def matmul(A, B):
    return [[sum(a * b for a, b in zip(row, col)) for col in zip(*B)] for row in A]


def transpose(A):
    return [list(r) for r in zip(*A)]


def softmax(xs):
    m = max(xs)
    es = [math.exp(x - m) for x in xs]
    s = sum(es)
    return [e / s for e in es]


def attention(Q, K, V, causal=False, offset=0, scale=True):
    d_k = len(Q[0])
    S = matmul(Q, transpose(K))
    if scale:
        S = [[s / math.sqrt(d_k) for s in row] for row in S]
    if causal:
        S = [[s if j <= i + offset else -math.inf for j, s in enumerate(row)] for i, row in enumerate(S)]
    W = [softmax(row) for row in S]
    return matmul(W, V), W


def rand_matrix(rng, r, c, scale=1.0):
    return [[rng.gauss(0, scale) for _ in range(c)] for _ in range(r)]


print("== 1. Subword tokenisation: byte pair encoding on a toy corpus ==")
words = {("l", "o", "w"): 5, ("l", "o", "w", "e", "r"): 2, ("n", "e", "w", "e", "s", "t"): 6, ("w", "i", "d", "e", "s", "t"): 3}
merges = []
for step in range(6):
    pairs = {}
    for w, f in words.items():
        for a, b in zip(w, w[1:]):
            pairs[(a, b)] = pairs.get((a, b), 0) + f
    best = max(pairs, key=lambda p: (pairs[p], p))
    merges.append((best, pairs[best]))
    new = {}
    for w, f in words.items():
        out, i = [], 0
        while i < len(w):
            if i + 1 < len(w) and (w[i], w[i + 1]) == best:
                out.append(w[i] + w[i + 1]); i += 2
            else:
                out.append(w[i]); i += 1
        new[tuple(out)] = f
    words = new
for (pair, count) in merges:
    print("merge", pair, "count", count)
print("segmentation after 6 merges:", {"".join(w): list(w) for w in words})

print("\n== 2. Embedding lookup equals one-hot times matrix ==")
rng = random.Random(0)
V, D = 6, 4
E = rand_matrix(rng, V, D)
tok = 3
onehot = [[1.0 if j == tok else 0.0 for j in range(V)]]
print("lookup equals one-hot product:", matmul(onehot, E)[0] == E[tok])
print("embedding table parameters, vocab 50,000 and d_model 768: %d" % (50000 * 768))

print("\n== 3. Why divide by sqrt(d_k) ==")
for d_k in (4, 16, 64, 256, 1024):
    r = random.Random(d_k)
    dots = []
    for _ in range(2000):
        q = [r.gauss(0, 1) for _ in range(d_k)]
        k = [r.gauss(0, 1) for _ in range(d_k)]
        dots.append(sum(a * b for a, b in zip(q, k)))
    mean = sum(dots) / len(dots)
    var = sum((x - mean) ** 2 for x in dots) / len(dots)
    print("d_k %4d: variance of q.k = %7.1f (theory %4d); after dividing by sqrt(d_k): %.2f" % (d_k, var, d_k, var / d_k))
r = random.Random(1)
d_k, n = 256, 8
q = [r.gauss(0, 1) for _ in range(d_k)]
keys = [[r.gauss(0, 1) for _ in range(d_k)] for _ in range(n)]
raw = [sum(a * b for a, b in zip(q, k)) for k in keys]
for name, logits in (("unscaled", raw), ("scaled", [x / math.sqrt(d_k) for x in raw])):
    p = softmax(logits)
    jac_norm = math.sqrt(sum((p[i] * ((i == j) - p[j])) ** 2 for i in range(n) for j in range(n)))
    print("d_k 256, 8 keys, %s: largest weight %.4f, softmax Jacobian norm %.5f" % (name, max(p), jac_norm))

print("\n== 4. Attention: shapes, causal mask, rows sum to one ==")
n, d_model, h = 10, 256, 4
d_k = d_model // h
print("n=%d, d_model=%d, h=%d: per head Q,K,V are %dx%d, scores %dx%d, head output %dx%d, concatenated %dx%d" % (n, d_model, h, n, d_k, n, n, n, d_k, n, d_model))
print("attention parameters W_Q,W_K,W_V,W_O (no bias): %d = 4 * %d^2" % (4 * d_model * d_model, d_model))
print("score matrix entries per head at n=1,000: %d; at n=2,000: %d (%dx)" % (1000 ** 2, 2000 ** 2, (2000 ** 2) // (1000 ** 2)))
rng = random.Random(2)
Q, K, V = rand_matrix(rng, 4, 3), rand_matrix(rng, 4, 3), rand_matrix(rng, 4, 2)
out, W = attention(Q, K, V, causal=True)
print("causal weights, row 0:", [round(x, 3) for x in W[0]], "; row 2:", [round(x, 3) for x in W[2]])
print("row sums:", [round(sum(r_), 6) for r_ in W])
V2 = [row[:] for row in V]
V2[3] = [100.0, -100.0]
K2 = [row[:] for row in K]
K2[3] = [9.0, 9.0, 9.0]
out2, _ = attention(Q, K2, V2, causal=True)
print("changing token 3 leaves output rows 0-2 unchanged:", out[:3] == out2[:3], "; row 3 changes:", out[3] != out2[3])

print("\n== 5. Positions: attention does not see order ==")
rng = random.Random(3)
X = rand_matrix(rng, 4, 4)
Wq, Wk, Wv = (rand_matrix(rng, 4, 4, 0.5) for _ in range(3))


def self_attn(X):
    return attention(matmul(X, Wq), matmul(X, Wk), matmul(X, Wv))[0]


perm = [2, 0, 3, 1]
Xp = [X[i] for i in perm]
o, op = self_attn(X), self_attn(Xp)
print("permuting the inputs permutes the outputs the same way:", all(max(abs(a - b) for a, b in zip(op[k], o[perm[k]])) < 1e-12 for k in range(4)))


def sinusoid(n, d):
    return [[math.sin(p / 10000 ** (j / d)) if j % 2 == 0 else math.cos(p / 10000 ** ((j - 1) / d)) for j in range(d)] for p in range(n)]


P = sinusoid(4, 4)
print("sinusoidal positions, d=4, pos 0..2:", [[round(x, 4) for x in row] for row in P[:3]])
Xpos = [[a + b for a, b in zip(x, p)] for x, p in zip(X, P)]
Xpos_p = [[a + b for a, b in zip(x, p)] for x, p in zip(Xp, P)]
o, op = self_attn(Xpos), self_attn(Xpos_p)
print("with positions added, a reorder of the tokens is no longer a pure reorder of the outputs:", not all(max(abs(a - b) for a, b in zip(op[k], o[perm[k]])) < 1e-9 for k in range(4)))

print("\n== 6. The block: parameters and activations ==")
d = 512
print("d=512, d_ff=2048: attention %d + MLP %d = %d per layer (12 d^2 = %d)" % (4 * d * d, 2 * d * 2048, 4 * d * d + 2 * d * 2048, 12 * d * d))
for d, L in ((1024, 24), (4096, 32)):
    print("d=%d, L=%d: 12 L d^2 = %d (%.2f billion)" % (d, L, 12 * L * d * d, 12 * L * d * d / 1e9))
print("share of a layer's weights in the MLP: %.4f" % (8 / 12))


def gelu(x):
    return 0.5 * x * (1 + math.erf(x / math.sqrt(2)))


def silu(x):
    return x / (1 + math.exp(-x))


print("x      relu    gelu    silu")
for x in (-3.0, -1.0, -0.5, 0.0, 0.5, 1.0, 3.0):
    print("%5.1f %7.4f %7.4f %7.4f" % (x, max(0.0, x), gelu(x), silu(x)))


def rms(x, eps=1e-6):
    s = math.sqrt(eps + sum(v * v for v in x) / len(x))
    return [v / s for v in x]


print("RMS of a pre-norm residual input [3, -4, 12, 0]:", round(math.sqrt(sum(v * v for v in [3, -4, 12, 0]) / 4), 4), "-> after RMSNorm", [round(v, 4) for v in rms([3, -4, 12, 0])])

print("\n== 7. Next-token training and perplexity ==")
Vsz = 50
print("uniform guess over %d tokens: loss ln(%d) = %.4f nats, perplexity %.1f" % (Vsz, Vsz, math.log(Vsz), math.exp(math.log(Vsz))))
text = "abacabadabac"
counts = {}
for a, b in zip(text, text[1:]):
    counts[(a, b)] = counts.get((a, b), 0) + 1
totals = {}
for (a, b), c in counts.items():
    totals[a] = totals.get(a, 0) + c
nll = -sum(math.log(counts[(a, b)] / totals[a]) for a, b in zip(text, text[1:])) / (len(text) - 1)
print("a 12-character text gives %d next-token targets from one pass; bigram counts give loss %.4f" % (len(text) - 1, nll))
logits_wrong = [0.0, 0.0, 5.0]
p = softmax(logits_wrong)
print("true token index 0 with logits [0,0,5]: p=%.4f, loss %.4f" % (p[0], -math.log(p[0])))
print("uniform guess over those 3 tokens: ln 3 = %.4f" % math.log(3))

print("\n== 8. KV cache ==")
rng = random.Random(4)
d = 6
Wq, Wk, Wv = (rand_matrix(rng, d, d, 0.4) for _ in range(3))
xs = rand_matrix(rng, 12, d)
full_out, _ = attention(matmul(xs, Wq), matmul(xs, Wk), matmul(xs, Wv), causal=True)
Kc, Vc, cached_out, kv_proj = [], [], [], 0
for x in xs:
    Kc += matmul([x], Wk)
    Vc += matmul([x], Wv)
    kv_proj += 1
    o, _ = attention(matmul([x], Wq), Kc, Vc)
    cached_out.append(o[0])
print("cached decoding equals full recomputation:", all(max(abs(a - b) for a, b in zip(cached_out[i], full_out[i])) < 1e-12 for i in range(12)))
n = 100
print("key/value projections for n=%d tokens: without a cache %d, with a cache %d" % (n, n * (n + 1) // 2, n))
L, kv_heads, head_dim, seq, nbytes = 32, 32, 128, 4096, 2
b = 2 * L * kv_heads * head_dim * seq * nbytes
print("KV cache: 2 * %d layers * %d heads * %d dims * %d tokens * %d bytes = %d bytes = %.1f GiB per sequence" % (L, kv_heads, head_dim, seq, nbytes, b, b / 2 ** 30))
print("with 8 shared KV heads instead of 32: %.1f GiB" % (b / 4 / 2 ** 30))

print("\n== 9. Sampling ==")
logits = [2.0, 1.0, 0.5, 0.0, -1.0]
for T in (0.5, 1.0, 2.0):
    p = softmax([x / T for x in logits])
    ent = -sum(x * math.log(x) for x in p)
    print("T=%.1f probs %s entropy %.3f" % (T, [round(x, 4) for x in p], ent))
p = softmax(logits)


def top_k(p, k):
    keep = sorted(range(len(p)), key=lambda i: (-p[i], i))[:k]
    z = sum(p[i] for i in keep)
    return [p[i] / z if i in keep else 0.0 for i in range(len(p))]


def top_p(p, thr):
    order = sorted(range(len(p)), key=lambda i: (-p[i], i))
    keep, c = [], 0.0
    for i in order:
        keep.append(i); c += p[i]
        if c >= thr - 1e-12:
            break
    z = sum(p[i] for i in keep)
    return [p[i] / z if i in keep else 0.0 for i in range(len(p))]


print("T=1 probs", [round(x, 4) for x in p])
print("top-k k=2:", [round(x, 4) for x in top_k(p, 2)])
print("top-p p=0.9:", [round(x, 4) for x in top_p(p, 0.9)])
print("top-p p=0.6:", [round(x, 4) for x in top_p(p, 0.6)])
rng = random.Random(5)
draws = [rng.choices(range(5), weights=top_p(p, 0.9))[0] for _ in range(10000)]
print("10,000 draws from the top-p 0.9 set, frequencies:", [round(draws.count(i) / 10000, 3) for i in range(5)])

print("\n== 10. LoRA ==")
d = 4096
r_, alpha = 8, 16
print("full matrix %d x %d: %d weights; rank-%d LoRA adds %d (%.4f%%)" % (d, d, d * d, r_, 2 * d * r_, 100 * 2 * d * r_ / (d * d)))
print("four attention matrices in each of 32 layers: %d trainable against %d in those matrices" % (4 * 32 * 2 * d * r_, 4 * 32 * d * d))
rng = random.Random(6)
d_out, d_in, r_ = 5, 7, 2
W0 = rand_matrix(rng, d_out, d_in)
A = rand_matrix(rng, r_, d_in, 0.3)
Bm = [[0.0] * r_ for _ in range(d_out)]
x = rand_matrix(rng, d_in, 1)
y0 = matmul(W0, x)
y_start = [[y0[i][0] + (alpha / r_) * matmul(Bm, matmul(A, x))[i][0]] for i in range(d_out)]
print("with B = 0 the adapted layer equals the frozen one:", y_start == y0)
Bm = rand_matrix(rng, d_out, r_, 0.3)
scale = alpha / r_
merged = [[W0[i][j] + scale * sum(Bm[i][k] * A[k][j] for k in range(r_)) for j in range(d_in)] for i in range(d_out)]
yb = matmul(Bm, matmul(A, x))
y_adapter = [[y0[i][0] + scale * yb[i][0]] for i in range(d_out)]
print("merged weights give the same output as base plus adapter:", max(abs(a[0] - b_[0]) for a, b_ in zip(matmul(merged, x), y_adapter)) < 1e-12)
print("shapes: W %dx%d, A %dx%d, B %dx%d" % (d_out, d_in, r_, d_in, d_out, r_))

print("\n== 11. Preference loss ==")
for diff in (-1.0, 0.0, 1.0, 3.0):
    print("reward margin %.1f: loss -log sigmoid = %.4f" % (diff, math.log(1 + math.exp(-diff))))

print("\ntotal %.1f s" % (time.time() - T0))

Evaluation, leakage and imbalance: validation design, metrics, thresholds and rare classes

Evaluation, statistics and data

Show the code (385 lines)

Python

import math
import random
import time

def stratified_kfold(labels, k):
    n = len(labels)
    if k < 2 or k > n:
        raise ValueError("need 2 <= k <= number of rows")
    fold_of = [0] * n
    counter = 0
    for cls in sorted(set(labels)):
        for i in range(n):
            if labels[i] == cls:
                fold_of[i] = counter % k
                counter += 1
    return [([i for i in range(n) if fold_of[i] != f], [i for i in range(n) if fold_of[i] == f]) for f in range(k)]


def group_kfold(groups, k):
    first_seen = []
    members = {}
    for i, g in enumerate(groups):
        if g not in members:
            members[g] = []
            first_seen.append(g)
        members[g].append(i)
    if k < 2 or k > len(first_seen):
        raise ValueError("need 2 <= k <= number of groups")
    order = sorted(first_seen, key=lambda g: -len(members[g]))
    sizes = [0] * k
    test = [[] for _ in range(k)]
    for g in order:
        f = sizes.index(min(sizes))
        test[f].extend(members[g])
        sizes[f] += len(members[g])
    n = len(groups)
    out = []
    for f in range(k):
        t = sorted(test[f])
        ts = set(t)
        out.append(([i for i in range(n) if i not in ts], t))
    return out


def time_series_split(n, n_splits, test_size=None, gap=0):
    if n_splits < 2:
        raise ValueError("n_splits must be at least 2")
    if test_size is None:
        test_size = n // (n_splits + 1)
    out = []
    for i in range(n_splits):
        end = n - (n_splits - 1 - i) * test_size
        start = end - test_size
        if test_size < 1 or start - gap < 1:
            raise ValueError("not enough rows for these settings")
        out.append((list(range(0, start - gap)), list(range(start, end))))
    return out


def roc_auc(y_true, scores):
    pos = [s for y, s in zip(y_true, scores) if y == 1]
    neg = [s for y, s in zip(y_true, scores) if y == 0]
    if not pos or not neg:
        raise ValueError("both classes are needed")
    order = sorted(range(len(scores)), key=lambda i: scores[i])
    ranks = [0.0] * len(scores)
    i = 0
    while i < len(order):
        j = i
        while j + 1 < len(order) and scores[order[j + 1]] == scores[order[i]]:
            j += 1
        for t in range(i, j + 1):
            ranks[order[t]] = (i + j) / 2 + 1
        i = j + 1
    rank_sum = sum(r for r, y in zip(ranks, y_true) if y == 1)
    return (rank_sum - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg))


def average_precision(y_true, scores):
    total_pos = sum(1 for y in y_true if y == 1)
    if total_pos == 0:
        raise ValueError("no positives")
    order = sorted(range(len(scores)), key=lambda i: -scores[i])
    tp = seen = 0
    prev_recall = 0.0
    ap = 0.0
    i = 0
    while i < len(order):
        j = i
        while j + 1 < len(order) and scores[order[j + 1]] == scores[order[i]]:
            j += 1
        for t in range(i, j + 1):
            tp += 1 if y_true[order[t]] == 1 else 0
        seen = j + 1
        recall = tp / total_pos
        ap += (recall - prev_recall) * (tp / seen)
        prev_recall = recall
        i = j + 1
    return ap


def precision_recall_at_threshold(y_true, scores, threshold):
    tp = sum(1 for y, s in zip(y_true, scores) if s >= threshold and y == 1)
    fp = sum(1 for y, s in zip(y_true, scores) if s >= threshold and y == 0)
    fn = sum(1 for y, s in zip(y_true, scores) if s < threshold and y == 1)
    precision = tp / (tp + fp) if tp + fp else 0.0
    recall = tp / (tp + fn) if tp + fn else 0.0
    return precision, recall


def cost_threshold(c_fn, c_fp):
    return c_fp / (c_fp + c_fn)


def best_threshold_by_cost(y_true, scores, c_fn, c_fp):
    best = None
    for t in sorted(set(scores)) + [float("inf")]:
        fn = sum(1 for y, s in zip(y_true, scores) if y == 1 and s < t)
        fp = sum(1 for y, s in zip(y_true, scores) if y == 0 and s >= t)
        cost = c_fn * fn + c_fp * fp
        if best is None or cost <= best[1]:
            best = (t, cost)
    return best


def expected_calibration_error(y_true, probs, n_bins=10):
    n = len(y_true)
    bins = [[] for _ in range(n_bins)]
    for y, p in zip(y_true, probs):
        bins[min(int(p * n_bins), n_bins - 1)].append((y, p))
    ece = 0.0
    for b in bins:
        if b:
            frac = sum(y for y, _ in b) / len(b)
            conf = sum(p for _, p in b) / len(b)
            ece += len(b) / n * abs(frac - conf)
    return ece


def duplicate_rows(train_rows, test_rows):
    seen = {tuple(r) for r in train_rows}
    return [i for i, r in enumerate(test_rows) if tuple(r) in seen]


def shared_groups(train_groups, test_groups):
    return sorted(set(train_groups) & set(test_groups))


def balance_by_duplication(indices, labels):
    by_class = {}
    for i in indices:
        by_class.setdefault(labels[i], []).append(i)
    if not by_class:
        return []
    target = max(len(v) for v in by_class.values())
    out = list(indices)
    for cls in sorted(by_class):
        rows = by_class[cls]
        for j in range(target - len(rows)):
            out.append(rows[j % len(rows)])
    return out


T0 = time.time()


def mean(xs):
    xs = list(xs)
    return sum(xs) / len(xs)


def counts(idx, labels):
    out = {}
    for i in idx:
        out[labels[i]] = out.get(labels[i], 0) + 1
    return dict(sorted(out.items()))


def sigmoid(z):
    return 1 / (1 + math.exp(-z))


def logit(p):
    return math.log(p / (1 - p))


def log_loss(y, p):
    return -mean(math.log(q) if t == 1 else math.log(1 - q) for t, q in zip(y, p))


def nn_predict(train_x, train_y, x):
    best, label = None, None
    for r, t in zip(train_x, train_y):
        d = sum((a - b) ** 2 for a, b in zip(r, x))
        if best is None or d < best:
            best, label = d, t
    return label


def balanced_accuracy(y, pred):
    recalls = []
    for c in sorted(set(y)):
        hits = [p == c for t, p in zip(y, pred) if t == c]
        recalls.append(sum(hits) / len(hits))
    return mean(recalls)


print("== 1. The fraud confusion matrix: 10,000 transactions, 20 fraud ==")
for flagged, caught in ((40, 15), (60, 18)):
    tp, fp, fn = caught, flagged - caught, 20 - caught
    tn = 10000 - tp - fp - fn
    prec, rec = tp / (tp + fp), tp / (tp + fn)
    print("flag %d, catch %d: TP %d FP %d FN %d TN %d | accuracy %.4f precision %.3f recall %.2f F1 %.3f"
          % (flagged, caught, tp, fp, fn, tn, (tp + tn) / 10000, prec, rec, 2 * prec * rec / (prec + rec)))
print("never-fraud model: accuracy %.3f, recall 0, cost %d" % (9980 / 10000, 20 * 5000))
for name, fn_, fp_ in (("flag 40, catch 15", 5, 25), ("flag 60, catch 18", 2, 42)):
    print("%s: total cost at 5000 per miss and 50 per false alarm = %d" % (name, 5000 * fn_ + 50 * fp_))

print("\n== 2. ROC-AUC and PR-AUC: the same 100 positives (score ~ N(2,1)), negatives ~ N(0,1) ==")
rng = random.Random(7)
pos = [rng.gauss(2, 1) for _ in range(100)]
neg_all = [rng.gauss(0, 1) for _ in range(49900)]
for name, neg in (("100 negatives (50% positive)", neg_all[:100]), ("49,900 negatives (0.2% positive)", neg_all)):
    y = [1] * len(pos) + [0] * len(neg)
    s = pos + neg
    p, r = precision_recall_at_threshold(y, s, 1.0)
    print("%-34s ROC-AUC %.3f  AP %.3f  | at score >= 1: precision %.3f recall %.2f"
          % (name, roc_auc(y, s), average_precision(y, s), p, r))
print("AP of a constant score on the 0.2%% set: %.4f (the positive rate)" % average_precision(y, [0.5] * len(y)))

print("\n== 3. Threshold from cost: a miss costs 5000, a false alarm 50 (cost units) ==")
print("threshold 50 / 5050 = %.4f" % cost_threshold(5000, 50))
rng = random.Random(3)
probs = [0.8 * rng.random() ** 12 for _ in range(20000)]
ys = [1 if rng.random() < p else 0 for p in probs]
print("calibrated scores: positive rate %.4f" % mean(ys))
for t in (0.5, 0.1, cost_threshold(5000, 50)):
    pr, rc = precision_recall_at_threshold(ys, probs, t)
    fn = sum(1 for y, p in zip(ys, probs) if y == 1 and p < t)
    fp = sum(1 for y, p in zip(ys, probs) if y == 0 and p >= t)
    print("threshold %.4f: cost per row %.2f  precision %.3f recall %.3f" % (t, (5000 * fn + 50 * fp) / 20000, pr, rc))
grid = [i / 1000 for i in range(1, 100)]
cost_of = lambda t: (5000 * sum(1 for y, p in zip(ys, probs) if y == 1 and p < t) + 50 * sum(1 for y, p in zip(ys, probs) if y == 0 and p >= t)) / 20000
bt = min(grid, key=cost_of)
print("cheapest threshold on a 0.001 grid: %.3f (cost per row %.2f)" % (bt, cost_of(bt)))

print("\n== 4. Split indices ==")
y = [0] * 45 + [1] * 5
print("stratified, 45 vs 5, k=3, test class counts:", [counts(te, y) for _, te in stratified_kfold(y, 3)])
print("stratified train class counts:", [counts(tr, y) for tr, _ in stratified_kfold(y, 3)])
print("group k-fold test sets:", [te for _, te in group_kfold([1, 1, 1, 2, 2, 2, 3, 3, 3, 3], 3)])
for i, (tr, te) in enumerate(time_series_split(12, 3, test_size=2, gap=2)):
    print("time series, gap 2, fold %d: train %s test %s" % (i, tr, te))

print("\n== 5. Leakage, measured ==")
# 5a. feature selection before the split, on pure noise
def pick(X, y, rows, k):
    ybar = mean(y[i] for i in rows)
    score = []
    for j in range(len(X[0])):
        xbar = mean(X[i][j] for i in rows)
        score.append(abs(sum((X[i][j] - xbar) * (y[i] - ybar) for i in rows)))
    return sorted(range(len(score)), key=lambda j: -score[j])[:k]

def centroid_accuracy(X, y, cols, tr, te):
    cents = {}
    for c in (0, 1):
        rows = [i for i in tr if y[i] == c]
        cents[c] = [mean(X[i][j] for i in rows) for j in cols]
    hit = 0
    for i in te:
        d = {c: sum((X[i][j] - m) ** 2 for j, m in zip(cols, cents[c])) for c in (0, 1)}
        hit += (0 if d[0] <= d[1] else 1) == y[i]
    return hit / len(te)

leaky, honest = [], []
for seed in range(20):
    rng = random.Random(seed)
    X = [[rng.gauss(0, 1) for _ in range(2000)] for _ in range(100)]
    yy = [rng.randrange(2) for _ in range(100)]
    tr, te = list(range(50)), list(range(50, 100))
    leaky.append(centroid_accuracy(X, yy, pick(X, yy, range(100), 10), tr, te))
    honest.append(centroid_accuracy(X, yy, pick(X, yy, tr, 10), tr, te))
print("5a. noise features and labels, 100 rows, 2000 features, 10 kept, 20 repeats:")
print("    selection on all rows: test accuracy %.3f | selection on train rows only: %.3f" % (mean(leaky), mean(honest)))

# 5b. the same patient on both sides of the split
def patient_cv(seed):
    rng = random.Random(seed)
    rows, labels, who = [], [], []
    for p in range(100):
        base = [rng.gauss(0, 1) for _ in range(3)]
        label = rng.randrange(2)
        for _ in range(5):
            rows.append([b + rng.gauss(0, 0.1) for b in base])
            labels.append(label)
            who.append(p)
    perm = list(range(len(rows)))
    rng.shuffle(perm)
    row_folds = [([i for i in range(500) if perm[i] % 5 != f], [i for i in range(500) if perm[i] % 5 == f]) for f in range(5)]
    out = []
    for folds in (row_folds, group_kfold(who, 5)):
        hits = 0
        for tr, te in folds:
            trx, trl = [rows[i] for i in tr], [labels[i] for i in tr]
            hits += sum(nn_predict(trx, trl, rows[i]) == labels[i] for i in te)
        out.append(hits / 500)
        out.append(len(shared_groups([who[i] for i in folds[0][0]], [who[i] for i in folds[0][1]])))
    return out
runs = [patient_cv(s) for s in range(5)]
print("5b. 100 patients x 5 visits, labels are coin flips per patient, 1-nearest-neighbour, 5 repeats:")
print("    row-level 5-fold: accuracy %.3f, patients on both sides in fold 0: %.0f" % (mean(r[0] for r in runs), mean(r[1] for r in runs)))
print("    group 5-fold:     accuracy %.3f, patients on both sides in fold 0: %.0f" % (mean(r[2] for r in runs), mean(r[3] for r in runs)))

# 5c. a random split on a time series
rng = random.Random(5)
walk, v = [], 0.0
for _ in range(300):
    v += rng.gauss(0, 1)
    walk.append(v)
def nearest_time_mae(folds):
    errs = []
    for tr, te in folds:
        for i in te:
            j = min(tr, key=lambda t: abs(t - i))
            errs.append(abs(walk[i] - walk[j]))
    return mean(errs)
perm = list(range(300))
rng.shuffle(perm)
rand_folds = [([i for i in range(300) if perm[i] % 5 != f], [i for i in range(300) if perm[i] % 5 == f]) for f in range(5)]
print("5c. random walk, predict each value from the nearest training time step:")
print("    random 5-fold MAE %.2f | forward-chaining (5 splits, test blocks of 50) MAE %.2f" % (nearest_time_mae(rand_folds), nearest_time_mae(time_series_split(300, 5))))

print("\n== 6. Resampling inside versus outside the folds (noise data, 15 positives of 300) ==")
res = {"duplicate first": [], "inside folds": []}
overlap = []
for seed in range(5):
    rng = random.Random(100 + seed)
    X = [[rng.gauss(0, 1) for _ in range(4)] for _ in range(300)]
    yy = [1] * 15 + [0] * 285
    rng.shuffle(yy)
    allrows = balance_by_duplication(list(range(300)), yy)
    rng.shuffle(allrows)
    bx, by = [X[i] for i in allrows], [yy[i] for i in allrows]
    accs = []
    for tr, te in stratified_kfold(by, 5):
        pred = [nn_predict([bx[i] for i in tr], [by[i] for i in tr], bx[i]) for i in te]
        accs.append(balanced_accuracy([by[i] for i in te], pred))
    res["duplicate first"].append(mean(accs))
    first = stratified_kfold(by, 5)[0]
    overlap.append(len(duplicate_rows([bx[i] for i in first[0]], [bx[i] for i in first[1]])) / len(first[1]))
    accs = []
    for tr, te in stratified_kfold(yy, 5):
        tr2 = balance_by_duplication(tr, yy)
        pred = [nn_predict([X[i] for i in tr2], [yy[i] for i in tr2], X[i]) for i in te]
        accs.append(balanced_accuracy([yy[i] for i in te], pred))
    res["inside folds"].append(mean(accs))
print("balanced accuracy over 5 seeds, 1-nearest-neighbour (honest value is about 0.5):")
for k, v in res.items():
    print("    %-17s %.3f" % (k, mean(v)))
print("    share of validation rows that have an exact copy in the training part (duplicate first): %.2f" % mean(overlap))

print("\n== 7. Calibration ==")
w, p0 = 99, 0.01
print("upweighting positives by %d turns a true probability of %.2f into %.3f" % (w, p0, w * p0 / (1 - p0 + w * p0)))
print("downsampling negatives 25x turns a 99/1 split into %.1f%% positives" % (100 * 1 / (1 + 99 / 25)))
rng = random.Random(1)
true_p = [min(max(rng.random(), 0.001), 0.999) for _ in range(20000)]
yc = [1 if rng.random() < p else 0 for p in true_p]
over = [sigmoid(2 * logit(p)) for p in true_p]
fixed = [sigmoid(logit(p) / 2) for p in over]
for name, q in (("calibrated", true_p), ("overconfident (logit x2)", over), ("rescaled back (logit / 2)", fixed)):
    print("%-26s ECE %.3f  log loss %.3f  ROC-AUC %.4f" % (name, expected_calibration_error(yc, q), log_loss(yc, q), roc_auc(yc, q)))

print("\n== 8. Regression metrics and error slices ==")
err = [1, 1, 1, 1, 20]
print("errors %s: MAE %.1f, RMSE %.2f" % (err, mean(err), math.sqrt(mean(e * e for e in err))))
print("actual 0.1 predicted 1.1: absolute percentage error %.0f%%" % (100 * abs(1.1 - 0.1) / 0.1))
n_, n_pos = 100, 1
print("balanced class weights for 99 negatives and 1 positive: negative %.4f, positive %.1f" % (n_ / (2 * (n_ - n_pos)), n_ / (2 * n_pos)))
prior = 0.002
print("log loss of always predicting the base rate 0.002: %.4f" % -(prior * math.log(prior) + (1 - prior) * math.log(1 - prior)))
print("slices: 9000 rows at 95%% correct and 1000 rows at 70%% correct give overall %.1f%%" % (100 * (9000 * 0.95 + 1000 * 0.70) / 10000))

print("\ntotal %.1f s" % (time.time() - T0))

Statistics and experimentation: intervals, tests, power, A/B tests and fair model comparison

Evaluation, statistics and data

Show the code (467 lines)

Python

import math
from itertools import combinations
from statistics import NormalDist

EPS = 1e-12


def _mean(xs):
    return sum(xs) / len(xs)


def bootstrap_ci(data, stat, n_resamples, alpha, rng):
    n = len(data)
    if n == 0 or n_resamples < 1 or not 0 < alpha < 1:
        raise ValueError("need data, n_resamples >= 1 and 0 < alpha < 1")
    stats = []
    for _ in range(n_resamples):
        stats.append(stat([data[rng.randrange(n)] for _ in range(n)]))
    stats.sort()
    lo = int(math.floor(round(alpha / 2 * n_resamples, 9)))
    hi = int(math.ceil(round((1 - alpha / 2) * n_resamples, 9))) - 1
    return stats[lo], stats[hi]


def _check_alt(alternative):
    if alternative not in ("two-sided", "greater", "less"):
        raise ValueError("alternative must be 'two-sided', 'greater' or 'less'")


def _is_extreme(t, observed, alternative):
    if alternative == "greater":
        return t >= observed - EPS
    if alternative == "less":
        return t <= observed + EPS
    return abs(t) >= abs(observed) - EPS


def permutation_test(a, b, n_resamples, rng, alternative="two-sided"):
    _check_alt(alternative)
    if not a or not b or n_resamples < 1:
        raise ValueError("need two non-empty samples and n_resamples >= 1")
    na = len(a)
    observed = _mean(a) - _mean(b)
    pooled = list(a) + list(b)
    extreme = 0
    for _ in range(n_resamples):
        rng.shuffle(pooled)
        t = _mean(pooled[:na]) - _mean(pooled[na:])
        if _is_extreme(t, observed, alternative):
            extreme += 1
    return observed, (extreme + 1) / (n_resamples + 1)


def exact_permutation_test(a, b, alternative="two-sided"):
    _check_alt(alternative)
    if not a or not b:
        raise ValueError("need two non-empty samples")
    n, na = len(a) + len(b), len(a)
    if math.comb(n, na) > 200000:
        raise ValueError("too many permutations for an exact test")
    pooled = list(a) + list(b)
    total_sum = sum(pooled)
    observed = _mean(a) - _mean(b)
    extreme = total = 0
    for idx in combinations(range(n), na):
        sa = sum(pooled[i] for i in idx)
        t = sa / na - (total_sum - sa) / (n - na)
        total += 1
        if _is_extreme(t, observed, alternative):
            extreme += 1
    return observed, extreme / total


def two_proportion_ztest(x1, n1, x2, n2):
    if n1 <= 0 or n2 <= 0 or not 0 <= x1 <= n1 or not 0 <= x2 <= n2:
        raise ValueError("need 0 <= x <= n and n > 0 in both groups")
    pooled = (x1 + x2) / (n1 + n2)
    if pooled in (0.0, 1.0):
        raise ValueError("pooled proportion is 0 or 1: no variation")
    se = math.sqrt(pooled * (1 - pooled) * (1 / n1 + 1 / n2))
    diff = x2 / n2 - x1 / n1
    z = diff / se
    return diff, z, math.erfc(abs(z) / math.sqrt(2))


def sample_size_per_arm(p1, p2, alpha=0.05, power=0.8):
    if not (0 < p1 < 1 and 0 < p2 < 1 and 0 < alpha < 1 and 0 < power < 1) or p1 == p2:
        raise ValueError("need different proportions in (0, 1) and alpha, power in (0, 1)")
    nd = NormalDist()
    z_sum = nd.inv_cdf(1 - alpha / 2) + nd.inv_cdf(power)
    return math.ceil(z_sum ** 2 * (p1 * (1 - p1) + p2 * (1 - p2)) / (p1 - p2) ** 2)


def power_two_proportions(p1, p2, n, alpha=0.05):
    if n < 1 or not (0 < p1 < 1 and 0 < p2 < 1 and 0 < alpha < 1):
        raise ValueError("need n >= 1, proportions in (0, 1) and alpha in (0, 1)")
    nd = NormalDist()
    se = math.sqrt((p1 * (1 - p1) + p2 * (1 - p2)) / n)
    d = abs(p1 - p2) / se
    zc = nd.inv_cdf(1 - alpha / 2)
    return nd.cdf(d - zc) + nd.cdf(-d - zc)


def bonferroni_reject(pvals, alpha=0.05):
    m = len(pvals)
    return [p <= alpha / m + EPS for p in pvals]


def bh_adjust(pvals):
    m = len(pvals)
    order = sorted(range(m), key=lambda i: (pvals[i], i))
    adjusted = [0.0] * m
    running = 1.0
    for rank in range(m, 0, -1):
        i = order[rank - 1]
        running = min(running, pvals[i] * m / rank)
        adjusted[i] = running
    return adjusted


def bh_reject(pvals, q=0.05):
    return [a <= q + EPS for a in bh_adjust(pvals)]


def _gamma_upper_regularized(a, x):
    if x <= 0:
        return 1.0
    if x < a + 1:
        term = total = 1.0 / a
        n = a
        for _ in range(1000):
            n += 1
            term *= x / n
            total += term
            if abs(term) < abs(total) * 1e-15:
                break
        return 1.0 - total * math.exp(-x + a * math.log(x) - math.lgamma(a))
    tiny = 1e-300
    b = x + 1 - a
    c = 1 / tiny
    d = 1 / b
    h = d
    for i in range(1, 1000):
        an = -i * (i - a)
        b += 2
        d = an * d + b
        d = tiny if abs(d) < tiny else d
        c = b + an / c
        c = tiny if abs(c) < tiny else c
        d = 1 / d
        delta = d * c
        h *= delta
        if abs(delta - 1) < 1e-15:
            break
    return math.exp(-x + a * math.log(x) - math.lgamma(a)) * h


def chi2_sf(x, df):
    if not isinstance(df, int) or df < 1:
        raise ValueError("df must be a positive integer")
    return min(1.0, max(0.0, _gamma_upper_regularized(df / 2, x / 2)))


def srm_check(observed, expected_ratios):
    k = len(observed)
    if k < 2 or len(expected_ratios) != k or any(o < 0 for o in observed):
        raise ValueError("need k >= 2 arms, matching ratios and non-negative counts")
    if any(r <= 0 for r in expected_ratios) or sum(observed) <= 0:
        raise ValueError("ratios must be positive and the total must be positive")
    total = sum(observed)
    rsum = sum(expected_ratios)
    stat = 0.0
    for o, r in zip(observed, expected_ratios):
        e = total * r / rsum
        stat += (o - e) ** 2 / e
    return stat, chi2_sf(stat, k - 1)


def mcnemar_test(b, c):
    if b < 0 or c < 0:
        raise ValueError("counts cannot be negative")
    if b + c == 0:
        return 0.0, 1.0
    stat = max(abs(b - c) - 1, 0) ** 2 / (b + c)
    return stat, chi2_sf(stat, 1)


def corrected_resampled_t(diffs, n_train, n_test):
    k = len(diffs)
    if k < 2 or n_train <= 0 or n_test <= 0:
        raise ValueError("need at least 2 differences and positive set sizes")
    mu = _mean(diffs)
    s2 = sum((d - mu) ** 2 for d in diffs) / (k - 1)
    if s2 == 0:
        raise ValueError("zero variance")
    return mu / math.sqrt((1 / k + n_test / n_train) * s2)


# ---------------------------------------------------------------- experiments
import random
import time
from statistics import NormalDist

T0 = time.time()
ND = NormalDist()


def mean(xs):
    return sum(xs) / len(xs)


def var_unbiased(xs):
    m = mean(xs)
    return sum((x - m) ** 2 for x in xs) / (len(xs) - 1)


def binomial(rng, n, p):
    return sum(1 for _ in range(n) if rng.random() < p)


def normal_pvalue(z):
    return math.erfc(abs(z) / math.sqrt(2))


print("== 1. Sampling, estimators, bias and variance")
rng = random.Random(1)
print("1a. mean of n draws from Exponential(1) (mean 1, sd 1), 4000 repeats")
for n in (5, 30, 200):
    means = [mean([rng.expovariate(1.0) for _ in range(n)]) for _ in range(4000)]
    mu = mean(means)
    sd = math.sqrt(var_unbiased(means))
    lo = sum(1 for m in means if m < 1 - 1.96 / math.sqrt(n)) / len(means)
    hi = sum(1 for m in means if m > 1 + 1.96 / math.sqrt(n)) / len(means)
    print("   n=%3d: mean of means %.3f, sd of the mean %.3f (sigma/sqrt(n) = %.3f), below-tail %.3f, above-tail %.3f"
          % (n, mu, sd, 1 / math.sqrt(n), lo, hi))

rng = random.Random(2)
v_n, v_n1, sd_n1 = [], [], []
for _ in range(20000):
    xs = [rng.gauss(0, 1) for _ in range(5)]
    m = mean(xs)
    ss = sum((x - m) ** 2 for x in xs)
    v_n.append(ss / 5)
    v_n1.append(ss / 4)
    sd_n1.append(math.sqrt(ss / 4))
print("1b. n=5, true variance 1, 20000 repeats: average of divide-by-n %.3f, divide-by-(n-1) %.3f, average of the square root of the latter %.3f"
      % (mean(v_n), mean(v_n1), mean(sd_n1)))

rng = random.Random(3)
true_mu, n, c = 0.5, 10, 0.8
err_plain, err_shrunk = [], []
for _ in range(40000):
    xbar = mean([rng.gauss(true_mu, 1) for _ in range(n)])
    err_plain.append((xbar - true_mu) ** 2)
    err_shrunk.append((c * xbar - true_mu) ** 2)
print("1c. estimating a mean of 0.5 from n=10 draws with sd 1: MSE of the sample mean %.4f (theory %.4f), MSE of 0.8 x the mean %.4f (theory %.4f = variance %.4f + bias^2 %.4f)"
      % (mean(err_plain), 1 / n, mean(err_shrunk), c * c / n + ((c - 1) * true_mu) ** 2, c * c / n, ((c - 1) * true_mu) ** 2))

def t_coverage(c, df, steps=20000):
    def pdf(x):
        return math.exp(math.lgamma((df + 1) / 2) - math.lgamma(df / 2)) / math.sqrt(df * math.pi) * (1 + x * x / df) ** (-(df + 1) / 2)
    h = c / steps
    total = pdf(0) + pdf(c) + sum(pdf(i * h) * (4 if i % 2 else 2) for i in range(1, steps))
    return 2 * total * h / 3


print("\n== 2. Confidence intervals: analytic and bootstrap")
print("   theory for normal data, n=10: an interval mean +/- 1.96 s/sqrt(n) covers with probability P(|t9| < 1.96) = %.3f; with the divide-by-n spread (as the bootstrap sees it) P(|t9| < 1.96 sqrt(0.9)) = %.3f"
      % (t_coverage(1.96, 9), t_coverage(1.96 * math.sqrt(0.9), 9)))
rng = random.Random(4)
reps = 400
cases = [("normal data, n=10", 10, lambda: rng.gauss(0, 1), 0.0),
         ("lognormal(0,1) data, n=15", 15, lambda: math.exp(rng.gauss(0, 1)), math.exp(0.5)),
         ("lognormal(0,1) data, n=60", 60, lambda: math.exp(rng.gauss(0, 1)), math.exp(0.5))]
for label, n, draw, truth in cases:
    hit_z = hit_b = low_z = low_b = 0
    width_z = width_b = 0.0
    for _ in range(reps):
        xs = [draw() for _ in range(n)]
        m, s = mean(xs), math.sqrt(var_unbiased(xs))
        lo, hi = m - 1.96 * s / math.sqrt(n), m + 1.96 * s / math.sqrt(n)
        hit_z += lo <= truth <= hi
        low_z += hi < truth
        width_z += hi - lo
        blo, bhi = bootstrap_ci(xs, mean, 200, 0.05, rng)
        hit_b += blo <= truth <= bhi
        low_b += bhi < truth
        width_b += bhi - blo
    print("   %-26s coverage: normal-approximation %.3f (width %.2f), percentile bootstrap %.3f (width %.2f)"
          % (label, hit_z / reps, width_z / reps, hit_b / reps, width_b / reps))
    print("   %-26s share of misses that lie entirely below the true mean: normal-approximation %.2f, bootstrap %.2f"
          % ("", low_z / max(reps - hit_z, 1), low_b / max(reps - hit_b, 1)))
data = [3, 5, 4, 9, 4, 6, 3, 5, 4, 5, 20, 4]
lo, hi = bootstrap_ci(data, mean, 2000, 0.05, random.Random(5))
print("   one dataset: mean %.3f, 95%% bootstrap interval (%.3f, %.3f)" % (mean(data), lo, hi))
lo, hi = bootstrap_ci(data, lambda xs: sorted(xs)[len(xs) // 2 - 1] / 2 + sorted(xs)[len(xs) // 2] / 2, 2000, 0.05, random.Random(5))
print("   same data, median: 95%% bootstrap interval (%.3f, %.3f)" % (lo, hi))

print("\n== 3. Hypothesis tests on a conversion test")
d, z, p = two_proportion_ztest(1000, 10000, 1090, 10000)
se = math.sqrt(0.1 * 0.9 / 10000 + (1090 / 10000) * (1 - 1090 / 10000) / 10000)
print("   1000/10000 against 1090/10000: lift %.4f, z %.3f, p %.4f, 95%% interval for the lift (%.4f, %.4f)"
      % (d, z, p, d - 1.96 * se, d + 1.96 * se))
d, z, p = two_proportion_ztest(200, 2000, 218, 2000)
print("   same rates on a fifth of the traffic (200/2000 against 218/2000): lift %.4f, z %.3f, p %.4f" % (d, z, p))
d, z, p = two_proportion_ztest(10000, 100000, 10090, 100000)
print("   same lift of 0.0009 with 100000 per arm: z %.3f, p %.5f" % (z, p))
a = [12, 15, 9, 20, 31, 11]
b = [8, 10, 7, 11, 9, 14, 6]
obs, p_exact = exact_permutation_test(a, b)
obs2, p_rand = permutation_test(a, b, 9999, random.Random(6))
print("   permutation test, 6 against 7 skewed values: difference in means %.3f, exact p %.4f (1716 splits), randomised p %.4f (9999 shuffles)"
      % (obs, p_exact, p_rand))
p_greater = exact_permutation_test(a, b, "greater")[1]
print("   one-sided exact p (greater) %.4f; twice the smaller one-sided p, the convention of scipy.stats.permutation_test, is %.4f against the %.4f above" % (p_greater, 2 * p_greater, p_exact))

print("\n== 4. What a p-value is, and is not")
rng = random.Random(7)
ps = []
for _ in range(2000):
    x1, x2 = binomial(rng, 500, 0.1), binomial(rng, 500, 0.1)
    ps.append(two_proportion_ztest(x1, 500, x2, 500)[2])
print("   2000 A/A tests (no true effect), 500 users per arm: share with p < 0.05 is %.3f, share with p < 0.5 is %.3f"
      % (sum(1 for q in ps if q < 0.05) / len(ps), sum(1 for q in ps if q < 0.5) / len(ps)))
rng = random.Random(8)
sims, looks, per_look = 1000, 10, 100
fixed = peeked = 0
for _ in range(sims):
    c1 = c2 = 0
    stopped = False
    for k in range(1, looks + 1):
        c1 += binomial(rng, per_look, 0.1)
        c2 += binomial(rng, per_look, 0.1)
        q = two_proportion_ztest(c1, k * per_look, c2, k * per_look)[2] if c1 + c2 > 0 else 1.0
        if q < 0.05:
            stopped = True
        if k == looks and q < 0.05:
            fixed += 1
    peeked += stopped
print("   1000 A/A tests with up to 10 looks (1000 users per arm at the end): fixed-horizon false positives %.3f, stop-at-first-significant %.3f"
      % (fixed / sims, peeked / sims))
prior_real, power_, alpha_ = 0.10, 0.80, 0.05
ppv = power_ * prior_real / (power_ * prior_real + alpha_ * (1 - prior_real))
print("   if 10%% of tested ideas truly work, power is 0.80 and alpha 0.05, the chance that a significant result is real is %.3f" % ppv)

print("\n== 5. Power and sample size")
for p2 in (0.12, 0.11, 0.105):
    print("   baseline 0.10 against %.3f: %6d users per arm" % (p2, sample_size_per_arm(0.10, p2)))
print("   cost ratio, 0.5-point lift against 2-point lift: %.2f times the users" % (sample_size_per_arm(0.10, 0.105) / sample_size_per_arm(0.10, 0.12)))
print("   rule of 16 for baseline 0.10 and a 0.01 lift: %.0f per arm; exact formula: %d" % (16 * 0.09 / 0.01 ** 2, sample_size_per_arm(0.10, 0.11)))
n_need = sample_size_per_arm(0.30, 0.35)
print("   baseline 0.30 against 0.35 needs %d per arm; formula power at that n %.3f; at 500 per arm %.3f" % (n_need, power_two_proportions(0.30, 0.35, n_need), power_two_proportions(0.30, 0.35, 500)))
rng = random.Random(9)
for n in (n_need, 500):
    wins = 0
    trials = 600
    for _ in range(trials):
        q = two_proportion_ztest(binomial(rng, n, 0.30), n, binomial(rng, n, 0.35), n)[2]
        wins += q < 0.05
    print("   simulated power with %d per arm over %d trials: %.3f" % (n, trials, wins / trials))

print("\n== 6. Many comparisons")
print("   chance of at least one p < 0.05 among 20 independent true nulls: %.3f" % (1 - 0.95 ** 20))
pv = [0.001, 0.012, 0.018, 0.030, 0.45]
print("   p-values %s: Bonferroni cut-off %.3f rejects %d; BH adjusted %s rejects %d at q 0.05"
      % (pv, 0.05 / 5, sum(bonferroni_reject(pv)), [round(x, 4) for x in bh_adjust(pv)], sum(bh_reject(pv))))
rng = random.Random(10)
tot = {"uncorrected": [0, 0, 0], "bonferroni": [0, 0, 0], "bh": [0, 0, 0]}
reps = 500
for _ in range(reps):
    pvals = [rng.random() for _ in range(80)] + [normal_pvalue(rng.gauss(3, 1)) for _ in range(20)]
    for name, rej in (("uncorrected", [x < 0.05 for x in pvals]), ("bonferroni", bonferroni_reject(pvals)), ("bh", bh_reject(pvals))):
        false_d = sum(rej[:80])
        true_d = sum(rej[80:])
        tot[name][0] += false_d
        tot[name][1] += true_d
        tot[name][2] += (false_d / (false_d + true_d)) if false_d + true_d else 0.0
for name, (f, t, fdp) in tot.items():
    print("   %-12s per 100 tests (80 null, 20 real, z shift 3): false discoveries %.2f, true discoveries %.2f, false discovery proportion %.3f"
          % (name, f / reps, t / reps, fdp / reps))

print("\n== 7. Experiments on ML systems")
rng = random.Random(11)
sims, users, views = 500, 200, 20
a_, b_ = 1, 9
rho = (a_ * b_ / ((a_ + b_) ** 2 * (a_ + b_ + 1))) / (0.1 * 0.9)
deff = 1 + (views - 1) * rho
bad = 0
for _ in range(sims):
    counts = []
    for _arm in range(2):
        clicks = 0
        for _u in range(users):
            pu = rng.betavariate(a_, b_)
            clicks += binomial(rng, views, pu)
        counts.append(clicks)
    bad += two_proportion_ztest(counts[0], users * views, counts[1], users * views)[2] < 0.05
print("   A/A tests, 200 users per arm, 20 page views each, randomised by USER but analysed by page view: false positives %.3f" % (bad / sims))
print("   within-user correlation rho %.4f, design effect 1 + (m - 1) rho = %.2f, predicted false-positive rate %.3f"
      % (rho, deff, 2 * (1 - ND.cdf(1.96 / math.sqrt(deff)))))
for obs_ in ([10400, 9600], [50500, 49500], [520, 480], [5200, 4800]):
    stat, p = srm_check(obs_, [1, 1])
    print("   SRM check, observed %s against a 50/50 design: chi-square %.2f, p %.3g" % (obs_, stat, p))
print("   three arms 3400/3300/3300 against 1:1:1 -> chi-square %.2f, p %.3f" % srm_check([3400, 3300, 3300], [1, 1, 1]))
a_easy, a_hard, b_easy, b_hard = (90, 100), (300, 900), (800, 900), (30, 100)
print("   Simpson: arm A easy %.3f hard %.3f overall %.3f; arm B easy %.3f hard %.3f overall %.3f"
      % (a_easy[0] / a_easy[1], a_hard[0] / a_hard[1], (a_easy[0] + a_hard[0]) / (a_easy[1] + a_hard[1]),
         b_easy[0] / b_easy[1], b_hard[0] / b_hard[1], (b_easy[0] + b_hard[0]) / (b_easy[1] + b_hard[1])))

print("\n== 8. Comparing two models fairly")
rng = random.Random(12)
n_items = 1000
a_right, b_right = [], []
for _ in range(n_items):
    difficulty = rng.gauss(0, 1)
    a_right.append(difficulty + rng.gauss(0, 0.3) < 0.84)
    b_right.append(difficulty + rng.gauss(0, 0.3) < 0.99)
acc_a, acc_b = mean(a_right), mean(b_right)
only_a = sum(1 for x, y in zip(a_right, b_right) if x and not y)
only_b = sum(1 for x, y in zip(a_right, b_right) if y and not x)
stat, p_mc = mcnemar_test(only_a, only_b)
_, z_u, p_u = two_proportion_ztest(sum(a_right), n_items, sum(b_right), n_items)
print("   accuracy A %.3f, B %.3f; A-only right %d, B-only right %d" % (acc_a, acc_b, only_a, only_b))
print("   McNemar (paired): chi-square %.2f, p %.4f; unpaired two-proportion z-test on the same accuracies: z %.2f, p %.4f" % (stat, p_mc, z_u, p_u))
diffs_items = [(1 if y else 0) - (1 if x else 0) for x, y in zip(a_right, b_right)]
lo, hi = bootstrap_ci(diffs_items, mean, 2000, 0.05, random.Random(13))
print("   bootstrap 95%% interval for the accuracy gain B minus A over the items: (%.4f, %.4f)" % (lo, hi))
diffs = [0.012, 0.020, 0.008, 0.015, 0.011, 0.018, 0.006, 0.014, 0.017, 0.009]
k = len(diffs)
naive = mean(diffs) / math.sqrt(var_unbiased(diffs) / k)
corr = corrected_resampled_t(diffs, 900, 100)
print("   ten 90/10 splits, score gaps (constructed): naive t %.2f, corrected t %.2f (ratio %.3f)" % (naive, corr, corr / naive))

print("\n== 9. A Bayesian view")
print("   1%% prevalence, sensitivity 90%%, false-positive rate 10%%: P(disease | +) = %.4f" % (0.01 * 0.9 / (0.01 * 0.9 + 0.99 * 0.1)))
print("   1%% prevalence, sensitivity 99%%, false-positive rate 5%%: P(disease | +) = %.4f" % (0.01 * 0.99 / (0.01 * 0.99 + 0.99 * 0.05)))
print("   10%% prevalence, sensitivity 90%%, false-positive rate 10%%: P(disease | +) = %.4f" % (0.10 * 0.9 / (0.10 * 0.9 + 0.90 * 0.1)))
print("   0.1%% prevalence, sensitivity 90%%, false-positive rate 10%%: P(disease | +) = %.4f" % (0.001 * 0.9 / (0.001 * 0.9 + 0.999 * 0.1)))
rng = random.Random(14)
draws = 20000
pa = [rng.betavariate(1 + 100, 1 + 900) for _ in range(draws)]
pb = [rng.betavariate(1 + 120, 1 + 880) for _ in range(draws)]
lift = sorted(y - x for x, y in zip(pa, pb))
print("   Beta(1,1) prior, A 100/1000, B 120/1000: posterior mean A %.4f, B %.4f, P(B > A) = %.3f, 95%% credible interval for the lift (%.4f, %.4f)"
      % (101 / 1002, 121 / 1002, sum(1 for x, y in zip(pa, pb) if y > x) / draws, lift[int(0.025 * draws)], lift[int(0.975 * draws) - 1]))
d, z, p = two_proportion_ztest(100, 1000, 120, 1000)
print("   same data with the z-test: lift %.3f, z %.3f, two-sided p %.4f, one-sided p %.4f (posterior P(A >= B) = %.3f)" % (d, z, p, p / 2, 1 - sum(1 for x, y in zip(pa, pb) if y > x) / draws))

print("\n== 10. Correlation and causation")
rng = random.Random(15)
N = 20000
zs = [rng.gauss(0, 1) for _ in range(N)]
xs = [z_ + rng.gauss(0, 1) for z_ in zs]
ys = [z_ + rng.gauss(0, 1) for z_ in zs]
xr = [rng.gauss(0, 1.4142135623730951) for _ in range(N)]


def corr(u, v):
    mu, mv = mean(u), mean(v)
    cov = sum((a_ - mu) * (b_ - mv) for a_, b_ in zip(u, v))
    return cov / math.sqrt(sum((a_ - mu) ** 2 for a_ in u) * sum((b_ - mv) ** 2 for b_ in v))


print("   a hidden Z drives both X and Y; X has no effect on Y. Observed corr(X, Y) = %.3f (theory 0.5)" % corr(xs, ys))
print("   assign X at random instead: corr(X, Y) = %.3f" % corr(xr, ys))

print("\ntotal %.1f s" % (time.time() - T0))

Data, features and production ML: preprocessing, encodings, point-in-time features, skew, drift and operations

Evaluation, statistics and data

Python

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

numeric = Pipeline([
    ("impute", SimpleImputer(strategy="median", add_indicator=True)),
    ("scale", StandardScaler()),
])
prep = ColumnTransformer([
    ("num", numeric, ["age", "income"]),
    ("cat", OneHotEncoder(handle_unknown="ignore"), ["city", "device"]),
])
model = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))])

model.fit(X_train, y_train)           # every statistic is learned here, on training rows only
scores = model.predict_proba(X_new)   # serving applies the same fitted steps
Show the code (552 lines)

Python

import math
from bisect import bisect_right

EPS = 1e-12


def _is_missing(v):
    return v is None or (isinstance(v, float) and math.isnan(v))


def _mean(xs):
    return sum(xs) / len(xs)


class Imputer:
    def __init__(self, strategy="mean"):
        if strategy not in ("mean", "median", "most_frequent"):
            raise ValueError("strategy must be 'mean', 'median' or 'most_frequent'")
        self.strategy = strategy
        self.fill_ = None

    def fit(self, values):
        present = [v for v in values if not _is_missing(v)]
        if not present:
            raise ValueError("no observed values to learn from")
        if self.strategy == "mean":
            self.fill_ = _mean(present)
        elif self.strategy == "median":
            s = sorted(present)
            mid = len(s) // 2
            self.fill_ = s[mid] if len(s) % 2 == 1 else (s[mid - 1] + s[mid]) / 2
        else:
            counts = {}
            for v in present:
                counts[v] = counts.get(v, 0) + 1
            best = max(counts.values())
            self.fill_ = min(v for v, c in counts.items() if c == best)
        return self

    def transform(self, values):
        if self.fill_ is None:
            raise RuntimeError("call fit first")
        filled, flags = [], []
        for v in values:
            if _is_missing(v):
                filled.append(self.fill_)
                flags.append(1)
            else:
                filled.append(v)
                flags.append(0)
        return filled, flags


class StandardScaler:
    def __init__(self):
        self.mean_ = None
        self.scale_ = None

    def fit(self, values):
        if len(values) == 0:
            raise ValueError("cannot fit on an empty column")
        self.mean_ = _mean(values)
        std = math.sqrt(sum((v - self.mean_) ** 2 for v in values) / len(values))
        self.scale_ = std if std >= EPS else 1.0
        return self

    def transform(self, values):
        if self.mean_ is None:
            raise RuntimeError("call fit first")
        return [(v - self.mean_) / self.scale_ for v in values]


class OneHotEncoder:
    def __init__(self):
        self.categories_ = None

    def fit(self, values):
        self.categories_ = sorted(set(values))
        return self

    def transform(self, values):
        if self.categories_ is None:
            raise RuntimeError("call fit first")
        index = {c: i for i, c in enumerate(self.categories_)}
        rows = []
        for v in values:
            row = [0] * len(self.categories_)
            if v in index:
                row[index[v]] = 1
            rows.append(row)
        return rows


def target_encoding_fit(categories, y, smooth):
    if len(categories) != len(y) or len(y) == 0 or smooth < 0:
        raise ValueError("need equal, non-empty lists and smooth >= 0")
    prior = _mean(y)
    n, s = {}, {}
    for c, t in zip(categories, y):
        n[c] = n.get(c, 0) + 1
        s[c] = s.get(c, 0) + t
    encoding = {c: (s[c] + smooth * prior) / (n[c] + smooth) for c in n}
    return encoding, prior


def target_encoding_apply(categories, encoding, prior):
    return [encoding.get(c, prior) for c in categories]


def target_encoding_oof(categories, y, n_folds, smooth):
    n = len(y)
    if len(categories) != n or n_folds < 2 or n_folds > n or smooth < 0:
        raise ValueError("need equal lists, 2 <= n_folds <= len(y) and smooth >= 0")
    out = [0.0] * n
    for f in range(n_folds):
        train = [i for i in range(n) if i % n_folds != f]
        enc, prior = target_encoding_fit([categories[i] for i in train], [y[i] for i in train], smooth)
        for i in range(f, n, n_folds):
            out[i] = enc.get(categories[i], prior)
    return out


def quantile_edges(values, bins):
    if len(values) == 0 or bins < 2:
        raise ValueError("need values and bins >= 2")
    s = sorted(values)
    n = len(s)
    edges = []
    for k in range(1, bins):
        lo, rem = divmod(k * (n - 1), bins)
        hi = min(lo + 1, n - 1)
        edges.append(s[lo] + rem / bins * (s[hi] - s[lo]))
    return edges


def bin_counts(values, edges):
    if any(edges[i] > edges[i + 1] for i in range(len(edges) - 1)):
        raise ValueError("edges must be sorted")
    counts = [0] * (len(edges) + 1)
    for v in values:
        counts[bisect_right(edges, v)] += 1
    return counts


def psi(expected_counts, actual_counts, eps=1e-4):
    if len(expected_counts) != len(actual_counts) or len(expected_counts) == 0:
        raise ValueError("need two lists of the same non-zero length")
    if min(expected_counts) < 0 or min(actual_counts) < 0:
        raise ValueError("counts cannot be negative")
    te, ta = sum(expected_counts), sum(actual_counts)
    if te == 0 or ta == 0:
        raise ValueError("a total of zero has no shares")
    total = 0.0
    for ce, ca in zip(expected_counts, actual_counts):
        e = max(ce / te, eps)
        a = max(ca / ta, eps)
        total += (a - e) * math.log(a / e)
    return total


def ks_statistic(a, b):
    if len(a) == 0 or len(b) == 0:
        raise ValueError("both samples need values")
    xs, ys = sorted(a), sorted(b)
    n, m = len(xs), len(ys)
    i = j = 0
    best = 0.0
    while i < n or j < m:
        if j >= m or (i < n and xs[i] <= ys[j]):
            v = xs[i]
        else:
            v = ys[j]
        while i < n and xs[i] <= v:
            i += 1
        while j < m and ys[j] <= v:
            j += 1
        best = max(best, abs(i / n - j / m))
    return best


def point_in_time_join(events, features, ttl=None):
    if ttl is not None and ttl < 0:
        raise ValueError("ttl cannot be negative")
    by_key = {}
    for key, ts, value in features:
        by_key.setdefault(key, []).append((ts, value))
    stamps = {}
    for key, rows in by_key.items():
        rows.sort(key=lambda r: r[0])
        stamps[key] = [r[0] for r in rows]
    out = []
    for key, ts in events:
        if key not in by_key:
            out.append(None)
            continue
        idx = bisect_right(stamps[key], ts) - 1
        if idx < 0:
            out.append(None)
            continue
        f_ts, value = by_key[key][idx]
        if ttl is not None and f_ts < ts - ttl:
            out.append(None)
        else:
            out.append(value)
    return out


def past_rolling_mean(values, window):
    if window < 1:
        raise ValueError("window must be at least 1")
    out = []
    for i in range(len(values)):
        past = values[max(0, i - window):i]
        out.append(_mean(past) if past else None)
    return out


# ---------------------------------------------------------------------------
# Experiments (not part of the homework)
# ---------------------------------------------------------------------------
import hashlib
import json
import random
import time

T0 = time.time()


def mean(xs):
    xs = list(xs)
    return sum(xs) / len(xs)


def sd(xs):
    xs = list(xs)
    m = mean(xs)
    return math.sqrt(sum((v - m) ** 2 for v in xs) / len(xs))


def auc(scores, labels):
    order = sorted(range(len(scores)), key=lambda i: scores[i])
    ranks = [0.0] * len(scores)
    i = 0
    while i < len(order):
        j = i
        while j + 1 < len(order) and scores[order[j + 1]] == scores[order[i]]:
            j += 1
        for k in range(i, j + 1):
            ranks[order[k]] = (i + j) / 2 + 1
        i = j + 1
    pos = [r for r, y in zip(ranks, labels) if y == 1]
    n1, n0 = len(pos), len(labels) - len(pos)
    return (sum(pos) - n1 * (n1 + 1) / 2) / (n1 * n0)


def skew(xs):
    m, s = mean(xs), sd(xs)
    return mean(((v - m) / s) ** 3 for v in xs)


print("== 1. Missing data: three mechanisms")
rng = random.Random(1)
N = 20000
z = [rng.gauss(0, 1) for _ in range(N)]
x = [50 + 10 * (0.8 * zi + 0.6 * rng.gauss(0, 1)) for zi in z]
print("   true mean %.2f, true sd %.2f" % (mean(x), sd(x)))
masks = {
    "MCAR (30% at random)": [rng.random() < 0.3 for _ in range(N)],
    "MAR  (60% if z > 0, else 10%)": [rng.random() < (0.6 if zi > 0 else 0.1) for zi in z],
    "MNAR (60% if x > 50, else 10%)": [rng.random() < (0.6 if xi > 50 else 0.1) for xi in x],
}
for name, miss in masks.items():
    obs = [xi for xi, m in zip(x, miss) if not m]
    imp = Imputer("mean").fit([None if m else xi for xi, m in zip(x, miss)])
    filled, _ = imp.transform([None if m else xi for xi, m in zip(x, miss)])
    hi = [xi for xi, zi, m in zip(x, z, miss) if not m and zi > 0]
    lo = [xi for xi, zi, m in zip(x, z, miss) if not m and zi <= 0]
    grp = [(mean(hi) if zi > 0 else mean(lo)) if m else xi for xi, zi, m in zip(x, z, miss)]
    print("   %-32s missing %.3f | observed mean %.2f | mean-imputed mean %.2f, sd %.2f | z-group imputed mean %.2f"
          % (name, mean(1.0 if m else 0.0 for m in miss), mean(obs), mean(filled), sd(filled), mean(grp)))
rng = random.Random(2)
ys, ms = [], []
for _ in range(N):
    yv = 1 if rng.random() < 0.3 else 0
    ys.append(yv)
    ms.append(rng.random() < (0.2 if yv else 0.7))
print("   lab test missing: P(missing) %.3f, P(y=1 | missing) %.3f, P(y=1 | observed) %.3f"
      % (mean(1.0 if m else 0.0 for m in ms), mean(y for y, m in zip(ys, ms) if m), mean(y for y, m in zip(ys, ms) if not m)))

print("\n== 2. Fit on training data only")
rng = random.Random(3)
tr = [rng.gauss(0, 1) for _ in range(1000)]
te = [rng.gauss(1.5, 1) for _ in range(1000)]
sc_train = StandardScaler().fit(tr)
sc_all = StandardScaler().fit(tr + te)
print("   train mean %.3f sd %.3f; test mean %.3f sd %.3f" % (mean(tr), sd(tr), mean(te), sd(te)))
print("   scaler fitted on train: scaled test mean %.3f, sd %.3f" % (mean(sc_train.transform(te)), sd(sc_train.transform(te))))
print("   scaler fitted on train+test: scaled test mean %.3f, sd %.3f" % (mean(sc_all.transform(te)), sd(sc_all.transform(te))))
imp_t = Imputer("median").fit([None if i % 10 == 0 else v for i, v in enumerate(tr)])
print("   median fill from train %.3f; from train+test it would be %.3f" % (imp_t.fill_, Imputer("median").fit(tr + te).fill_))

print("\n== 3. Encoding categoricals")
cats500 = ["c%03d" % i for i in range(500)]
oh = OneHotEncoder().fit(cats500)
print("   one-hot of 500 categories: %d columns; an unseen category gives a row with sum %d" % (len(oh.categories_), sum(oh.transform(["new"])[0])))


def bucket(name, buckets):
    return int.from_bytes(hashlib.md5(name.encode()).digest()[:4], "big") % buckets


for b in (64, 256, 1024):
    loads = {}
    for cname in cats500:
        loads[bucket(cname, b)] = loads.get(bucket(cname, b), 0) + 1
    shared = sum(v for v in loads.values() if v > 1)
    print("   hash 500 categories into %4d buckets: %3d buckets used, largest bucket holds %d, %3d categories share a bucket"
          % (b, len(loads), max(loads.values()), shared))
d_raw = abs(23 - 0)
d_cyc = lambda h1, h2: math.hypot(math.sin(2 * math.pi * h1 / 24) - math.sin(2 * math.pi * h2 / 24),
                                  math.cos(2 * math.pi * h1 / 24) - math.cos(2 * math.pi * h2 / 24))
print("   hour 23 vs hour 0: raw distance %d, sin/cos distance %.4f; hour 0 vs 1: %.4f; hour 0 vs 12: %.4f"
      % (d_raw, d_cyc(23, 0), d_cyc(0, 1), d_cyc(0, 12)))

print("   -- smoothing with 10 pseudo-rows")
cats_s = ["few"] * 1 + ["some"] * 10 + ["many"] * 100 + ["rest"] * 889
y_s = [1] + [1] * 8 + [0] * 2 + [1] * 80 + [0] * 20 + [1] * 233 + [0] * 656
enc_s, prior_s = target_encoding_fit(cats_s, y_s, 10)
enc_0, _ = target_encoding_fit(cats_s, y_s, 0)
print("   prior %.4f" % prior_s)
for c_, n_ in (("few", 1), ("some", 10), ("many", 100)):
    print("   category %-4s n=%3d: raw mean %.3f, smoothed %.3f" % (c_, n_, enc_0[c_], enc_s[c_]))

print("   -- target-encoding leakage, labels independent of the category")
rng = random.Random(4)
n_rows, n_cat = 4000, 400
cat_all = ["k%d" % rng.randrange(n_cat) for _ in range(n_rows)]
y_all = [1 if rng.random() < 0.3 else 0 for _ in range(n_rows)]
c_tr, c_te, y_tr, y_te = cat_all[:2000], cat_all[2000:], y_all[:2000], y_all[2000:]
for smooth in (0, 10):
    enc, pr = target_encoding_fit(c_tr, y_tr, smooth)
    in_sample = target_encoding_apply(c_tr, enc, pr)
    oof = target_encoding_oof(c_tr, y_tr, 5, smooth)
    on_test = target_encoding_apply(c_te, enc, pr)
    print("   smooth %2d: AUC of the encoded feature  train in-sample %.3f | train out-of-fold %.3f | held-out test %.3f"
          % (smooth, auc(in_sample, y_tr), auc(oof, y_tr), auc(on_test, y_te)))
print("   -- leave-one-out encoding (the row's own target removed) still leaks")


def loo_encode(cats, ys):
    n_c, s_c = {}, {}
    for c_, t_ in zip(cats, ys):
        n_c[c_] = n_c.get(c_, 0) + 1
        s_c[c_] = s_c.get(c_, 0) + t_
    return [(s_c[c_] - t_) / (n_c[c_] - 1) if n_c[c_] > 1 else mean(ys) for c_, t_ in zip(cats, ys)]


one_level = ["same"] * len(y_tr)
print("   one constant level, 2000 rows: AUC of the feature, leave-one-out %.3f | 5-fold out-of-fold %.3f"
      % (auc(loo_encode(one_level, y_tr), y_tr), auc(target_encoding_oof(one_level, y_tr, 5, 0), y_tr)))
print("   400 levels, labels independent: AUC leave-one-out %.3f | 5-fold out-of-fold %.3f"
      % (auc(loo_encode(c_tr, y_tr), y_tr), auc(target_encoding_oof(c_tr, y_tr, 5, 0), y_tr)))
print("   -- same, but each category has its own true rate (0.10 to 0.50)")
rng = random.Random(5)
rate = {"k%d" % i: 0.10 + 0.40 * rng.random() for i in range(n_cat)}
y_all2 = [1 if rng.random() < rate[c_] else 0 for c_ in cat_all]
y_tr2, y_te2 = y_all2[:2000], y_all2[2000:]
for smooth in (0, 10):
    enc, pr = target_encoding_fit(c_tr, y_tr2, smooth)
    oof = target_encoding_oof(c_tr, y_tr2, 5, smooth)
    print("   smooth %2d: AUC  train in-sample %.3f | train out-of-fold %.3f | held-out test %.3f | best possible (true rates) %.3f"
          % (smooth, auc(target_encoding_apply(c_tr, enc, pr), y_tr2), auc(oof, y_tr2),
             auc(target_encoding_apply(c_te, enc, pr), y_te2), auc([rate[c_] for c_ in c_te], y_te2)))

print("\n== 4. Scaling, outliers and skew")
rng = random.Random(6)
ln = [math.exp(rng.gauss(0, 1)) for _ in range(5000)]
print("   lognormal(0,1) sample: mean %.2f, median %.2f, skewness %.2f; after log: skewness %.2f"
      % (mean(ln), sorted(ln)[2500], skew(ln), skew([math.log(v) for v in ln])))
clean = [rng.gauss(10, 2) for _ in range(99)]
dirty = clean + [1000.0]
zc = StandardScaler().fit(clean).transform(clean)
zd = StandardScaler().fit(dirty).transform(dirty)
q1, med, q3 = quantile_edges(dirty, 4)
zr = [(v - med) / (q3 - q1) for v in dirty]
print("   99 ordinary values (mean 10, sd 2): sd of the scaled values %.3f clean, %.3f after adding one value of 1000"
      % (sd(zc), sd(zd[:99])))
print("   with the outlier: standard scaler sd %.2f, outlier z %.2f; median/IQR scaling: sd of ordinary values %.3f, outlier %.1f"
      % (StandardScaler().fit(dirty).scale_, zd[-1], sd(zr[:99]), zr[-1]))

print("\n== 5. Feature crosses")
rng = random.Random(7)
x1 = [rng.gauss(0, 1) for _ in range(4000)]
x2 = [rng.gauss(0, 1) for _ in range(4000)]
yx = [(1 if a * b > 0 else 0) if rng.random() > 0.05 else (0 if a * b > 0 else 1) for a, b in zip(x1, x2)]


def sign_rule_accuracy(feature):
    pos = mean(1.0 if (f > 0) == (t == 1) else 0.0 for f, t in zip(feature, yx))
    return max(pos, 1 - pos)


print("   y = 1 when x1 * x2 > 0, 5%% of labels flipped. Best sign rule on x1: %.3f, on x2: %.3f, on the cross x1*x2: %.3f"
      % (sign_rule_accuracy(x1), sign_rule_accuracy(x2), sign_rule_accuracy([a * b for a, b in zip(x1, x2)])))

print("\n== 6. Point-in-time correctness")
feats = [("u1", 1, 3), ("u1", 5, 4), ("u1", 9, 10), ("u2", 2, 7)]
evs = [("u1", 5), ("u1", 8), ("u1", 0), ("u2", 1), ("u1", 100)]
print("   events %s -> %s" % (evs, point_in_time_join(evs, feats)))
print("   with ttl 3 -> %s" % point_in_time_join(evs, feats, ttl=3))
series = [3, 5, 4, 10]
print("   series %s: past-only rolling mean (window 3) %s; mean including the current value at the last step %.2f"
      % (series, past_rolling_mean(series, 3), mean(series[-3:] if len(series) >= 3 else series)))
rng = random.Random(8)
n_cust = 3000
churn, leaky, correct = [], [], []
for _ in range(n_cust):
    ch = 1 if rng.random() < 0.3 else 0
    p_before = 0.3 if ch else 0.4
    p_after = 0.0 if ch else 0.4
    before = sum(1 for _d in range(30) if rng.random() < p_before)
    after = sum(1 for _d in range(7) if rng.random() < p_after)
    churn.append(ch)
    correct.append(-before)
    leaky.append(-(before + after))
print("   churn prediction at time t, events counted in the 30 days before t: AUC %.3f; counting 7 days past t as well: AUC %.3f"
      % (auc(correct, churn), auc(leaky, churn)))

print("\n== 7. Training-serving skew")
rng = random.Random(9)
n_s = 20000
xv = [rng.gauss(100, 15) for _ in range(n_s)]
yv = [1 if v + rng.gauss(0, 5) < 85 else 0 for v in xv]
miss = [None if rng.random() < 0.1 else v for v in xv]
imp = Imputer("median").fit(miss)
offline, _ = imp.transform(miss)
served = [0.0 if v is None else v for v in miss]


def prec_rec(values):
    flag = [1 if v < 85 else 0 for v in values]
    tp = sum(1 for f, t in zip(flag, yv) if f and t)
    return tp / sum(flag), tp / sum(yv), sum(flag)


for name, vals in (("offline (median fill %.1f)" % imp.fill_, offline), ("served (fill 0)", served)):
    p_, r_, nf = prec_rec(vals)
    print("   %-26s flagged %5d, precision %.3f, recall %.3f" % (name, nf, p_, r_))

print("\n== 8. Drift")
e2, a2 = [0.5, 0.5], [0.3, 0.7]
print("   hand example: expected %s actual %s: PSI = %.4f" % (e2, a2, psi([50, 50], [30, 70])))
rng = random.Random(10)
ref = [rng.gauss(0, 1) for _ in range(50000)]
edges = quantile_edges(ref, 10)
ref_counts = bin_counts(ref, edges)
cases = [("no drift", 0.0, 1.0), ("mean +0.1", 0.1, 1.0), ("mean +0.5", 0.5, 1.0), ("sd x1.5, mean same", 0.0, 1.5), ("mean +0.5, sd x1.2", 0.5, 1.2)]
drifted = None
for name, mu, sg in cases:
    cur = [rng.gauss(mu, sg) for _ in range(10000)]
    drifted = cur
    print("   %-20s PSI %.4f   KS %.4f" % (name, psi(ref_counts, bin_counts(cur, edges)), ks_statistic(ref, cur)))
print("   -- PSI under no drift depends on the sample size (10 bins, 50,000 reference rows, 100 repeats)")
for n_a in (100, 1000, 10000):
    vals = []
    for _ in range(100):
        cur = [rng.gauss(0, 1) for _ in range(n_a)]
        vals.append(psi(ref_counts, bin_counts(cur, edges)))
    vals.sort()
    print("   n = %5d: mean PSI %.4f (derived guess 9 x (1/n + 1/50000) = %.4f), 95th percentile %.4f"
          % (n_a, mean(vals), 9 * (1 / n_a + 1 / 50000), vals[94]))
cur = drifted
print("   -- the last drifted sample above (mean +0.5, sd 1.2) with different bin counts")
for b in (5, 10, 20):
    ed = quantile_edges(ref, b)
    print("   %2d bins: PSI %.4f" % (b, psi(bin_counts(ref, ed), bin_counts(cur, ed))))
print("   -- a new category")
exp_c = [600, 300, 100, 0]
act_c = [500, 300, 100, 100]
for eps in (1e-4, 1e-6):
    print("   expected shares 0.6/0.3/0.1/0, actual 0.5/0.3/0.1/0.1, eps %g: PSI %.3f" % (eps, psi(exp_c, act_c, eps)))
big_n = 100000
r1 = [rng.gauss(0, 1) for _ in range(big_n)]
r2 = [rng.gauss(0.02, 1) for _ in range(big_n)]
ed = quantile_edges(r1, 10)
print("   -- a tiny shift (mean +0.02) with %d rows on each side: PSI %.5f, KS %.4f, 5%% KS critical value 1.358 x sqrt(2/n) = %.4f"
      % (big_n, psi(bin_counts(r1, ed), bin_counts(r2, ed)), ks_statistic(r1, r2), 1.358 * math.sqrt(2 / big_n)))
print("   -- concept drift: the inputs do not move, the rule does")
rng = random.Random(11)
xa = [rng.gauss(0, 1) for _ in range(20000)]
xb = [rng.gauss(0, 1) for _ in range(20000)]
ya = [1 if v > 0 else 0 for v in xa]
yb = [1 if v > 1 else 0 for v in xb]
edg = quantile_edges(xa, 10)
print("   PSI of the input %.4f; accuracy of the rule 'x > 0' before %.3f, after the label rule moved to 'x > 1': %.3f"
      % (psi(bin_counts(xa, edg), bin_counts(xb, edg)), mean(1.0 if (v > 0) == (t == 1) else 0.0 for v, t in zip(xa, ya)),
         mean(1.0 if (v > 0) == (t == 1) else 0.0 for v, t in zip(xb, yb))))

print("\n== 9. Label delay")
rng = random.Random(12)
n_l = 40000
delay = [rng.expovariate(1 / 20) for _ in range(n_l)]
is_pos = [rng.random() < 0.05 for _ in range(n_l)]
for age in (7, 14, 30, 60, 90):
    seen = sum(1 for d, p in zip(delay, is_pos) if p and d <= age)
    print("   cohort aged %2d days: positives labelled so far %.4f (true rate %.4f; share of positives labelled %.3f; theory 1 - exp(-age/20) = %.3f)"
          % (age, seen / n_l, mean(1.0 if p else 0.0 for p in is_pos), seen / sum(is_pos), 1 - math.exp(-age / 20)))

print("\n== 10. Retraining policies on a drifting concept")


def run_policy(policy, weeks=40, seed=13):
    rng = random.Random(seed)
    model_c = 0.0
    last_train = 0
    retrains = 0
    accs = []
    labelled_acc = []
    for t in range(weeks):
        c_t = 0.1 * t
        xs = [rng.gauss(0, 1) for _ in range(2000)]
        acc = mean(1.0 if (v > model_c) == (v > c_t) else 0.0 for v in xs)
        accs.append(acc)
        labelled_acc.append(acc)
        retrain = False
        if policy == "schedule 10 weeks" and t - last_train >= 10:
            retrain = True
        if policy == "trigger: accuracy < 0.95" and t >= 2 and labelled_acc[t - 2] < 0.95:
            retrain = True
        if retrain:
            model_c = 0.1 * max(t - 2, 0)
            last_train = t
            retrains += 1
    return mean(accs), min(accs), retrains


for pol in ("never", "schedule 10 weeks", "trigger: accuracy < 0.95"):
    m_, lo_, r_ = run_policy(pol)
    print("   %-26s mean accuracy %.3f, worst week %.3f, retrains %d" % (pol, m_, lo_, r_))

print("\n== 11. Versioning and reproducibility")
snap = {"rows": [[1, 0.5, "a"], [2, 0.7, "b"]], "schema": ["id", "x", "cat"]}
snap2 = {"rows": [[1, 0.5, "a"], [2, 0.7, "c"]], "schema": ["id", "x", "cat"]}
h = lambda o: hashlib.sha256(json.dumps(o, sort_keys=True).encode()).hexdigest()
print("   snapshot hash %s ... ; one changed cell: %s ... ; same snapshot again: %s ..." % (h(snap)[:12], h(snap2)[:12], h(dict(snap))[:12]))
rng_a, rng_b, rng_c = random.Random(0), random.Random(0), random.Random(1)
print("   same seed gives the same first draw: %s; a different seed does not: %s" % (rng_a.random() == rng_b.random(), rng_a.random() == rng_c.random()))
rng = random.Random(14)
flips = [1 if rng.random() < 0.10 else 0 for _ in range(20000)]
print("   label noise: with 10%% of labels flipped, a model that is always right is scored %.3f" % (1 - mean(flips)))

print("\ntotal %.1f s" % (time.time() - T0))

ML system design: framing, budgets, two-stage retrieval, serving, rollout and monitoring

ML systems and interviews

Show the code (228 lines)

Python

import math
from collections import OrderedDict


def percentile(values, p):
    if len(values) == 0:
        raise ValueError("percentile of an empty list")
    if not 0 < p <= 100:
        raise ValueError("p must satisfy 0 < p <= 100")
    s = sorted(values)
    rank = max(1, math.ceil(p / 100 * len(s) - 1e-9))
    return s[rank - 1]


def servers_needed(qps, latency_s, concurrency, target_util):
    if qps < 0 or latency_s < 0 or concurrency < 1 or not 0 < target_util <= 1:
        raise ValueError("bad capacity inputs")
    if qps == 0:
        return 0
    in_flight = qps * latency_s
    return max(1, math.ceil(in_flight / (concurrency * target_util) - 1e-9))


def path_latency(stages):
    total = 0.0
    for st in stages:
        group = st if isinstance(st, (list, tuple)) else [st]
        if any(g < 0 for g in group):
            raise ValueError("negative latency")
        total += max(group) if len(group) else 0.0
    return total


def cost_per_million_requests(servers, price_per_hour, qps):
    if qps <= 0 or servers < 0 or price_per_hour < 0:
        raise ValueError("bad cost inputs")
    return servers * price_per_hour / (qps * 3600) * 1_000_000


def recall_at_k(ranked, relevant, k):
    if k < 1:
        raise ValueError("k must be at least 1")
    rel = set(relevant)
    if not rel:
        return 0.0
    return len(set(ranked[:k]) & rel) / len(rel)


def ndcg_at_k(ranked, gains, k):
    if k < 1:
        raise ValueError("k must be at least 1")
    seen = set()
    dcg = 0.0
    for i, item in enumerate(ranked[:k]):
        if item in seen:
            continue
        seen.add(item)
        dcg += gains.get(item, 0) / math.log2(i + 2)
    ideal_gains = sorted(gains.values(), reverse=True)[:k]
    ideal = sum(g / math.log2(i + 2) for i, g in enumerate(ideal_gains))
    return dcg / ideal if ideal > 0 else 0.0


def two_stage(retrieved, scores, n_candidates, k):
    if n_candidates < 1 or k < 1:
        raise ValueError("n_candidates and k must be at least 1")
    cands = retrieved[:n_candidates]
    order = sorted(range(len(cands)), key=lambda i: (-scores[cands[i]], i))
    return [cands[i] for i in order[:k]]


def lru_hit_rate(requests, capacity):
    if capacity < 0:
        raise ValueError("capacity must not be negative")
    if len(requests) == 0 or capacity == 0:
        return 0.0
    cache = OrderedDict()
    hits = 0
    for key in requests:
        if key in cache:
            hits += 1
            cache.move_to_end(key)
        else:
            cache[key] = True
            if len(cache) > capacity:
                cache.popitem(last=False)
    return hits / len(requests)


def batch_stats(batch_size, fixed_ms, per_item_ms):
    if batch_size < 1 or fixed_ms < 0 or per_item_ms < 0:
        raise ValueError("bad batch inputs")
    latency = fixed_ms + per_item_ms * batch_size
    if latency <= 0:
        raise ValueError("latency must be positive")
    return latency, batch_size / latency * 1000


def best_batch_size(max_batch, fixed_ms, per_item_ms, latency_cap_ms):
    if max_batch < 1:
        raise ValueError("max_batch must be at least 1")
    best = 0
    for b in range(1, max_batch + 1):
        latency, _ = batch_stats(b, fixed_ms, per_item_ms)
        if latency <= latency_cap_ms + 1e-9:
            best = b
    return best


def timeout_fallback(latencies, timeout_ms, fallback_ms):
    if timeout_ms < 0 or fallback_ms < 0 or any(x < 0 for x in latencies):
        raise ValueError("negative latency")
    if len(latencies) == 0:
        return [], 0.0
    served, used = [], 0
    for x in latencies:
        if x <= timeout_ms:
            served.append(x)
        else:
            served.append(timeout_ms + fallback_ms)
            used += 1
    return served, used / len(latencies)


import math
import random
from statistics import NormalDist

print("== 1. Capacity: a feed for 5M daily users")
dau, sessions = 5_000_000, 4
per_day = dau * sessions
avg_qps = per_day / 86_400
peak_qps = avg_qps * 3
servers = servers_needed(peak_qps, 0.060, 8, 0.5)
print(f"requests per day {per_day:,}  average qps {avg_qps:.2f}  peak qps {peak_qps:.2f}")
print(f"in flight at peak {peak_qps * 0.060:.1f}  servers {servers}")
print(f"dollars per million requests at $0.40 per server-hour {cost_per_million_requests(servers, 0.40, avg_qps):.2f}")
print(f"daily server cost ${servers * 0.40 * 24:.2f}")
print(f"item embeddings, 200,000 x 64 floats of 4 bytes: {200_000 * 64 * 4 / 1e6:.1f} MB")
print(f"item embeddings, 100,000,000 x 128 floats of 4 bytes: {100_000_000 * 128 * 4 / 1e9:.1f} GB")
print(f"100M parameters: fp32 {100e6 * 4 / 1e6:.0f} MB, int8 {100e6 * 1 / 1e6:.0f} MB")

print("\n== 2. Latency: the mean hides the tail")
rng = random.Random(7)
lat = [rng.lognormvariate(math.log(40), 0.5) for _ in range(20_000)]
p50, p95, p99 = (percentile(lat, p) for p in (50, 95, 99))
print(f"mean {sum(lat) / len(lat):.1f} ms  p50 {p50:.1f}  p95 {p95:.1f}  p99 {p99:.1f}  max {max(lat):.1f}")
print(f"serial path 5 + 10 + 40 ms: {path_latency([5, 10, 40])}  with the two fetches in parallel: {path_latency([5, [10, 40]])}")
fan = 10
slow = sum(1 for _ in range(20_000) if max(rng.lognormvariate(math.log(40), 0.5) for _ in range(fan)) > p99)
print(f"fan-out {fan}: share of requests with at least one call above the single-call p99: {slow / 20_000:.4f} (formula {1 - 0.99 ** fan:.4f})")
nd = NormalDist()
q_est = nd.cdf((math.log(p99) - math.log(40)) / 0.5)
print(f"the estimated p99 {p99:.1f} ms is the true {q_est * 100:.2f}th percentile, so one call exceeds it with probability {1 - q_est:.5f}")
print(f"fan-out {fan} with that probability: {1 - q_est ** fan:.4f}")
served, rate = timeout_fallback(lat, 100.0, 5.0)
print(f"timeout 100 ms, fallback 5 ms: fallback rate {rate:.4f}  p99 served {percentile(served, 99):.1f}  max served {max(served):.1f}")

print("\n== 3. Batching: throughput against latency")
for b in (1, 8, 16, 64):
    l, t = batch_stats(b, 8, 0.5)
    print(f"batch {b:>2}: latency {l:5.1f} ms  throughput {t:7.1f} items/s")
bb = best_batch_size(256, 8, 0.5, 20)
print(f"largest batch within a 20 ms cap: {bb}  ({batch_stats(bb, 8, 0.5)[1]:.1f} items/s)")

print("\n== 4. Two stages: recall at the retriever, NDCG at the ranker")
N, USERS, REL = 20_000, 150, 20
sums = {}
ranker_all = []
retr_only = []
for u in range(USERS):
    r = random.Random(1000 + u)
    gain = {}
    for item in r.sample(range(N), REL):
        gain[item] = r.choice([1, 2, 3])
    cheap = [gain.get(i, 0) + r.gauss(0, 1.2) for i in range(N)]
    exact = {i: gain.get(i, 0) + r.gauss(0, 0.5) for i in range(N)}
    retrieved = sorted(range(N), key=lambda i: -cheap[i])
    retr_only.append(ndcg_at_k(retrieved, gain, 10))
    ranker_all.append(ndcg_at_k(sorted(range(N), key=lambda i: -exact[i]), gain, 10))
    for n in (50, 200, 500, 2000):
        final = two_stage(retrieved, exact, n, 10)
        a = sums.setdefault(n, [0.0, 0.0])
        a[0] += recall_at_k(retrieved, list(gain), n)
        a[1] += ndcg_at_k(final, gain, 10)
print(f"retriever alone, NDCG@10: {sum(retr_only) / USERS:.3f}")
for n, (rc, nd) in sums.items():
    print(f"candidates {n:>4}: recall@{n} {rc / USERS:.3f}  final NDCG@10 {nd / USERS:.3f}  ranker calls per request {n}")
print(f"ranker on all {N:,} items, NDCG@10: {sum(ranker_all) / USERS:.3f}  ranker calls per request {N}")

print("\n== 5. Cache: Zipf traffic and an LRU cache")
rng = random.Random(11)
keys = 10_000
w = [1 / (r + 1) for r in range(keys)]
reqs = rng.choices(range(keys), weights=w, k=200_000)
for cap in (10, 100, 1000):
    print(f"capacity {cap:>4} ({cap / keys:.1%} of keys): hit rate {lru_hit_rate(reqs, cap):.3f}")

print("\n== 6. Decisions from calibrated scores")
loss, friction = 80.0, 4.0
print(f"decline when p > friction / (friction + loss) = {friction / (friction + loss):.4f}")
print(f"expected value per impression at pCTR 0.02 and bid $1.50: ${0.02 * 1.50:.2f}; if pCTR is overstated 2x: ${0.04 * 1.50:.2f}")

print("\n== 7. A toy feedback loop")
CTR = [0.10] * 10
CTR[7] = 0.15
def run(seed, eps, rounds=3000):
    r = random.Random(seed)
    shows, clicks = [0] * 10, [0] * 10
    for _ in range(rounds):
        if r.random() < eps:
            i = r.randrange(10)
        else:
            est = [clicks[j] / shows[j] if shows[j] else 0.0 for j in range(10)]
            best = max(est)
            i = r.choice([j for j in range(10) if est[j] == best])
        shows[i] += 1
        clicks[i] += r.random() < CTR[i]
    return shows
for eps in (0.0, 0.1):
    top7 = never = 0
    share = 0.0
    for seed in range(100):
        s = run(seed, eps)
        top7 += s.index(max(s)) == 7
        share += max(s) / sum(s)
        never += sum(1 for x in s if x < 30)
    print(f"epsilon {eps}: item 7 most shown in {top7} of 100 runs, mean share of the most shown item {share / 100:.3f}, items with under 30 impressions per run {never / 100:.2f}")
Show the code (44 lines)

Text

== 1. Capacity: a feed for 5M daily users
requests per day 20,000,000  average qps 231.48  peak qps 694.44
in flight at peak 41.7  servers 11
dollars per million requests at $0.40 per server-hour 5.28
daily server cost $105.60
item embeddings, 200,000 x 64 floats of 4 bytes: 51.2 MB
item embeddings, 100,000,000 x 128 floats of 4 bytes: 51.2 GB
100M parameters: fp32 400 MB, int8 100 MB

== 2. Latency: the mean hides the tail
mean 45.2 ms  p50 40.1  p95 91.5  p99 126.2  max 277.5
serial path 5 + 10 + 40 ms: 55.0  with the two fetches in parallel: 45.0
fan-out 10: share of requests with at least one call above the single-call p99: 0.1030 (formula 0.0956)
the estimated p99 126.2 ms is the true 98.92th percentile, so one call exceeds it with probability 0.01077
fan-out 10 with that probability: 0.1027
timeout 100 ms, fallback 5 ms: fallback rate 0.0320  p99 served 105.0  max served 105.0

== 3. Batching: throughput against latency
batch  1: latency   8.5 ms  throughput   117.6 items/s
batch  8: latency  12.0 ms  throughput   666.7 items/s
batch 16: latency  16.0 ms  throughput  1000.0 items/s
batch 64: latency  40.0 ms  throughput  1600.0 items/s
largest batch within a 20 ms cap: 24  (1200.0 items/s)

== 4. Two stages: recall at the retriever, NDCG at the ranker
retriever alone, NDCG@10: 0.214
candidates   50: recall@50 0.165  final NDCG@10 0.472  ranker calls per request 50
candidates  200: recall@200 0.284  final NDCG@10 0.654  ranker calls per request 200
candidates  500: recall@500 0.395  final NDCG@10 0.772  ranker calls per request 500
candidates 2000: recall@2000 0.613  final NDCG@10 0.903  ranker calls per request 2000
ranker on all 20,000 items, NDCG@10: 0.944  ranker calls per request 20000

== 5. Cache: Zipf traffic and an LRU cache
capacity   10 (0.1% of keys): hit rate 0.131
capacity  100 (1.0% of keys): hit rate 0.391
capacity 1000 (10.0% of keys): hit rate 0.675

== 6. Decisions from calibrated scores
decline when p > friction / (friction + loss) = 0.0476
expected value per impression at pCTR 0.02 and bid $1.50: $0.03; if pCTR is overstated 2x: $0.06

== 7. A toy feedback loop
epsilon 0.0: item 7 most shown in 14 of 100 runs, mean share of the most shown item 0.998, items with under 30 impressions per run 9.00
epsilon 0.1: item 7 most shown in 55 of 100 runs, mean share of the most shown item 0.670, items with under 30 impressions per run 1.68

Training at scale: memory arithmetic, parallelism, mixed precision and scaling laws

ML systems and interviews

Show the code (341 lines)

Python

import math
import struct


def state_bytes_per_param(stage, dp, weight_bytes=2, grad_bytes=2, optimizer_bytes=12):
    if stage not in (0, 1, 2, 3):
        raise ValueError("stage must be 0, 1, 2 or 3")
    if not isinstance(dp, int) or isinstance(dp, bool) or dp < 1:
        raise ValueError("dp must be a whole number >= 1")
    if weight_bytes < 0 or grad_bytes < 0 or optimizer_bytes < 0:
        raise ValueError("byte counts must not be negative")
    w, g, o = float(weight_bytes), float(grad_bytes), float(optimizer_bytes)
    if stage == 0:
        return w + g + o
    if stage == 1:
        return w + g + o / dp
    if stage == 2:
        return w + (g + o) / dp
    return (w + g + o) / dp


def model_state_gb(params, dp, stage, weight_bytes=2, grad_bytes=2, optimizer_bytes=12):
    if params < 0:
        raise ValueError("params must not be negative")
    per = state_bytes_per_param(stage, dp, weight_bytes, grad_bytes, optimizer_bytes)
    return params * per / 1e9


def fits_on_gpu(params, dp, stage, gpu_gb, activation_gb=0.0, overhead_gb=0.0, **bytes_kw):
    if gpu_gb < 0 or activation_gb < 0 or overhead_gb < 0:
        raise ValueError("memory sizes must not be negative")
    total = model_state_gb(params, dp, stage, **bytes_kw) + activation_gb + overhead_gb
    return total <= gpu_gb


def scaled_lr(base_lr, base_batch, batch, step, warmup_steps):
    if base_lr <= 0 or base_batch <= 0 or batch <= 0:
        raise ValueError("base_lr, base_batch and batch must be positive")
    if step < 0 or warmup_steps < 0:
        raise ValueError("step and warmup_steps must not be negative")
    target = base_lr * (batch / base_batch)
    if warmup_steps == 0 or step >= warmup_steps:
        return target
    return base_lr + (target - base_lr) * (step / warmup_steps)


def mse_gradient(w, b, xs, ys):
    if len(xs) != len(ys) or len(xs) == 0:
        raise ValueError("xs and ys must have the same non-zero length")
    n = len(xs)
    dw = db = 0.0
    for x, y in zip(xs, ys):
        err = w * x + b - y
        dw += 2.0 * err * x
        db += 2.0 * err
    return dw / n, db / n


def accumulated_gradient(w, b, xs, ys, micro_size):
    if not isinstance(micro_size, int) or isinstance(micro_size, bool) or micro_size < 1:
        raise ValueError("micro_size must be a whole number >= 1")
    if len(xs) != len(ys) or len(xs) == 0:
        raise ValueError("xs and ys must have the same non-zero length")
    total_w = total_b = 0.0
    for start in range(0, len(xs), micro_size):
        cx = xs[start:start + micro_size]
        cy = ys[start:start + micro_size]
        gw, gb = mse_gradient(w, b, cx, cy)
        total_w += gw * len(cx)
        total_b += gb * len(cx)
    n = len(xs)
    return total_w / n, total_b / n


def micro_batch_variance_mean(values, micro_size):
    if len(values) == 0:
        raise ValueError("values must not be empty")
    if not isinstance(micro_size, int) or isinstance(micro_size, bool) or micro_size < 1:
        raise ValueError("micro_size must be a whole number >= 1")
    variances = []
    for start in range(0, len(values), micro_size):
        chunk = values[start:start + micro_size]
        m = sum(chunk) / len(chunk)
        variances.append(sum((v - m) ** 2 for v in chunk) / len(chunk))
    return sum(variances) / len(variances)


def to_fp16(x):
    try:
        return struct.unpack("<e", struct.pack("<e", x))[0]
    except OverflowError:
        return math.inf if x > 0 else -math.inf


def fp16_gradient(grad, scale):
    if scale <= 0:
        raise ValueError("scale must be positive")
    scaled = to_fp16(grad * scale)
    if math.isinf(scaled) or math.isnan(scaled):
        return scaled
    return scaled / scale


def next_loss_scale(scale, found_inf, good_steps, growth_factor=2.0, backoff_factor=0.5,
                    growth_interval=2000):
    if found_inf:
        return scale * backoff_factor, 0
    good_steps += 1
    if good_steps >= growth_interval:
        return scale * growth_factor, 0
    return scale, good_steps


def ring_allreduce_seconds(size_bytes, n, bandwidth, latency=0.0):
    if not isinstance(n, int) or isinstance(n, bool) or n < 1:
        raise ValueError("n must be a whole number >= 1")
    if bandwidth <= 0 or size_bytes < 0 or latency < 0:
        raise ValueError("bandwidth must be positive, size and latency not negative")
    if n == 1:
        return 0.0
    return 2.0 * (n - 1) / n * size_bytes / bandwidth + 2.0 * (n - 1) * latency


def central_allreduce_seconds(size_bytes, n, bandwidth):
    if not isinstance(n, int) or isinstance(n, bool) or n < 1:
        raise ValueError("n must be a whole number >= 1")
    if bandwidth <= 0 or size_bytes < 0:
        raise ValueError("bandwidth must be positive, size not negative")
    return 2.0 * (n - 1) * size_bytes / bandwidth


def bubble_fraction(stages, microbatches):
    for v in (stages, microbatches):
        if not isinstance(v, int) or isinstance(v, bool) or v < 1:
            raise ValueError("stages and microbatches must be whole numbers >= 1")
    return (stages - 1) / (microbatches + stages - 1)


def microbatches_for_bubble(stages, target):
    if not 0 < target < 1:
        raise ValueError("target must be between 0 and 1")
    if not isinstance(stages, int) or isinstance(stages, bool) or stages < 1:
        raise ValueError("stages must be a whole number >= 1")
    m = 1
    while (stages - 1) > target * (m + stages - 1) + 1e-12:
        m += 1
    return m


def activation_units(n_layers, k):
    if not isinstance(n_layers, int) or isinstance(n_layers, bool) or n_layers < 1:
        raise ValueError("n_layers must be a whole number >= 1")
    if not isinstance(k, int) or isinstance(k, bool) or not 1 <= k <= n_layers:
        raise ValueError("k must be a whole number between 1 and n_layers")
    return k + -(-n_layers // k)


def best_checkpoint_count(n_layers):
    best_k = 1
    best = activation_units(n_layers, 1)
    for k in range(2, n_layers + 1):
        u = activation_units(n_layers, k)
        if u < best:
            best, best_k = u, k
    return best_k


def recompute_overhead(forward=1.0, backward=2.0):
    if forward < 0 or backward < 0 or forward + backward <= 0:
        raise ValueError("costs must not be negative and must not both be zero")
    return forward / (forward + backward)


def loader_step_time(compute_s, load_s, workers):
    if not isinstance(workers, int) or isinstance(workers, bool) or workers < 1:
        raise ValueError("workers must be a whole number >= 1")
    if compute_s < 0 or load_s < 0:
        raise ValueError("times must not be negative")
    return max(compute_s, load_s / workers)


def min_workers(compute_s, load_s):
    if compute_s <= 0 or load_s < 0:
        raise ValueError("compute_s must be positive and load_s not negative")
    w = 1
    while load_s / w > compute_s + 1e-12:
        w += 1
    return w


def wasted_fraction(interval, write, mtbf):
    if interval <= 0 or write <= 0 or mtbf <= 0:
        raise ValueError("interval, write and mtbf must be positive")
    return write / interval + interval / (2.0 * mtbf)


def best_interval(write, mtbf):
    if write <= 0 or mtbf <= 0:
        raise ValueError("write and mtbf must be positive")
    return math.sqrt(2.0 * write * mtbf)


def training_flops(params, tokens):
    if params < 0 or tokens < 0:
        raise ValueError("params and tokens must not be negative")
    return 6.0 * params * tokens


def training_days(flops, gpus, peak_flops_per_gpu, utilisation):
    if not isinstance(gpus, int) or isinstance(gpus, bool) or gpus < 1:
        raise ValueError("gpus must be a whole number >= 1")
    if peak_flops_per_gpu <= 0 or not 0 < utilisation <= 1 or flops < 0:
        raise ValueError("bad peak, utilisation or flops")
    return flops / (gpus * peak_flops_per_gpu * utilisation) / 86400.0


def compute_optimal(flops, tokens_per_param=20.0):
    if flops < 0 or tokens_per_param <= 0:
        raise ValueError("flops must not be negative and tokens_per_param must be positive")
    n = math.sqrt(flops / (6.0 * tokens_per_param))
    return n, tokens_per_param * n


print("== 1. Memory: where the bytes go")
for name, p in (("1.5B", 1.5e9), ("7B", 7e9), ("70B", 70e9)):
    w = p * 2 / 1e9
    g = p * 2 / 1e9
    o = p * 12 / 1e9
    print(f"{name}: weights {w:.0f} GB, gradients {g:.0f} GB, Adam states and fp32 copy {o:.0f} GB, total {model_state_gb(p, 1, 0):.0f} GB")
print("bytes per parameter, mixed-precision Adam:", state_bytes_per_param(0, 1))
print("7B model state per device, 8 devices:")
for stage in (0, 1, 2, 3):
    print(f"  stage {stage}: {state_bytes_per_param(stage, 8):.2f} bytes per parameter, {model_state_gb(7e9, 8, stage):.1f} GB")
print("7.5B model on 64 devices:", [round(model_state_gb(7.5e9, 64, s), 1) for s in (0, 1, 2, 3)], "GB")
print("fits on an 80 GB device with 20 GB of activations and 4 GB overhead, 7B, 8 devices:",
      [fits_on_gpu(7e9, 8, s, 80, 20, 4) for s in (0, 1, 2, 3)])
print("fp32 weights and gradients plus Adam (4+4+8):", state_bytes_per_param(0, 1, 4, 4, 8), "bytes per parameter")

print("\n== 2. Batch size and learning rate")
base_lr, base_batch, batch, warm = 0.1, 256, 8192, 5000
print(f"k = {batch // base_batch}, target rate {scaled_lr(base_lr, base_batch, batch, warm, warm):.2f}")
for step in (0, 1000, 2500, 4999, 5000, 9000):
    print(f"  step {step:>5}: lr {scaled_lr(base_lr, base_batch, batch, step, warm):.4f}")
print("no warmup, step 0:", scaled_lr(base_lr, base_batch, batch, 0, 0))

print("\n== 3. Gradient accumulation")
xs = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]
ys = [1.2, 1.9, 3.1, 3.8, 5.3, 5.9, 7.2, 7.8, 9.1, 9.9]
full = mse_gradient(0.5, 0.0, xs, ys)
print(f"full batch of 10:        dw {full[0]:.6f}  db {full[1]:.6f}")
for micro in (1, 2, 5, 10):
    a = accumulated_gradient(0.5, 0.0, xs, ys, micro)
    print(f"micro-batches of {micro:>2}:     dw {a[0]:.6f}  db {a[1]:.6f}")
micro = 4
a = accumulated_gradient(0.5, 0.0, xs, ys, micro)
chunks = [(xs[i:i + micro], ys[i:i + micro]) for i in range(0, len(xs), micro)]
sizes = [len(cx) for cx, cy in chunks]
print(f"micro-batches of {micro} (sizes {sizes}): dw {a[0]:.6f}  db {a[1]:.6f}")
chunk_means = [mse_gradient(0.5, 0.0, cx, cy)[0] for cx, cy in chunks]
print(f"unweighted mean of {len(chunks)} chunk means: dw {sum(chunk_means) / len(chunks):.6f}")
print(f"sum of {len(chunks)} chunk means, no division: dw {sum(chunk_means):.6f}")
vals = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]
m = sum(vals) / len(vals)
fullvar = sum((v - m) ** 2 for v in vals) / len(vals)
print(f"variance of 8 values {fullvar:.4f}; mean of per-micro-batch variances: size 4 {micro_batch_variance_mean(vals, 4):.4f}, size 2 {micro_batch_variance_mean(vals, 2):.4f}, size 1 {micro_batch_variance_mean(vals, 1):.4f}")

print("\n== 4. Mixed precision")
print("half precision largest value:", to_fp16(65504.0), " 65520 rounds to:", to_fp16(65520.0))
print("1.0 + 0.0001 in half precision:", to_fp16(1.0 + 0.0001))
w16 = w_wide = 1.0
for _ in range(100):
    w16 = to_fp16(w16 + 0.0001)
    w_wide = w_wide + 0.0001
print(f"100 updates of 0.0001: half-precision weight {w16}, higher-precision master weight {w_wide:.4f}")
for grad in (1e-8, 3e-8, 1e-5):
    row = ", ".join(f"scale {s:>5}: {fp16_gradient(grad, s):.3e}" for s in (1, 1024, 65536))
    print(f"gradient {grad:.0e} -> {row}")
print("gradient 2.0 at scale 65536:", fp16_gradient(2.0, 65536), " at scale 8192:", fp16_gradient(2.0, 8192))
scale, good = 65536.0, 0
trace = []
for found_inf in (False, True, False, False, False, False, False, True, False):
    scale, good = next_loss_scale(scale, found_inf, good, growth_interval=3)
    trace.append(f"{'inf' if found_inf else 'ok '}->{scale:g}")
print("loss scale trace (growth interval 3):", " ".join(trace))

def to_bf16(x):
    bits = struct.unpack("<I", struct.pack("<f", x))[0]
    bits += 0x7FFF + ((bits >> 16) & 1)
    return struct.unpack("<f", struct.pack("<I", (bits & 0xFFFF0000) & 0xFFFFFFFF))[0]
print("bfloat16 (emulated): 1e-8 ->", f"{to_bf16(1e-8):.3e}", " 70000 ->", to_bf16(70000.0), " 1.0001 ->", to_bf16(1.0001))

print("\n== 5. Communication")
grad_bytes = 7e9 * 2
bw = 50e9
print(f"gradients of a 7B model in half precision: {grad_bytes / 1e9:.0f} GB, link {bw / 1e9:.0f} GB/s per device (assumed)")
for n in (2, 8, 64, 1024):
    print(f"  {n:>4} devices: ring {ring_allreduce_seconds(grad_bytes, n, bw):.3f} s, central {central_allreduce_seconds(grad_bytes, n, bw):.2f} s")
print(f"  1024 devices with 5 microseconds per step: ring {ring_allreduce_seconds(grad_bytes, 1024, bw, 5e-6):.4f} s")
print("  1 device:", ring_allreduce_seconds(grad_bytes, 1, bw))

print("\n== 6. Pipeline bubble")
for p in (4, 8):
    print(f"  stages {p}: " + ", ".join(f"m={m} bubble {bubble_fraction(p, m):.3f}" for m in (1, 4, 16, 32, 64)))
print("  microbatches for a 10% bubble:", {p: microbatches_for_bubble(p, 0.10) for p in (2, 4, 8, 16)})
print("  idealised bubble at m = 4p, p = 8:", round(bubble_fraction(8, 32), 3))
print("  bubble relative to ideal compute (p-1)/m, p=8, m=32:", round(7 / 32, 3))

print("\n== 7. Activation checkpointing")
for n in (16, 100, 1000):
    k = best_checkpoint_count(n)
    print(f"  {n:>4} layers: no checkpointing {n} units, best k {k} -> {activation_units(n, k)} units")
print(f"  extra compute with backward = 2 x forward: {recompute_overhead():.3f}; with backward = 1 x forward: {recompute_overhead(1, 1):.3f}")

print("\n== 8. Data loading")
for w in (1, 2, 3, 4, 8):
    st = loader_step_time(0.25, 0.9, w)
    print(f"  {w} workers: step {st:.3f} s, accelerator busy {0.25 / st:.0%}")
print("  fewest workers:", min_workers(0.25, 0.9))

print("\n== 9. Checkpoint interval")
write, mtbf = 3.0, 360.0
for interval in (5, 10, 30, 60, 120, 240):
    print(f"  every {interval:>3} min: wasted {wasted_fraction(interval, write, mtbf):.3f}")
bi = best_interval(write, mtbf)
print(f"  best interval {bi:.1f} min, wasted {wasted_fraction(bi, write, mtbf):.3f}")

print("\n== 10. Compute and scaling")
print(f"  7B params on 1T tokens: {training_flops(7e9, 1e12):.2e} FLOPs")
print(f"  on 1024 devices at 300 TFLOP/s peak and 40% utilisation: {training_days(training_flops(7e9, 1e12), 1024, 3e14, 0.4):.2f} days")
print(f"  on 256 devices: {training_days(training_flops(7e9, 1e12), 256, 3e14, 0.4):.2f} days")
c_chin = training_flops(70e9, 1.4e12)
c_goph = training_flops(280e9, 300e9)
c_paper = 5.76e23
print(f"  Chinchilla 70B x 1.4T tokens: {c_chin:.2e} FLOPs; Gopher 280B x 300B tokens: {c_goph:.2e} FLOPs")
print(f"  against the paper's 5.76e+23 for Gopher: 6ND is {c_goph / c_paper - 1:+.1%} for Gopher and {c_chin / c_paper - 1:+.1%} for Chinchilla")
n, d = compute_optimal(c_chin)
print(f"  compute_optimal({c_chin:.2e}): N {n:.3e}, D {d:.3e}, tokens per parameter {d / n:.0f}")
n2, d2 = compute_optimal(c_paper)
print(f"  at the paper's Gopher budget {c_paper:.2e}: N {n2:.3e}, D {d2:.3e}")
print(f"  tokens per parameter: Chinchilla {1.4e12 / 70e9:.0f}, Gopher {300e9 / 280e9:.2f}")
print(f"  inference of a 7B model, 2N per token: {2 * 7e9:.1e} FLOPs per token")
Show the code (95 lines)

Text

== 1. Memory: where the bytes go
1.5B: weights 3 GB, gradients 3 GB, Adam states and fp32 copy 18 GB, total 24 GB
7B: weights 14 GB, gradients 14 GB, Adam states and fp32 copy 84 GB, total 112 GB
70B: weights 140 GB, gradients 140 GB, Adam states and fp32 copy 840 GB, total 1120 GB
bytes per parameter, mixed-precision Adam: 16.0
7B model state per device, 8 devices:
  stage 0: 16.00 bytes per parameter, 112.0 GB
  stage 1: 5.50 bytes per parameter, 38.5 GB
  stage 2: 3.75 bytes per parameter, 26.2 GB
  stage 3: 2.00 bytes per parameter, 14.0 GB
7.5B model on 64 devices: [120.0, 31.4, 16.6, 1.9] GB
fits on an 80 GB device with 20 GB of activations and 4 GB overhead, 7B, 8 devices: [False, True, True, True]
fp32 weights and gradients plus Adam (4+4+8): 16.0 bytes per parameter

== 2. Batch size and learning rate
k = 32, target rate 3.20
  step     0: lr 0.1000
  step  1000: lr 0.7200
  step  2500: lr 1.6500
  step  4999: lr 3.1994
  step  5000: lr 3.2000
  step  9000: lr 3.2000
no warmup, step 0: 3.2

== 3. Gradient accumulation
full batch of 10:        dw -28.885000  db -8.290000
micro-batches of  1:     dw -28.885000  db -8.290000
micro-batches of  2:     dw -28.885000  db -8.290000
micro-batches of  5:     dw -28.885000  db -8.290000
micro-batches of 10:     dw -28.885000  db -8.290000
micro-batches of 4 (sizes [4, 4, 2]): dw -28.885000  db -8.290000
unweighted mean of 3 chunk means: dw -35.375000
sum of 3 chunk means, no division: dw -106.125000
variance of 8 values 5.2500; mean of per-micro-batch variances: size 4 1.2500, size 2 0.2500, size 1 0.0000

== 4. Mixed precision
half precision largest value: 65504.0  65520 rounds to: inf
1.0 + 0.0001 in half precision: 1.0
100 updates of 0.0001: half-precision weight 1.0, higher-precision master weight 1.0100
gradient 1e-08 -> scale     1: 0.000e+00, scale  1024: 1.001e-08, scale 65536: 9.997e-09
gradient 3e-08 -> scale     1: 5.960e-08, scale  1024: 2.998e-08, scale 65536: 3.001e-08
gradient 1e-05 -> scale     1: 1.001e-05, scale  1024: 9.999e-06, scale 65536: 9.999e-06
gradient 2.0 at scale 65536: inf  at scale 8192: 2.0
loss scale trace (growth interval 3): ok ->65536 inf->32768 ok ->32768 ok ->32768 ok ->65536 ok ->65536 ok ->65536 inf->32768 ok ->32768
bfloat16 (emulated): 1e-8 -> 1.001e-08  70000 -> 70144.0  1.0001 -> 1.0

== 5. Communication
gradients of a 7B model in half precision: 14 GB, link 50 GB/s per device (assumed)
     2 devices: ring 0.280 s, central 0.56 s
     8 devices: ring 0.490 s, central 3.92 s
    64 devices: ring 0.551 s, central 35.28 s
  1024 devices: ring 0.559 s, central 572.88 s
  1024 devices with 5 microseconds per step: ring 0.5697 s
  1 device: 0.0

== 6. Pipeline bubble
  stages 4: m=1 bubble 0.750, m=4 bubble 0.429, m=16 bubble 0.158, m=32 bubble 0.086, m=64 bubble 0.045
  stages 8: m=1 bubble 0.875, m=4 bubble 0.636, m=16 bubble 0.304, m=32 bubble 0.179, m=64 bubble 0.099
  microbatches for a 10% bubble: {2: 9, 4: 27, 8: 63, 16: 135}
  idealised bubble at m = 4p, p = 8: 0.179
  bubble relative to ideal compute (p-1)/m, p=8, m=32: 0.219

== 7. Activation checkpointing
    16 layers: no checkpointing 16 units, best k 4 -> 8 units
   100 layers: no checkpointing 100 units, best k 10 -> 20 units
  1000 layers: no checkpointing 1000 units, best k 28 -> 64 units
  extra compute with backward = 2 x forward: 0.333; with backward = 1 x forward: 0.500

== 8. Data loading
  1 workers: step 0.900 s, accelerator busy 28%
  2 workers: step 0.450 s, accelerator busy 56%
  3 workers: step 0.300 s, accelerator busy 83%
  4 workers: step 0.250 s, accelerator busy 100%
  8 workers: step 0.250 s, accelerator busy 100%
  fewest workers: 4

== 9. Checkpoint interval
  every   5 min: wasted 0.607
  every  10 min: wasted 0.314
  every  30 min: wasted 0.142
  every  60 min: wasted 0.133
  every 120 min: wasted 0.192
  every 240 min: wasted 0.346
  best interval 46.5 min, wasted 0.129

== 10. Compute and scaling
  7B params on 1T tokens: 4.20e+22 FLOPs
  on 1024 devices at 300 TFLOP/s peak and 40% utilisation: 3.96 days
  on 256 devices: 15.82 days
  Chinchilla 70B x 1.4T tokens: 5.88e+23 FLOPs; Gopher 280B x 300B tokens: 5.04e+23 FLOPs
  against the paper's 5.76e+23 for Gopher: 6ND is -12.5% for Gopher and +2.1% for Chinchilla
  compute_optimal(5.88e+23): N 7.000e+10, D 1.400e+12, tokens per parameter 20
  at the paper's Gopher budget 5.76e+23: N 6.928e+10, D 1.386e+12
  tokens per parameter: Chinchilla 20, Gopher 1.07
  inference of a 7B model, 2N per token: 1.4e+10 FLOPs per token

The ML interview playbook: structure, answer method, debugging procedures, estimates and project defence

ML systems and interviews

Show the code (263 lines)

Python

import math


def confusion_counts(y_true, y_pred):
    if len(y_true) != len(y_pred):
        raise ValueError('length mismatch')
    tp = fp = fn = tn = 0
    for t, p in zip(y_true, y_pred):
        if t not in (0, 1) or p not in (0, 1):
            raise ValueError('labels must be 0 or 1')
        if p == 1 and t == 1:
            tp += 1
        elif p == 1:
            fp += 1
        elif t == 1:
            fn += 1
        else:
            tn += 1
    return (tp, fp, fn, tn)


def precision_recall_f1(y_true, y_pred):
    tp, fp, fn, _ = confusion_counts(y_true, y_pred)
    precision = tp / (tp + fp) if tp + fp else 0.0
    recall = tp / (tp + fn) if tp + fn else 0.0
    f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
    return (precision, recall, f1)


def majority_baseline_accuracy(y):
    if len(y) == 0:
        raise ValueError('empty labels')
    counts = {}
    for v in y:
        counts[v] = counts.get(v, 0) + 1
    return max(counts.values()) / len(y)


def auc_from_scores(y_true, scores):
    if len(y_true) != len(scores):
        raise ValueError('length mismatch')
    if any((t not in (0, 1) for t in y_true)):
        raise ValueError('labels must be 0 or 1')
    pos = [s for t, s in zip(y_true, scores) if t == 1]
    neg = [s for t, s in zip(y_true, scores) if t == 0]
    if not pos or not neg:
        raise ValueError('need both classes')
    wins = 0.0
    for a in pos:
        for b in neg:
            if a > b:
                wins += 1.0
            elif a == b:
                wins += 0.5
    return wins / (len(pos) * len(neg))


def kfold_indices(n, k):
    if k < 2 or k > n:
        raise ValueError('need 2 <= k <= n')
    base, extra = divmod(n, k)
    out = []
    start = 0
    for i in range(k):
        size = base + 1 if i < extra else base
        val = list(range(start, start + size))
        train = list(range(0, start)) + list(range(start + size, n))
        out.append((train, val))
        start += size
    return out


def forward_chain_splits(n, n_splits):
    if n_splits < 1:
        raise ValueError('n_splits must be at least 1')
    test_size = n // (n_splits + 1)
    if test_size < 1:
        raise ValueError('too few rows')
    out = []
    for i in range(n_splits):
        start = n - (n_splits - i) * test_size
        out.append((list(range(0, start)), list(range(start, start + test_size))))
    return out


def leak_fraction(train_ids, val_ids):
    if len(val_ids) == 0:
        return 0.0
    seen = set(train_ids)
    return sum((1 for v in val_ids if v in seen)) / len(val_ids)


def diagnose_curves(train_err, val_err, target_err, gap_tol):
    if len(train_err) == 0 or len(train_err) != len(val_err):
        raise ValueError('need two curves of the same non-zero length')
    tr, va = (train_err[-1], val_err[-1])
    bias = tr > target_err
    var = va - tr > gap_tol
    if bias and var:
        return 'high-bias-and-variance'
    if bias:
        return 'high-bias'
    if var:
        return 'high-variance'
    return 'ok'


def first_step(s):
    if s.get('loss_nan'):
        return 'check-data-and-lr'
    if s.get('loss_flat'):
        tiny = s.get('overfits_tiny_batch')
        if tiny is None:
            return 'overfit-tiny-batch'
        return 'tune-optimiser' if tiny else 'fix-pipeline-bug'
    if s.get('leakage_suspected') or s.get('suspiciously_good'):
        return 'audit-leakage'
    if s.get('offline_online_gap'):
        return 'check-experiment-then-features'
    for key in ('train_err', 'val_err', 'target_err', 'gap_tol'):
        if key not in s:
            raise ValueError('missing ' + key)
    verdict = diagnose_curves([s['train_err']], [s['val_err']], s['target_err'], s['gap_tol'])
    return {'high-bias': 'fix-bias', 'high-variance': 'fix-variance', 'high-bias-and-variance': 'fix-bias-first', 'ok': 'error-analysis'}[verdict]


def ppv_from_rates(prevalence, sensitivity, fpr):
    for v in (prevalence, sensitivity, fpr):
        if not 0 <= v <= 1:
            raise ValueError('rates must be in [0, 1]')
    tp = prevalence * sensitivity
    fp = (1 - prevalence) * fpr
    return tp / (tp + fp) if tp + fp > 0 else 0.0


def wilson_interval(successes, n, z=1.96):
    if n < 1 or successes < 0 or successes > n:
        raise ValueError('bad counts')
    p = successes / n
    denom = 1 + z * z / n
    centre = (p + z * z / (2 * n)) / denom
    half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom
    return (max(0.0, centre - half), min(1.0, centre + half))


def mlp_params(sizes):
    if len(sizes) < 2 or any((s < 1 for s in sizes)):
        raise ValueError('need at least two positive sizes')
    return sum((a * b + b for a, b in zip(sizes[:-1], sizes[1:])))


def mlp_forward_flops(sizes, batch):
    if len(sizes) < 2 or any((s < 1 for s in sizes)) or batch < 1:
        raise ValueError('bad sizes or batch')
    return sum((2 * batch * a * b for a, b in zip(sizes[:-1], sizes[1:])))

import random

print("== 1. Base rates: why the first number needs a denominator")
people, prevalence, sens, fpr = 10_000, 0.01, 0.99, 0.05
sick = round(people * prevalence)
tp_n = round(sick * sens)
fp_n = round((people - sick) * fpr)
print(f"of {people:,} people {sick} are sick and the test finds {tp_n}; of {people - sick:,} healthy people it flags {fp_n}")
print(f"P(sick | positive) = {tp_n} / {tp_n + fp_n} = {tp_n / (tp_n + fp_n):.4f}  (ppv_from_rates {ppv_from_rates(prevalence, sens, fpr):.4f})")
print(f"alerts: per 100,000 payments {100000 * 0.001 * 0.8:.0f} real and {100000 * 0.999 * 0.03:.0f} false, real share {ppv_from_rates(0.001, 0.8, 0.03):.4f}")
y = [1] * 100 + [0] * 9_900
never = [0] * 10_000
tp, fp, fn, tn = confusion_counts(y, never)
print(f"always-legit model: accuracy {(tp + tn) / len(y):.4f}  precision, recall, f1 {precision_recall_f1(y, never)}  baseline {majority_baseline_accuracy(y):.4f}")
model = [1] * 60 + [0] * 40 + [1] * 40 + [0] * 9_860
tp, fp, fn, tn = confusion_counts(y, model)
print(f"a real model: tp {tp} fp {fp} fn {fn} tn {tn}  accuracy {(tp + tn) / len(y):.4f}  precision {precision_recall_f1(y, model)[0]:.2f}  recall {precision_recall_f1(y, model)[1]:.2f}  f1 {precision_recall_f1(y, model)[2]:.2f}")

print("\n== 2. How sure are you of a number?")
for k, n in ((182, 200), (176, 200), (1820, 2000), (1760, 2000)):
    lo, hi = wilson_interval(k, n)
    print(f"{k}/{n} = {k / n:.3f}  95% Wilson interval [{lo:.3f}, {hi:.3f}]  width {hi - lo:.3f}")


def two_prop_z(p1, n1, p2, n2):
    pooled = (p1 * n1 + p2 * n2) / (n1 + n2)
    return (p1 - p2) / math.sqrt(pooled * (1 - pooled) * (1 / n1 + 1 / n2))

print(f"difference test, 0.91 against 0.88 with 200 items each: z = {two_prop_z(0.91, 200, 0.88, 200):.2f}")
print(f"difference test with 2000 items each: z = {two_prop_z(0.91, 2000, 0.88, 2000):.2f}")
n_sig = next(n for n in range(2, 100_000) if two_prop_z(0.91, n, 0.88, n) > 1.96)
print(f"smallest items per model for z above 1.96 at these accuracies: {n_sig}")

print("\n== 3. Too good to be true: three leak checks and what each catches")
rng = random.Random(5)
n = 400
labels = [rng.randint(0, 1) for _ in range(n)]
honest = [0.8 * t + rng.gauss(0, 1) for t in labels]
proxy = [t + rng.gauss(0, 0.05) for t in labels]
shuffled_labels = labels[:]
rng.shuffle(shuffled_labels)
print(f"honest feature AUC {auc_from_scores(labels, honest):.3f}")
print(f"proxy feature (written after the outcome) AUC {auc_from_scores(labels, proxy):.3f}")
print(f"chance baseline, honest feature against shuffled labels AUC {auc_from_scores(shuffled_labels, honest):.3f}")
print(f"proxy feature against shuffled labels AUC {auc_from_scores(shuffled_labels, proxy):.3f}  (a proxy does not survive the shuffle)")


def target_encode(cats, ys, fit_rows, apply_rows):
    total, count = {}, {}
    for i in fit_rows:
        total[cats[i]] = total.get(cats[i], 0) + ys[i]
        count[cats[i]] = count.get(cats[i], 0) + 1
    prior = sum(ys[i] for i in fit_rows) / len(fit_rows)
    return [total[cats[i]] / count[cats[i]] if cats[i] in count else prior for i in apply_rows]

r2 = random.Random(9)
cats = [r2.randrange(100) for _ in range(n)]
noise_labels = [r2.randint(0, 1) for _ in range(n)]
rows = list(range(n))
leaky_te = target_encode(cats, noise_labels, rows, rows)
print(f"pure-noise category, target-encoded on all rows: AUC {auc_from_scores(noise_labels, leaky_te):.3f}")
shuf2 = noise_labels[:]
r2.shuffle(shuf2)
leaky_te_shuf = target_encode(cats, shuf2, rows, rows)
print(f"same encoding with shuffled labels: AUC {auc_from_scores(shuf2, leaky_te_shuf):.3f}  (label-using preprocessing survives the shuffle)")
oof = [0.0] * n
for tr, va in kfold_indices(n, 5):
    for i, v in zip(va, target_encode(cats, noise_labels, tr, va)):
        oof[i] = v
print(f"same category, encoded out of fold: AUC {auc_from_scores(noise_labels, oof):.3f}")
patients = [i // 4 for i in range(n)]
rows_val = set(rng.sample(range(n), 80))
tr_ids = [patients[i] for i in range(n) if i not in rows_val]
va_ids = [patients[i] for i in range(n) if i in rows_val]
print(f"random row split: {leak_fraction(tr_ids, va_ids):.3f} of validation rows have a patient who is also in training")
val_patients = set(rng.sample(range(100), 20))
tr_ids = [p for p in patients if p not in val_patients]
va_ids = [p for p in patients if p in val_patients]
print(f"split by patient: {leak_fraction(tr_ids, va_ids):.3f}")

print("\n== 4. Split generators")
print("kfold n=10 k=3 validation folds:", [v for _, v in kfold_indices(10, 3)])
for tr, te in forward_chain_splits(12, 3):
    print(f"forward chain n=12: train rows 0..{tr[-1]} test rows {te[0]}..{te[-1]}")

print("\n== 5. Debugging as a decision procedure")
print("learning-curve check:", diagnose_curves([0.30, 0.12, 0.04, 0.02], [0.40, 0.33, 0.28, 0.25], 0.05, 0.05))
cases = [
    ("loss is NaN after 50 steps", {"loss_nan": True}),
    ("loss flat, tiny batch not tried", {"loss_flat": True}),
    ("loss flat, tiny batch cannot overfit", {"loss_flat": True, "overfits_tiny_batch": False}),
    ("loss flat, tiny batch overfits", {"loss_flat": True, "overfits_tiny_batch": True}),
    ("validation AUC 0.99 on a hard task", {"suspiciously_good": True}),
    ("offline win, A/B flat", {"offline_online_gap": True}),
    ("train 2%, validation 25%", {"train_err": 0.02, "val_err": 0.25, "target_err": 0.05, "gap_tol": 0.05}),
    ("train 20%, validation 22%", {"train_err": 0.20, "val_err": 0.22, "target_err": 0.05, "gap_tol": 0.05}),
    ("train 20%, validation 45%", {"train_err": 0.20, "val_err": 0.45, "target_err": 0.05, "gap_tol": 0.05}),
    ("train 3%, validation 6%", {"train_err": 0.03, "val_err": 0.06, "target_err": 0.05, "gap_tol": 0.05}),
]
for name, s in cases:
    print(f"{name:<40} -> {first_step(s)}")

print("\n== 6. Estimation")
sizes = [784, 256, 128, 10]
print(f"parameters of {sizes}: {mlp_params(sizes):,}  fp32 {mlp_params(sizes) * 4 / 1e6:.2f} MB")
print(f"forward FLOPs per example {mlp_forward_flops(sizes, 1):,}  batch of 64 {mlp_forward_flops(sizes, 64):,}")
print(f"at an assumed sustained 10 GFLOP/s a batch of 64 takes {mlp_forward_flops(sizes, 64) / 10e9 * 1000:.1f} ms")
Show the code (50 lines)

Text

== 1. Base rates: why the first number needs a denominator
of 10,000 people 100 are sick and the test finds 99; of 9,900 healthy people it flags 495
P(sick | positive) = 99 / 594 = 0.1667  (ppv_from_rates 0.1667)
alerts: per 100,000 payments 80 real and 2997 false, real share 0.0260
always-legit model: accuracy 0.9900  precision, recall, f1 (0.0, 0.0, 0.0)  baseline 0.9900
a real model: tp 60 fp 40 fn 40 tn 9860  accuracy 0.9920  precision 0.60  recall 0.60  f1 0.60

== 2. How sure are you of a number?
182/200 = 0.910  95% Wilson interval [0.862, 0.942]  width 0.080
176/200 = 0.880  95% Wilson interval [0.828, 0.918]  width 0.090
1820/2000 = 0.910  95% Wilson interval [0.897, 0.922]  width 0.025
1760/2000 = 0.880  95% Wilson interval [0.865, 0.894]  width 0.028
difference test, 0.91 against 0.88 with 200 items each: z = 0.98
difference test with 2000 items each: z = 3.09
smallest items per model for z above 1.96 at these accuracies: 803

== 3. Too good to be true: three leak checks and what each catches
honest feature AUC 0.718
proxy feature (written after the outcome) AUC 1.000
chance baseline, honest feature against shuffled labels AUC 0.503
proxy feature against shuffled labels AUC 0.469  (a proxy does not survive the shuffle)
pure-noise category, target-encoded on all rows: AUC 0.758
same encoding with shuffled labels: AUC 0.784  (label-using preprocessing survives the shuffle)
same category, encoded out of fold: AUC 0.443
random row split: 0.950 of validation rows have a patient who is also in training
split by patient: 0.000

== 4. Split generators
kfold n=10 k=3 validation folds: [[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]
forward chain n=12: train rows 0..2 test rows 3..5
forward chain n=12: train rows 0..5 test rows 6..8
forward chain n=12: train rows 0..8 test rows 9..11

== 5. Debugging as a decision procedure
learning-curve check: high-variance
loss is NaN after 50 steps               -> check-data-and-lr
loss flat, tiny batch not tried          -> overfit-tiny-batch
loss flat, tiny batch cannot overfit     -> fix-pipeline-bug
loss flat, tiny batch overfits           -> tune-optimiser
validation AUC 0.99 on a hard task       -> audit-leakage
offline win, A/B flat                    -> check-experiment-then-features
train 2%, validation 25%                 -> fix-variance
train 20%, validation 22%                -> fix-bias
train 20%, validation 45%                -> fix-bias-first
train 3%, validation 6%                  -> error-analysis

== 6. Estimation
parameters of [784, 256, 128, 10]: 235,146  fp32 0.94 MB
forward FLOPs per example 469,504  batch of 64 30,048,256
at an assumed sustained 10 GFLOP/s a batch of 64 takes 3.0 ms