20. Calibration

Why this layer exists

A harness acts on probabilities. Hermes, before a flagged shell command runs, asks a small model whether the reader should approve it; chapter 21 replaces that question with a decision model, whose answer is the probability that the call is harmful. Something has to turn that number into an action, and the obvious rule, a threshold, is only as good as the number.

A gate turns a probability into an action by comparing it with costs. Asking the reader about a call that was harmless costs cFPc_{FP} (a false positive: an interruption and a delay); letting a harmful call run unasked costs cFNc_{FN} (a false negative). If pp is the probability that the call is harmful, asking has expected cost (1−p)cFP(1 - p)\,c_{FP}, since the ask was wasted exactly when the call was harmless, and not asking has expected cost pcFNp\,c_{FN}. Asking is the cheaper action when

(1−p)cFP<pcFN⇔cFP<p(cFP+cFN)⇔p>cFPcFP+cFN=t∗. (1 - p)\,c_{FP} < p\,c_{FN} \;\Leftrightarrow\; c_{FP} < p\,(c_{FP} + c_{FN}) \;\Leftrightarrow\; p > \frac{c_{FP}}{c_{FP} + c_{FN}} = t^* .

If a missed harmful call costs 99 times as much as a needless prompt, t∗=1/100t^* = 1/100: ask whenever the chance of harm exceeds one in a hundred. The derivation took pp to be the probability of harm. A model whose 0.01 means “harmful one time in ten” makes the gate ask far too rarely, and nothing in the gate can tell. The property the derivation needs is calibration: among all the answers that say pp, the statement is true a fraction pp of the time. A model can rank calls perfectly and still be miscalibrated, and then every threshold derived from costs is wrong.

Chapter 21’s decision models consume all of it: their heads train on a proper score, carry a fitted temperature, and report their calibration with this chapter’s estimators.

Mechanism

Proper scoring rules

A model that answers with probabilities is trained by charging it a number for each answer, and it is judged by the average of such numbers on held-out data. Which charges reward honesty? Let a forecast pp, shape (K,)(K,), be a distribution over KK outcomes, non-negative and summing to 1, and let y∈{0,…,K−1}y \in \{0, \ldots, K-1\} be the outcome that happens. A scoring rule S(p,y)S(p, y) is the charge; here every rule is written as a loss, so lower is better. If the outcome is drawn from a distribution qq, also of shape (K,)(K,), the expected charge for reporting pp is

S¯(p,q)=Ey∼q[S(p,y)]=∑k=0K−1qkS(p,k). \bar S(p, q) = \mathbb{E}_{y \sim q}\big[S(p, y)\big] = \sum_{k=0}^{K-1} q_k\, S(p, k) .

SS is proper if S¯(p,q)≥S¯(q,q)\bar S(p, q) \ge \bar S(q, q) for every pp and every qq: reporting the distribution the outcome is really drawn from is never beaten. It is strictly proper if, in addition, equality holds only at p=qp = q: every other report is beaten. A forecaster who believes qq and wants to minimise its expected charge reports qq under a strictly proper rule, and under no other report does as well; there is nothing to gain from shading. Training is the same argument with gradient descent as the forecaster. A model trained to minimise the average of SS over outcomes drawn from qq is pushed toward p=qp = q, and the gates need exactly that number, since the threshold t∗t^* of “Why this layer exists” was derived for the probability itself. So the training loss and the evaluation scores must both be proper. Four rules follow, each proved strictly proper, then one that is not.

The log score, S(p,y)=−logpyS(p, y) = -\log p_y, chapter 4’s surprise of the outcome under the forecast. Its expectation is chapter 4’s cross-entropy from qq to pp, which splits into two parts by adding and subtracting ∑kqklogqk\sum_k q_k \log q_k:

S¯(p,q)=−∑kqklogpk=−∑kqklogqk+∑kqklogqkpk=H(q)+KL(q∥p). \bar S(p, q) = -\sum_k q_k \log p_k = -\sum_k q_k \log q_k + \sum_k q_k \log \frac{q_k}{p_k} = H(q) + \mathrm{KL}(q \,\Vert\, p) .

H(q)H(q) does not depend on the report. Gibbs’ inequality (chapter 4) says KL(q∥p)≥0\mathrm{KL}(q \Vert p) \ge 0, with equality only at p=qp = q. So S¯(p,q)≥H(q)=S¯(q,q)\bar S(p, q) \ge H(q) = \bar S(q, q), with equality only at p=qp = q: strictly proper. The least expected charge is the entropy of the outcome, the uncertainty no forecast can remove. The log score is unbounded: a forecast that gives 0 to an outcome with qk>0q_k > 0 has expected charge +∞+\infty, which is why chapter 21’s heads work in log space, where a probability too small for float64 still has a finite logarithm, and why log_loss returns inf for a zero probability instead of raising.

The Brier score, S(p,y)=∑k(pk−[y=k])2S(p, y) = \sum_k (p_k - [y = k])^2, the squared distance between the forecast and the one-hot vector of the outcome, between 0 and 2. By linearity of expectation, S¯(p,q)=∑kE[(pk−[y=k])2]\bar S(p, q) = \sum_k \mathbb{E}\big[(p_k - [y = k])^2\big]. Expand one term:

(pk−[y=k])2=pk2−2pk[y=k]+[y=k]2. (p_k - [y = k])^2 = p_k^2 - 2 p_k [y = k] + [y = k]^2 .

An indicator is 0 or 1, so [y=k]2=[y=k][y = k]^2 = [y = k], and its expectation is the probability of its event, E[y=k]=qk\mathbb{E}[y = k] = q_k. So

E[(pk−[y=k])2]=pk2−2pkqk+qk=(pk−qk)2+qk(1−qk), \mathbb{E}\big[(p_k - [y = k])^2\big] = p_k^2 - 2 p_k q_k + q_k = (p_k - q_k)^2 + q_k (1 - q_k),

where the last step adds and subtracts qk2q_k^2: pk2−2pkqk+qk2p_k^2 - 2p_k q_k + q_k^2 is (pk−qk)2(p_k - q_k)^2, and qk−qk2=qk(1−qk)q_k - q_k^2 = q_k(1 - q_k) is what is left. Summing over kk,

S¯(p,q)=∑k(pk−qk)2+∑kqk(1−qk). \bar S(p, q) = \sum_k (p_k - q_k)^2 + \sum_k q_k (1 - q_k) .

The second sum is fixed by qq; the first is a sum of squares, zero only when every pk=qkp_k = q_k. Strictly proper. The expected Brier score is the squared distance from the report to the truth plus a floor set by the truth. Unlike the log score it is bounded: a confident miss costs at most 2.

The spherical score rewards py/∥p∥2p_y / \lVert p \rVert_2, the probability of the outcome divided by the forecast’s Euclidean length; as a loss, S(p,y)=−py/∥p∥2S(p, y) = -p_y / \lVert p \rVert_2, between −1-1 and 0. The expected reward is

∑kqkpk∥p∥=q⋅p∥p∥. \sum_k q_k \frac{p_k}{\lVert p \rVert} = \frac{q \cdot p}{\lVert p \rVert} .

Cauchy–Schwarz bounds it, and the bound’s proof also gives its equality case. For nonzero vectors pp and qq, the squared length of the difference of their unit vectors is

∥p∥p∥−q∥q∥∥2=1−2q⋅p∥q∥∥p∥+1≥0, \left\lVert \frac{p}{\lVert p \rVert} - \frac{q}{\lVert q \rVert} \right\rVert^2 = 1 - 2\, \frac{q \cdot p}{\lVert q \rVert \lVert p \rVert} + 1 \;\ge\; 0,

so q⋅p≤∥q∥∥p∥q \cdot p \le \lVert q \rVert \lVert p \rVert, with equality only when the two unit vectors coincide, that is when p=λqp = \lambda q for some λ>0\lambda > 0. The expected reward is therefore at most ∥q∥\lVert q \rVert, and p=qp = q attains it: q⋅q/∥q∥=∥q∥q \cdot q / \lVert q \rVert = \lVert q \rVert. Any maximiser has p=λqp = \lambda q, and both sum to 1, so 1=∑kpk=λ∑kqk=λ1 = \sum_k p_k = \lambda \sum_k q_k = \lambda, and p=qp = q. Strictly proper. The division by ∥p∥\lVert p \rVert is what makes it so: a forecast spread thin has a small length (the uniform forecast has length 1/K1/\sqrt{K}), and dividing by it keeps a hedged report from being charged as if it had simply missed.

The ranked probability score. A score question’s levels are ordered, and the log and Brier scores are blind to the order. With the truth at level 2 of four, the forecasts A=(0.1,0.6,0.2,0.1)A = (0.1, 0.6, 0.2, 0.1) and B=(0.6,0.1,0.2,0.1)B = (0.6, 0.1, 0.2, 0.1) both give the outcome 0.2 and spread the rest over the same numbers, so both have log score 1.6094 and Brier score 1.02 (talos). Yet AA puts its bulk one level from the truth and BB two. With Fk=∑j≤kpjF_k = \sum_{j \le k} p_j the forecast’s cumulative distribution, the ranked probability score is

RPS(p,y)=∑k=0K−2(Fk−[y≤k])2, \mathrm{RPS}(p, y) = \sum_{k=0}^{K-2} \big(F_k - [y \le k]\big)^2 ,

where the term k=K−1k = K-1 is left out because FK−1=1=[y≤K−1]F_{K-1} = 1 = [y \le K-1] always. Each term is a one-term Brier score for the binary event Y≤kY \le k, forecast with probability FkF_k. Under qq that event has probability Qk=∑j≤kqjQ_k = \sum_{j \le k} q_j, and the Brier expansion above, with the event Y≤kY \le k in place of y=ky = k, gives each term’s expectation:

E[(Fk−[Y≤k])2]=Fk2−2FkQk+Qk=(Fk−Qk)2+Qk(1−Qk). \mathbb{E}\big[(F_k - [Y \le k])^2\big] = F_k^2 - 2 F_k Q_k + Q_k = (F_k - Q_k)^2 + Q_k (1 - Q_k) .

Summing, RPS‾(p,q)=∑k=0K−2(Fk−Qk)2+∑k=0K−2Qk(1−Qk)\overline{\mathrm{RPS}}(p, q) = \sum_{k=0}^{K-2} (F_k - Q_k)^2 + \sum_{k=0}^{K-2} Q_k (1 - Q_k), least exactly when Fk=QkF_k = Q_k for every k≤K−2k \le K-2. The cumulative values determine the forecast, pk=Fk−Fk−1p_k = F_k - F_{k-1} with F−1=0F_{-1} = 0 and FK−1=1F_{K-1} = 1, so F=QF = Q means p=qp = q. Strictly proper. For the two forecasts above, FA=(0.1,0.7,0.9)F^A = (0.1, 0.7, 0.9) and FB=(0.6,0.7,0.9)F^B = (0.6, 0.7, 0.9) against the steps (0,0,1)(0, 0, 1) give RPS=0.51\mathrm{RPS} = 0.51 for AA and 0.860.86 for BB (talos). The reason is visible in a forecast that puts all its mass on one level jj: then Fk=[j≤k]F_k = [j \le k], which differs from [y≤k][y \le k] exactly for the kk from min(j,y)\min(j, y) to max(j,y)−1\max(j, y) - 1, so RPS=∣j−y∣\mathrm{RPS} = |j - y|. On point forecasts the RPS is the absolute error in levels, the loss whose best single answer is the median (chapter 21, “Typed questions in one pass”, proves it), and on spread forecasts it charges mass by how far it sits from the outcome.

A rule that is not proper. The linear score charges minus the probability given to what happened, S(p,y)=−pyS(p, y) = -p_y, which sounds as reasonable as any. Its expectation is −q⋅p-q \cdot p, a linear function of pp. Let mm be a most likely outcome, qm=maxkqkq_m = \max_k q_k. Then

−q⋅p=−∑kqkpk≥−qm∑kpk=−qm, -q \cdot p = -\sum_k q_k p_k \;\ge\; -q_m \sum_k p_k = -q_m ,

with equality at p=emp = e_m, all the mass on mm. The honest report scores −∑kqk2-\sum_k q_k^2, and ∑kqk2≤qm∑kqk=qm\sum_k q_k^2 \le q_m \sum_k q_k = q_m, with equality only when every qk>0q_k > 0 equals qmq_m. So unless qq is uniform over the outcomes it allows, reporting certainty on the mode strictly beats reporting qq. A model trained on the linear score learns to be as overconfident as it can, and its probabilities say which outcome it favours and nothing about how likely that outcome is.

Sums of proper rules. If S1S_1 is strictly proper, S2S_2 proper and λ>0\lambda > 0, then S=S1+λS2S = S_1 + \lambda S_2 is strictly proper: S¯(p,q)−S¯(q,q)=[S¯1(p,q)−S¯1(q,q)]+λ[S¯2(p,q)−S¯2(q,q)]\bar S(p, q) - \bar S(q, q) = \big[\bar S_1(p, q) - \bar S_1(q, q)\big] + \lambda \big[\bar S_2(p, q) - \bar S_2(q, q)\big], a sum of a term that is positive for p≠qp \ne q and one that is never negative. The controlled experiment below rewards the log score plus 0.5 times the spherical score, the weights of proper_reward in Laya (at commit 6d942c9), an open rebuild of the interface of TypeSafe AI’s Jev (chapter 21). Laya’s README describes its training as reinforcement learning against strictly proper scoring rules: RLCD, Reinforcement Learning for Calibrated Decisions, the method TypeSafe AI names for Jev. This argument makes the unfloored sum strictly proper; Laya’s own version floors the log term, which breaks properness for probabilities below about 10−410^{-4} (exercise (c)).

Why cross-entropy training seeks calibration

Properness is about one distribution. Training faces one per input: a state xx has a true conditional distribution q(⋅∣x)q(\cdot \mid x) over the answers, shape (K,)(K,), and the model gives its own, p(⋅∣x)p(\cdot \mid x), computed from parameters ϕ\phi. The same letters as the last section: qq the truth, pp the report. Over the population of inputs, the expected log loss is

R(ϕ)=ExEy∼q(⋅∣x)[−logp(y∣x)]=Ex[H(q(⋅∣x))+KL(q(⋅∣x)∥p(⋅∣x))], R(\phi) = \mathbb{E}_{x}\, \mathbb{E}_{y \sim q(\cdot \mid x)}\big[-\log p(y \mid x)\big] = \mathbb{E}_{x}\Big[ H\big(q(\cdot \mid x)\big) + \mathrm{KL}\big(q(\cdot \mid x) \,\Vert\, p(\cdot \mid x)\big) \Big],

the log score’s decomposition applied inside the outer expectation, one xx at a time. The entropy term does not depend on ϕ\phi, and each KL term is at least 0, with equality only where p(⋅∣x)=q(⋅∣x)p(\cdot \mid x) = q(\cdot \mid x). So if some ϕ\phi reproduces the true conditional for every input, it minimises RR, and every minimiser reproduces it, except on a set of inputs of probability 0.

A model that reproduces the truth is calibrated. Let y^(x)\hat y(x) be its top answer and c(x)=maxkp(k∣x)c(x) = \max_k p(k \mid x) its confidence. The event c(X)=γc(X) = \gamma is decided by XX alone, so the probability of being right on it can be computed by first conditioning on XX (the tower property of conditional expectation) and then using p=qp = q:

P(Y=y^(X)∣c(X)=γ)=E[q(y^(X)∣X)∣c(X)=γ], P\big(Y = \hat y(X) \mid c(X) = \gamma\big) = \mathbb{E}\Big[ q\big(\hat y(X) \mid X\big) \,\Big|\, c(X) = \gamma \Big] ,

because given XX, the chance that YY equals the fixed answer y^(X)\hat y(X) is q(y^(X)∣X)q(\hat y(X) \mid X). With p=qp = q, and then the definition of cc as the probability of the top answer, the right-hand side is

E[p(y^(X)∣X)∣c(X)=γ]=E[c(X)∣c(X)=γ]=γ. \mathbb{E}\Big[ p\big(\hat y(X) \mid X\big) \,\Big|\, c(X) = \gamma \Big] = \mathbb{E}\big[ c(X) \mid c(X) = \gamma \big] = \gamma .

The same argument works for any probability the model reports and the event it is about: among the yes-or-no answers that say p=γp = \gamma, the statement is true a fraction γ\gamma of the time.

Chapter 21’s heads cannot reproduce the truth. They are linear or bilinear maps from a frozen embedding, fitted to a few thousand items, and their family almost certainly does not contain q(⋅∣x)q(\cdot \mid x). What survives this misspecification is calibration in the large, from the stationarity conditions of the parameters that shift the logits. The gradient of a softmax’s mean log loss in its logits is G=(Q−Y)/NG = (Q - Y)/N, shape (N,K)(N, K) (chapter 13’s distillation gradient at T=1T = 1; fit_ce below uses it, and chapter 21 derives it for its choice head), so the gradient in a per-option bias bb is the column sums of GG, and here bb is not penalised. At a stationary point of the training loss that gradient is zero, so for every option kk

1N∑n=1NQnk=1N∑n=1NYnk: \frac{1}{N} \sum_{n=1}^{N} Q_{nk} = \frac{1}{N} \sum_{n=1}^{N} Y_{nk} :

on the training data, the average probability the model gives each option equals the option’s average target. A logistic model’s bias gives the same identity for one probability: ∂L/∂b=∑n(σ(zn)−yn)/N=0\partial L / \partial b = \sum_n (\sigma(z_n) - y_n)/N = 0 makes the mean predicted probability equal the mean label. The temperature, fitted below, adds one more condition of this kind. These are statements about averages over a whole set. A model can meet them and be wrong in every bin, overconfident on half the items and underconfident on the other half, and they hold on the data the model was fitted to, where a model that has memorised some of its items is more confident than it will be on new ones. Both gaps are why calibration is measured, and the temperature fitted, on held-out data.

Measuring calibration

A forecaster is calibrated if, among its answers that say γ\gamma, the statement is true a fraction γ\gamma of the time. For a choice this is usually checked on the top answer: with confidence c=maxkpkc = \max_k p_k and top answer y^\hat y, calibrated means P(Y=y^∣c=γ)=γP(Y = \hat y \mid c = \gamma) = \gamma for every γ\gamma. That is top-label calibration, and it checks only the largest probability of each answer. The gates read more than the top answer: chapter 47 thresholds a yes/no probability pp, and chapter 42 thresholds at_least[k] for the level the reader’s user model names ("2", soon, by default). Chapter 28 alone acts on the top route, and it records the whole distribution beside it. The machinery below applies to any one probability and the 0/1 outcome of its event: the functions take a vector conf of probabilities and a vector correct of outcomes, and top_label is one way to make those two vectors from a matrix of answers. For a noul, chapter 21’s word for a statement that is true or false, conf is pp and correct the gold label.

With finite data the condition cannot be checked at each γ\gamma, since no two confidences are equal. So the items are grouped into BB bins by confidence. For bin bb, holding nbn_b of the NN items, let confb\mathrm{conf}_b be its mean confidence and accb\mathrm{acc}_b the fraction of its items whose event happened. A reliability diagram plots each bin as the point (confb,accb)(\mathrm{conf}_b, \mathrm{acc}_b); a calibrated forecaster’s points lie near the diagonal. The expected calibration error summarises the diagram as the average distance from the diagonal, weighted by the bins’ sizes:

ECE=∑b=1BnbN∣accb−confb∣. \mathrm{ECE} = \sum_{b=1}^{B} \frac{n_b}{N}\, \big|\mathrm{acc}_b - \mathrm{conf}_b\big| .

Two ways of drawing the bins are in use. Equal width cuts [0,1][0, 1] into BB intervals of width 1/B1/B; Guo, Pleiss, Sun and Weinberger’s 2017 study of neural-network calibration, whose recommended remedy is the temperature scaling below, reports it with B=15B = 15. Equal mass sorts the items by confidence and cuts them into BB runs of (nearly) equal count. Confidences are not spread evenly over [0,1][0, 1]: a four-option top label is never below 1/4, and a good model’s confidences pile up near 1, so equal-width bins leave some bins empty and average a crowded bin over whatever it holds. Equal-mass bins give every bin the same amount of data, and chapter 21’s weights file records the equal-mass version (ece_adaptive).

The binning bias. Even a perfectly calibrated forecaster has a positive ECE on finite data. Take one bin, holding items i=1,…,nbi = 1, \ldots, n_b with confidences cic_i and outcomes oi∈{0,1}o_i \in \{0, 1\}. Calibrated means that, given the confidences, each oio_i is a Bernoulli draw with probability cic_i, independently. Then

Xb=accb−confb=1nb∑i=1nb(oi−ci) X_b = \mathrm{acc}_b - \mathrm{conf}_b = \frac{1}{n_b} \sum_{i=1}^{n_b} (o_i - c_i)

has mean 0, and, since independent terms’ variances add and Var(oi)=ci(1−ci)\mathrm{Var}(o_i) = c_i (1 - c_i),

Var(Xb)=1nb2∑ici(1−ci)=vbnb,vb=1nb∑ici(1−ci). \mathrm{Var}(X_b) = \frac{1}{n_b^2} \sum_i c_i (1 - c_i) = \frac{v_b}{n_b}, \qquad v_b = \frac{1}{n_b} \sum_i c_i (1 - c_i) .

vbv_b is at most 1/4. Write c¯=confb\bar c = \mathrm{conf}_b for the bin’s mean confidence: vb=c¯−1nb∑ici2v_b = \bar c - \frac{1}{n_b} \sum_i c_i^2, and the mean of the squares is at least the square of the mean (their difference is the confidences’ variance within the bin, which is not negative), so vb≤c¯−c¯2=c¯(1−c¯)≤1/4v_b \le \bar c - \bar c^2 = \bar c (1 - \bar c) \le 1/4, the last because c¯(1−c¯)\bar c (1 - \bar c) is largest at c¯=1/2\bar c = 1/2. A variable with mean 0 is not 0, and its absolute value has a positive mean. Two estimates of that mean:

  • For any distribution, (E∣X∣)2≤E[X2](\mathbb{E}|X|)^2 \le \mathbb{E}[X^2], because the difference is Var(∣X∣)≥0\mathrm{Var}(|X|) \ge 0. So E∣Xb∣≤vb/nb≤1/(2nb)\mathbb{E}|X_b| \le \sqrt{v_b / n_b} \le 1/(2\sqrt{n_b}), for every nbn_b.
  • For a bin of a few dozen items or more, XbX_b is a mean of many independent terms and nearly normal (the central limit theorem). For X∼N(0,s2)X \sim \mathcal{N}(0, s^2), by symmetry and ∫0∞xe−x2/2s2dx=s2\int_0^\infty x\, e^{-x^2/2s^2}\, dx = s^2,

E∣X∣=2∫0∞xe−x2/2s2s2πdx=2s2s2π=s2/π≈0.798s. \mathbb{E}|X| = 2 \int_0^\infty x\, \frac{e^{-x^2/2s^2}}{s\sqrt{2\pi}}\, dx = \frac{2 s^2}{s \sqrt{2\pi}} = s \sqrt{2/\pi} \approx 0.798\, s .

Summing the bins with their weights, and using the normal approximation and vb≤1/4v_b \le 1/4,

E[ECE]=∑bnbNE∣Xb∣≲∑bnbN2π12nb=2π12N∑bnb. \mathbb{E}[\mathrm{ECE}] = \sum_b \frac{n_b}{N}\, \mathbb{E}|X_b| \lesssim \sum_b \frac{n_b}{N} \sqrt{\frac{2}{\pi}}\, \frac{1}{2\sqrt{n_b}} = \sqrt{\frac{2}{\pi}}\, \frac{1}{2N} \sum_b \sqrt{n_b} .

With equal-mass bins, nb=N/Bn_b = N/B and ∑bnb=BN/B=BN\sum_b \sqrt{n_b} = B \sqrt{N/B} = \sqrt{BN}, so

E[ECE]≲2πB4N. \mathbb{E}[\mathrm{ECE}] \lesssim \sqrt{\frac{2}{\pi}}\, \sqrt{\frac{B}{4N}} .

For any other binning with B′B' non-empty bins, Cauchy–Schwarz gives ∑bnb=∑b1⋅nb≤B′∑bnb=B′N\sum_b \sqrt{n_b} = \sum_b 1 \cdot \sqrt{n_b} \le \sqrt{B'} \sqrt{\sum_b n_b} = \sqrt{B' N}, with equality only for equal counts: equal mass is the worst case of this bound, and equal-width bins, with some empty and the rest unequal, sit lower. The floor falls like 1/N1/\sqrt{N} and grows like B\sqrt{B}. More bins resolve the diagram more finely and raise the noise in every bin.

The oracle ECE measures the floor directly. calibration_lab.py draws labels from known probabilities, a random linear softmax over 16 Gaussian features and four classes, and scores the truth itself, whose calibration error is zero by construction: everything its ECE reports is noise. Beside it, an overconfident copy, the same logits doubled, whose error is real. The table is below, in “Scores, ECE and temperature”. The truth’s equal-mass ECE falls from 0.1363 at N=100N = 100 to 0.0077 at N=30,000N = 30{,}000, a factor of 17.7 for a factor of 300 in NN, against 300=17.3\sqrt{300} = 17.3, and stays under the bound, which assumed the worst variance, 1/4. The bound can be tightened with this truth’s own variance. The bins’ terms are vb/nb\sqrt{v_b/n_b} with nb=N/Bn_b = N/B, so the sum is 2/π1/nb1B∑bvb\sqrt{2/\pi}\,\sqrt{1/n_b}\,\frac{1}{B}\sum_b \sqrt{v_b}, and by Jensen’s inequality for the concave square root, 1B∑bvb≤1B∑bvb\frac{1}{B}\sum_b \sqrt{v_b} \le \sqrt{\frac{1}{B}\sum_b v_b}, where 1B∑bvb\frac{1}{B}\sum_b v_b is exactly the sample’s mean c(1−c)c(1 - c), since the bins hold equal numbers of items. This truth’s mean c(1−c)c(1 - c) is 0.2096 (200,000 items, talos), which shrinks the bound by 4×0.2096=0.916\sqrt{4 \times 0.2096} = 0.916, to 0.0258 at N=3,000N = 3{,}000. The table’s 0.0271 is above it, and that is sampling noise: it is a mean of 20 draws, and with a per-draw standard deviation of about 0.005 (measured over 400 draws) the mean has a standard error of about 0.0011. Over 400 draws of 3,000 items the mean is 0.0251 with a standard error of 0.0003 (talos), under the bound, which bounds the expectation. The equal-width column sits below the equal-mass one, as the Cauchy–Schwarz step leads one to expect: with four classes the confidence never falls below 1/4, so at least the first three of fifteen equal-width bins are always empty. The overconfident copy stays near 0.16 from N=1,000N = 1{,}000 on, because its error does not shrink with data, but at N=100N = 100 it scores 0.2041 where the truth scores 0.1363: at that size the floor is most of the number.

The debiased estimator. Squares separate the floor from the error cleanly. For any random variable, E[X2]=(EX)2+Var(X)\mathbb{E}[X^2] = (\mathbb{E} X)^2 + \mathrm{Var}(X). With X=accb−confbX = \mathrm{acc}_b - \mathrm{conf}_b and the confidences fixed,

E[(accb−confb)2]=(E[accb]−confb)2+Var(accb): \mathbb{E}\big[(\mathrm{acc}_b - \mathrm{conf}_b)^2\big] = \big(\mathbb{E}[\mathrm{acc}_b] - \mathrm{conf}_b\big)^2 + \mathrm{Var}(\mathrm{acc}_b) :

the bin’s true squared error plus the noise. The noise can be estimated from the bin itself. Suppose the bin’s nn outcomes are independent draws with one probability μ\mu, and write a¯=accb\bar a = \mathrm{acc}_b for their mean. Then E[a¯]=μ\mathbb{E}[\bar a] = \mu and Var(a¯)=μ(1−μ)/n\mathrm{Var}(\bar a) = \mu (1 - \mu)/n, so

E[a¯(1−a¯)]=E[a¯]−E[a¯2]=μ−(μ(1−μ)n+μ2), \mathbb{E}[\bar a (1 - \bar a)] = \mathbb{E}[\bar a] - \mathbb{E}[\bar a^2] = \mu - \Big(\frac{\mu (1 - \mu)}{n} + \mu^2\Big),

using E[a¯2]=Var(a¯)+(Ea¯)2\mathbb{E}[\bar a^2] = \mathrm{Var}(\bar a) + (\mathbb{E} \bar a)^2, and collecting terms,

μ−μ2−μ(1−μ)n=μ(1−μ)(1−1n)=μ(1−μ)n−1n. \mu - \mu^2 - \frac{\mu (1 - \mu)}{n} = \mu (1 - \mu)\Big(1 - \frac{1}{n}\Big) = \mu (1 - \mu)\, \frac{n - 1}{n} .

Dividing by n−1n - 1,

E[a¯(1−a¯)n−1]=μ(1−μ)n=Var(a¯): \mathbb{E}\Big[\frac{\bar a (1 - \bar a)}{n - 1}\Big] = \frac{\mu (1 - \mu)}{n} = \mathrm{Var}(\bar a) :

an unbiased estimate of the noise term. Subtracting it in every bin estimates the squared calibration error without the floor,

CE^2=max(0,∑bnbN[(accb−confb)2−accb(1−accb)nb−1]), \hat{\mathrm{CE}}_2 = \sqrt{\max\Big(0,\; \sum_b \frac{n_b}{N} \Big[ (\mathrm{acc}_b - \mathrm{conf}_b)^2 - \frac{\mathrm{acc}_b (1 - \mathrm{acc}_b)}{n_b - 1} \Big] \Big)} ,

where the sum can come out negative by chance, when a bin’s estimated noise exceeds its squared gap, hence the max\max. This is the debiased estimator Kumar, Liang and Ma analyse in “Verified Uncertainty Calibration” (2019), which they trace to the meteorological literature. Three cautions. It measures an ℓ2\ell_2 error, the root of a weighted mean square, so its numbers are not on the scale of the ℓ1\ell_1 ECEs beside it in the lab’s table. It assumed one μ\mu per bin; if the true probabilities in a bin have mean μ¯\bar\mu and variance w2w^2, then Var(a¯)=(μ¯(1−μ¯)−w2)/n\mathrm{Var}(\bar a) = (\bar\mu (1 - \bar\mu) - w^2)/n, and repeating the computation above gives E[a¯(1−a¯)/(n−1)]=Var(a¯)+w2/(n−1)\mathbb{E}[\bar a (1 - \bar a)/(n - 1)] = \mathrm{Var}(\bar a) + w^2/(n - 1): it subtracts slightly too much, by an amount that is small when the bins are narrow. And the root of a maximum with 0 turns noise of mean about 0 into a positive number on average, so the truth’s debiased value is not 0 either: 0.0290 at N=100N = 100 in the lab. The root of the plain weighted mean square, the same quantity with nothing subtracted, is 0.1598 for the truth at N=100N = 100 against a debiased 0.0280, and 0.0103 against 0.0032 at N=30,000N = 30{,}000 (20 draws each, talos; a different set of draws from the lab’s).

Proper scores need no bins. The average log loss and Brier score over held-out items estimate their expectations with an ordinary sampling error and no binning choice at all, so they are the primary numbers of every calibration report in this chapter and the next; the ECEs come after them. They do not measure calibration alone: by the decompositions above, a lower expected score means a report nearer the truth, which rewards both being calibrated and telling items apart.

Discrimination is separate. A noul forecaster that answers every state with the base rate of its statement, p=πp = \pi every time, is calibrated: among its answers that say π\pi, which are all of them, the statement is true a fraction π\pi of the time. It is also useless, because it ranks no state above another. On talos, 10,000 items with π=0.3\pi = 0.3 give it an equal-width ECE of 0.0036, the gap between the sample’s frequency, 0.3036, and 0.3, since all its confidences fall in one bin, and an AUROC of exactly 0.5. Its equal-mass ECE is 0.0127: equal-mass bins cut its tied confidences into fifteen arbitrary groups of items, and each group’s accuracy differs from 0.3 by sampling noise, the floor derived above. The AUROC measures ranking: the probability that a randomly chosen positive item scores higher than a randomly chosen negative one, ties counting a half. auroc computes it from ranks. Sort all NN scores, give each its rank from 1, with tied scores sharing the average of their ranks, and let R+R_+ be the sum of the positives’ ranks. A positive’s rank is 1 plus the number of items below it plus half the number of others tied with it. Split those items into positives and negatives. The positives’ ranks among the positives alone are 1,…,n+1, \ldots, n_+, with ties averaged, summing to n+(n++1)/2n_+(n_+ + 1)/2; what remains is, for each positive, the number of negatives below it plus half the negatives tied with it, and summed over the positives that is n+n−AUROCn_+ n_-\, \mathrm{AUROC}. So

AUROC=R+−n+(n++1)/2n+n−, \mathrm{AUROC} = \frac{R_+ - n_+ (n_+ + 1)/2}{n_+ n_-} ,

the Mann–Whitney statistic. It is unchanged by any strictly increasing transformation of the scores, and so blind to calibration. A gate needs both: its threshold t∗t^* assumes calibration, and it is only worth having if the probabilities also discriminate.

Reliability diagrams of the true probabilities and of an overconfident copy Two reliability diagrams side by side, each over 3,000 items drawn from the known four-class truth of calibration_lab.py, with ten equal-mass bins of 300 items. Both axes run from 0.2 to 1. Each bin is a point at its mean confidence across and its accuracy up, with a vertical bar for the 95 percent bootstrap band of the accuracy, and a dashed diagonal marks perfect calibration. Left, the truth itself: every point lies near the diagonal, and all ten bands cross it; the ten-bin ECE is 0.014. Right, the same logits doubled: the points run from confidence 0.44 to 0.99 while accuracy only reaches 0.89, every point lies below the diagonal, no band reaches it, and the gap is largest, 0.29, at confidence 0.83; the ten-bin ECE is 0.165. Both panels score the same items against the same labels. 0.2 0.2 0.4 0.4 0.6 0.6 0.8 0.8 1 1 mean confidence accuracy ECE 0.014 The truth 0.2 0.2 0.4 0.4 0.6 0.6 0.8 0.8 1 1 mean confidence accuracy ECE 0.165 Logits doubled a bin of 300 95% bootstrap band calibrated: accuracy = confidence

The figure draws both forecasters of the lab on one draw of 3,000 items (talos), with ten equal-mass bins. Each vertical bar is a bootstrap band: the bins are fixed from the full sample, each bin’s items are resampled with replacement 200 times, the accuracy is recomputed each time, and the bar runs from the 2.5th to the 97.5th percentile of those accuracies. It shows how far a bin’s accuracy could move on another sample of the same size. For a bin of 300 items near accuracy 0.6 the binomial standard error is 0.6×0.4/300=0.028\sqrt{0.6 \times 0.4 / 300} = 0.028, and the truth’s bars are 0.07 to 0.12 long, about the ±1.96\pm 1.96 standard errors of a normal interval. Every one of the truth’s bars crosses the diagonal, so none of its bins’ deviations can be told apart from noise; none of the overconfident copy’s bars does. What a bootstrap interval promises, and when it fails, is chapter 38’s subject.

Temperature scaling

A trained classifier is usually wrong about its own confidence in one direction: fitted to its training set, it is more confident on new items than it should be. Temperature scaling corrects that with one number per model (per head, in chapter 21). For an item with logits zz, shape (K,)(K,), the model answers pT=softmax(z/T)p_T = \mathrm{softmax}(z / T) for a temperature T>0T > 0. Dividing by a positive number keeps the logits’ order, so the top answer, and with it the accuracy, is the same at every TT. T>1T > 1 pulls the distribution toward uniform, T<1T < 1 sharpens it, and the limits are the uniform distribution as T→∞T \to \infty and all the mass on the top answer as T→0T \to 0. Models train at T=1T = 1 (chapter 21’s exercise (i) says why), and TT is then fitted alone, by minimising the log loss on held-out gold labels, a fitting split (gold_fit in chapter 21), and the result is reported on another held-out split (gold_eval), since a TT fitted to one sample is tuned to that sample.

The NLL is convex in β=1/T\beta = 1/T. For one item with label yy, write pβ=softmax(βz)p_\beta = \mathrm{softmax}(\beta z). Its log loss is

ℓ(β)=−logpβ,y=−βzy+log∑keβzk. \ell(\beta) = -\log p_{\beta, y} = -\beta z_y + \log \sum_k e^{\beta z_k} .

Differentiate the log-sum-exp: its derivative is ∑kzkeβzk/∑jeβzj=∑kzkpβ,k\sum_k z_k e^{\beta z_k} / \sum_j e^{\beta z_j} = \sum_k z_k\, p_{\beta, k}, so

ℓ′(β)=−zy+Ek∼pβ[zk]. \ell'(\beta) = -z_y + \mathbb{E}_{k \sim p_\beta}[z_k] .

Next, each probability’s derivative: logpβ,k=βzk−log∑jeβzj\log p_{\beta, k} = \beta z_k - \log \sum_j e^{\beta z_j}, so ddβlogpβ,k=zk−Epβ[z]\frac{d}{d\beta} \log p_{\beta, k} = z_k - \mathbb{E}_{p_\beta}[z] and dpβ,kdβ=pβ,k(zk−Epβ[z])\frac{d p_{\beta, k}}{d\beta} = p_{\beta, k}\big(z_k - \mathbb{E}_{p_\beta}[z]\big). Then

ℓ′′(β)=∑kzkpβ,k(zk−Epβ[z])=Epβ[z2]−(Epβ[z])2=Vark∼pβ(zk)≥0, \ell''(\beta) = \sum_k z_k\, p_{\beta, k} \big(z_k - \mathbb{E}_{p_\beta}[z]\big) = \mathbb{E}_{p_\beta}[z^2] - \big(\mathbb{E}_{p_\beta}[z]\big)^2 = \mathrm{Var}_{k \sim p_\beta}(z_k) \ge 0 ,

the variance of the logits under the model’s own distribution. ℓ\ell is convex in β\beta, and so is the mean over items, a sum of convex functions. It is strictly convex as long as some item’s logits are not all equal, since pβp_\beta gives every option positive probability. With soft targets YY, the first term becomes −β∑kYkzk-\beta \sum_k Y_k z_k, still linear in β\beta, and the second derivative is the same. A logistic answer is the softmax of the two logits (z,0)(z, 0), so the same holds for it. Chapter 21’s score head, whose levels are not a softmax, needs its own argument, which it gets there.

Searching in logT\log T. A convex function of β\beta on (0,∞)(0, \infty) is unimodal: it strictly falls, possibly stays flat at its minimum, then strictly rises. (Were it level at two points left of a lower point, the middle one would lie above the chord to the lower point, against convexity; symmetrically on the right.) Composing with a strictly monotone map moves points but keeps their order, reversed or not, so the composite also strictly falls and then strictly rises: the NLL is unimodal in logT=−logβ\log T = -\log \beta. It need not be convex there, but unimodality is all a golden-section search needs. Searching on logT\log T treats 0.1 and 10 alike, and the default bracket [0.05,20][0.05, 20] is symmetric about T=1T = 1 in it, log0.05=−3.00\log 0.05 = -3.00 and log20=3.00\log 20 = 3.00.

Golden-section search keeps a bracket [a,b][a, b] known to contain a minimiser, and two interior points c<dc < d. If f(c)≤f(d)f(c) \le f(d), not every minimiser can lie beyond dd: were every minimiser beyond dd, ff would be strictly falling on [a,d][a, d] and f(c)>f(d)f(c) > f(d). So a minimiser lies in [a,d][a, d], which becomes the bracket. Otherwise one lies in [c,b][c, b]. Each step evaluates ff at one new point only if the surviving interior point lands where the next step needs one. With bracket length LL, put c=b−gLc = b - gL and d=a+gLd = a + gL. After keeping [a,d][a, d], of length gLgL, the next step wants its upper interior point at a+g⋅gLa + g \cdot gL, and the old cc sits at a+(1−g)La + (1 - g) L. They coincide when

g2=1−g,g2+g−1=0,g=5−12=0.618…, g^2 = 1 - g, \qquad g^2 + g - 1 = 0, \qquad g = \frac{\sqrt{5} - 1}{2} = 0.618\ldots ,

the positive root; by symmetry the other case needs the same gg. Every step then costs one evaluation and shrinks the bracket by the factor gg. fit_temperature runs 80 steps: the bracket of logT\log T starts log400=5.99\log 400 = 5.99 wide and ends 5.99×g80=1.1×10−165.99 \times g^{80} = 1.1 \times 10^{-16} wide (talos), about float64’s resolution near 1, and returns its midpoint.

Why the result is floored. If every fitting item’s label is its strict top answer, then zyz_y is the item’s largest logit and some other logit is smaller, ℓ′(β)=Epβ[z]−zy<0\ell'(\beta) = \mathbb{E}_{p_\beta}[z] - z_y < 0 for every β\beta, and the NLL keeps falling as T→0T \to 0. The search then runs to the bottom of its bracket. fit_temperature raises the bracket’s bottom to T_MIN =10−3= 10^{-3} whatever lo it is given, and clamps its answer into the bracket, since elogxe^{\log x} need not give back xx: on talos, math.exp(math.log(20.0)) is 19.999999999999996. Chapter 21 relies on the floor: every fitted temperature is at least the floor its score head’s ordinal_log_probs applies, and its weights file refuses a stored temperature below it (WeightsInvalid), so Python and Go never divide by a smaller one.

Fitting lowers the NLL it fits. Let T⋆T^\star minimise the fitting split’s NLL over the bracket. The default bracket contains T=1T = 1, so NLL(T⋆)≤NLL(1)\mathrm{NLL}(T^\star) \le \mathrm{NLL}(1). The search keeps a minimiser inside its bracket at every step and returns a point of the final bracket, within about 10−1610^{-16} of T⋆T^\star in logT\log T, so the fitted temperature satisfies the same inequality up to that rounding. The inequality is strict unless T=1T = 1 is already a minimiser: if ddβNLL≠0\frac{d}{d\beta}\mathrm{NLL} \ne 0 at β=1\beta = 1, a small step in one direction lowers the NLL. Setting the mean of ℓ′(β)\ell'(\beta) to zero gives the condition the fitted temperature meets when it lands inside the bracket,

1N∑n=1Nzn,yn=1N∑n=1NEk∼pβ[zn,k]: \frac{1}{N} \sum_{n=1}^{N} z_{n, y_n} = \frac{1}{N} \sum_{n=1}^{N} \mathbb{E}_{k \sim p_\beta}[z_{n,k}] :

on the fitting split, the average logit of the observed answer equals the average logit the model expects under its own distribution. It is calibration in the large again, now for the scale of the logits rather than their offsets. None of this holds for the evaluation split. TT was chosen for a different sample, and on the evaluation split its NLL can come out higher than at T=1T = 1. When the two splits are drawn alike and the fitting split is large, their NLL curves are close and the evaluation NLL falls as well, as it does below; the report comes from gold_eval so that nothing rests on that.

On the lab’s overconfident copy, whose logits are exactly twice the truth’s so that T=2T = 2 undoes the doubling, one draw of 3,000 items split in half gives (talos): ddβNLL=0.5329\frac{d}{d\beta}\mathrm{NLL} = 0.5329 at β=1\beta = 1 on the fitting half, positive, so lowering β\beta, raising TT, helps; a fitted T=1.9948T = 1.9948; the fitting half’s NLL from 1.1228 to 0.9597; the evaluation half’s from 1.1280 to 0.9624, the truth’s own value to four places; its equal-mass ECE from 0.1613 to 0.0260, against the truth’s 0.0263 on the same items and a floor bound of 2/π15/6000=0.0399\sqrt{2/\pi}\sqrt{15/6000} = 0.0399 for 1,500 items; and the accuracy 0.6033 at every temperature. One number fixed it because the copy’s miscalibration is one scale factor. A model that is overconfident at some confidences and underconfident at others, or miscalibrated on one option only, has no single TT that fixes it, and no temperature changes which answer is on top.

A controlled experiment

TypeSafe AI says Jev is trained by RLCD, reinforcement learning against a proper scoring rule (“Sums of proper rules”), and claims calibrated answers for it. Laya’s proper_reward spells out one reading: the model’s report is perturbed, the perturbed report is scored by the log score plus 0.5 times the spherical score, and the score is the reward. With no loss code, data or weights published, a reproduction could not be checked, so this section asks a question instead. Cross-entropy training already seeks calibration (“Why cross-entropy training seeks calibration”). What does reinforcement learning with a proper reward add to it, and does calibration from either survive when the data a gate sees stops looking like the data it was trained on?

Real data cannot answer that, because its true probabilities are unknown: every calibration number outside this section, here and in chapter 21, is estimated from sampled labels, with the binning floor of “Measuring calibration” under it. Here the truth is a formula. The inputs are drawn from a known distribution, the true conditional p(y∣x)p(y \mid x) is computed for every item, and the labels are sampled from it. A model’s calibration error is then a distance between two distributions the program holds for every item, with no bins and no sampled labels in it.

The truth. Each of ten seeds s=0,…,9s = 0, \ldots, 9 draws one truth (make_truth). Inputs are x∼N(0,I16)x \sim \mathcal{N}(0, I_{16}), shape (16,)(16,), and there are K=4K = 4 classes. With weights W∗W^* of shape (4,16)(4, 16), entries drawn from N(0,0.352)\mathcal{N}(0, 0.35^2), and a bias b∗b^* of shape (4,)(4,) from N(0,0.52)\mathcal{N}(0, 0.5^2), the well-specified arm has

p(y∣x)=softmax(W∗x+b∗)y. p(y \mid x) = \mathrm{softmax}(W^* x + b^*)_y .

The misspecified arm adds a term the learners cannot represent: with ϕ2(x)\phi_2(x) the 120 products xixjx_i x_j for i<ji < j, shape (120,)(120,), and WpW_p of shape (4,120)(4, 120) from N(0,0.052)\mathcal{N}(0, 0.05^2),

p(y∣x)=softmax(W∗x+b∗+Wpϕ2(x))y. p(y \mid x) = \mathrm{softmax}\big(W^* x + b^* + W_p\, \phi_2(x)\big)_y .

The scale 0.05 leaves a linear model a usable approximation rather than a hopeless one. Both learners are linear softmax models, z=Wx+bz = W x + b with WW of shape (4,16)(4, 16) and bb of shape (4,)(4,), both started at 0: in the first arm the truth is in their family, in the second it is not. Each seed trains on n=5,000n = 5{,}000 source items, fits a temperature on 1,000 more, and is tested on 20,000 items from each of four target distributions.

The learners. (a) Cross-entropy: the mean log loss of the sampled labels, full batch, Adam (chapter 9’s update, adam_fit, which chapter 21 lists) for 500 steps at learning rate 0.05. (b) REINFORCE with a proper reward: for item nn the model’s logits znz_n, shape (4,)(4,), are perturbed to z~n=zn+σε\tilde z_n = z_n + \sigma \varepsilon with ε∼N(0,I4)\varepsilon \sim \mathcal{N}(0, I_4); the report is q~=softmax(z~n)\tilde q = \mathrm{softmax}(\tilde z_n), and it earns the reward

S(q~,y)=logq~y+0.5q~y∥q~∥2, S(\tilde q, y) = \log \tilde q_y + 0.5\, \frac{\tilde q_y}{\lVert \tilde q \rVert_2} ,

the log score plus half the spherical score, both as rewards (higher is better), which “Sums of proper rules” showed is strictly proper. Each item gets G=8G = 8 draws, the baseline is the group’s mean reward, and Adam ascends the estimated gradient for 1,500 steps at learning rate 0.02, for σ∈{0.25,0.5,1.0}\sigma \in \{0.25, 0.5, 1.0\}. The noise is what makes this reinforcement learning: the reward is paid on a sampled action, the perturbed report, and the gradient comes from the log-probability of that action, not from differentiating the reward.

The REINFORCE gradient. Fix one item and drop its index. The perturbed logits z~=z+σε\tilde z = z + \sigma\varepsilon are a Gaussian with mean zz and covariance σ2I\sigma^2 I, whose density is

πz(z~)=(2πσ2)−K/2exp(−∥z~−z∥22σ2). \pi_z(\tilde z) = (2\pi\sigma^2)^{-K/2} \exp\Big(-\frac{\lVert \tilde z - z \rVert^2}{2\sigma^2}\Big) .

Its log is −K2log(2πσ2)−12σ2∑k(z~k−zk)2-\frac{K}{2}\log(2\pi\sigma^2) - \frac{1}{2\sigma^2}\sum_k (\tilde z_k - z_k)^2, and differentiating in zkz_k gives −12σ2⋅2(z~k−zk)(−1)-\frac{1}{2\sigma^2} \cdot 2(\tilde z_k - z_k)(-1), so

∇zlogπz(z~)=z~−zσ2,shape (K,). \nabla_z \log \pi_z(\tilde z) = \frac{\tilde z - z}{\sigma^2} , \qquad \text{shape } (K,) .

Write the reward of a draw as R(z~)=S(softmax(z~),y)R(\tilde z) = S(\mathrm{softmax}(\tilde z), y); it depends on zz only through the draw. Chapter 13’s log-derivative trick, with an integral over z~\tilde z in place of the sum over replies, moves the gradient onto the density:

∇zEz~∼πz[R(z~)]=∫R(z~)∇zπz(z~)dz~=∫R(z~)πz(z~)∇zlogπz(z~)dz~=E[R(z~)z~−zσ2]. \begin{aligned} \nabla_z\, \mathbb{E}_{\tilde z \sim \pi_z}[R(\tilde z)] &= \int R(\tilde z)\, \nabla_z \pi_z(\tilde z)\, d\tilde z = \int R(\tilde z)\, \pi_z(\tilde z)\, \nabla_z \log \pi_z(\tilde z)\, d\tilde z \\[0.6em] &= \mathbb{E}\Big[R(\tilde z)\, \frac{\tilde z - z}{\sigma^2}\Big] . \end{aligned}

(Moving ∇z\nabla_z inside the integral is allowed here: the density is smooth in zz and its Gaussian tails dominate the reward, which is bounded above and grows no faster than linearly in z~\tilde z below.) A constant baseline bb subtracts nothing in expectation, because E[(z~−z)/σ2]=E[ε]/σ=0\mathbb{E}[(\tilde z - z)/\sigma^2] = \mathbb{E}[\varepsilon]/\sigma = 0; this is chapter 13’s argument, where ∫∇zπz=∇z1=0\int \nabla_z \pi_z = \nabla_z 1 = 0 did the same work. With GG draws z~1,…,z~G\tilde z_1, \ldots, \tilde z_G, rewards RgR_g and their mean R¯\bar R, the estimate is

g^=1G∑g=1G(Rg−R¯)z~g−zσ2,shape (K,). \hat g = \frac{1}{G} \sum_{g=1}^{G} (R_g - \bar R)\, \frac{\tilde z_g - z}{\sigma^2} , \qquad \text{shape } (K,) .

R¯\bar R contains RgR_g itself, so it is not a constant. Chapter 13’s leave-one-out step repairs it: with bgb_g the mean of the other G−1G - 1 rewards, Rg−R¯=G−1G(Rg−bg)R_g - \bar R = \frac{G-1}{G}(R_g - b_g), and bgb_g is independent of draw gg, so E[g^]=G−1G∇zE[R]\mathbb{E}[\hat g] = \frac{G-1}{G}\, \nabla_z \mathbb{E}[R]: the true gradient times 7/87/8 for G=8G = 8. The factor does not matter to Adam, whose step divides the gradient’s running mean by the root of its running mean square, so a constant factor on every gradient cancels (up to the 10−810^{-8} in the denominator).

The logits of all NN items are Z=XW⊤+bZ = X W^\top + b, with XX of shape (N,16)(N, 16) and ZZ of shape (N,4)(N, 4). The objective is the mean reward, 1N∑nE[Rn]\frac{1}{N}\sum_n \mathbb{E}[R_n], and znz_n depends on WkdW_{kd} through znk=∑dWkdxnd+bkz_{nk} = \sum_d W_{kd} x_{nd} + b_k, so ∂znk/∂Wkd=xnd\partial z_{nk} / \partial W_{kd} = x_{nd} and ∂znk/∂bk=1\partial z_{nk} / \partial b_k = 1. The chain rule then gives, with g^n\hat g_n stacked into G^\hat G of shape (N,4)(N, 4),

∂∂W=1N∑ng^nxn⊤=1NG^⊤X(4,16),∂∂b=1N∑ng^n(4,). \frac{\partial}{\partial W} = \frac{1}{N} \sum_n \hat g_n x_n^\top = \frac{1}{N} \hat G^\top X \quad (4, 16), \qquad \frac{\partial}{\partial b} = \frac{1}{N} \sum_n \hat g_n \quad (4,) .

This reward is differentiable, so there is a second route to the same expectation: ∇zE[R(z+σε)]=E[∇R(z+σε)]\nabla_z \mathbb{E}[R(z + \sigma\varepsilon)] = \mathbb{E}[\nabla R(z + \sigma\varepsilon)], differentiating through the draw. test_reinforce_is_an_unbiased_estimate_of_the_reward_gradient checks that the two agree, computing the REINFORCE estimate with one group of 400,000 draws (where (G−1)/G(G-1)/G differs from 1 by 2.5×10−62.5 \times 10^{-6}) against finite differences of the reward. REINFORCE never differentiates SS; that is why it applies to rewards on sampled text, and why it is noisier here, where the derivative was available.

The shared optimum, and where it stops being shared. Cross-entropy minimises the expected log loss, and “Why cross-entropy training seeks calibration” showed that when some parameters reproduce the truth for every xx, those parameters minimise it and every minimiser reproduces the truth. In the well-specified arm the truth is a linear softmax, so the population optimum of (a) is p^=p\hat p = p.

For (b), fix xx, write pp for p(⋅∣x)p(\cdot \mid x), shape (4,)(4,), and S¯(r,p)=∑kpkS(r,k)\bar S(r, p) = \sum_k p_k S(r, k) for the expected reward of report rr. The population objective at xx is Eε[S¯(softmax(z+σε),p)]\mathbb{E}_\varepsilon\big[\bar S(\mathrm{softmax}(z + \sigma\varepsilon), p)\big]. At σ=0\sigma = 0 that is S¯(softmax(z),p)\bar S(\mathrm{softmax}(z), p), and strict properness makes softmax(z)=p\mathrm{softmax}(z) = p its only maximiser: the same optimum as (a). At σ>0\sigma > 0 the report is a random vector, and no choice of zz makes every draw equal pp. For the log term the optimum can be found exactly. Since logsoftmax(z~)y=z~y−LSE(z~)\log \mathrm{softmax}(\tilde z)_y = \tilde z_y - \mathrm{LSE}(\tilde z), with LSE(z~)=log∑kez~k\mathrm{LSE}(\tilde z) = \log \sum_k e^{\tilde z_k},

EεEy∼p[logsoftmax(z+σε)y]=p⋅z+σp⋅E[ε]−Eε[LSE(z+σε)]=p⋅z−Eε[LSE(z+σε)]. \begin{aligned} \mathbb{E}_\varepsilon \mathbb{E}_{y \sim p}\big[\log \mathrm{softmax}(z + \sigma\varepsilon)_y\big] &= p \cdot z + \sigma\, p \cdot \mathbb{E}[\varepsilon] - \mathbb{E}_\varepsilon\big[\mathrm{LSE}(z + \sigma\varepsilon)\big] \\[0.6em] &= p \cdot z - \mathbb{E}_\varepsilon\big[\mathrm{LSE}(z + \sigma\varepsilon)\big] . \end{aligned}

The gradient of LSE\mathrm{LSE} is the softmax, so the gradient in zz is p−Eε[softmax(z+σε)]p - \mathbb{E}_\varepsilon[\mathrm{softmax}(z + \sigma\varepsilon)]. LSE\mathrm{LSE} is convex, an average of convex functions is convex, and so the objective is concave: its stationary points are its maxima, and they satisfy

Eε[softmax(z+σε)]=p. \mathbb{E}_\varepsilon\big[\mathrm{softmax}(z + \sigma\varepsilon)\big] = p .

Under the log reward it is the noisy report’s mean that the optimum makes equal to the truth, exactly; the noise-free report softmax(z)\mathrm{softmax}(z), the one a deployed model would give, is something else. The spherical term moves the stationary point again, by an amount with no closed form, so the full reward’s optimum is near this condition rather than on it. The two learners share a population optimum only at σ=0\sigma = 0.

How far is softmax(z)\mathrm{softmax}(z) from its noisy mean? Write f=softmaxf = \mathrm{softmax} and expand one component to second order around zz:

fi(z+σε)=fi(z)+σ∑k∂fi∂zkεk+σ22∑k,l∂2fi∂zk∂zlεkεl+O(σ3∥ε∥3). f_i(z + \sigma\varepsilon) = f_i(z) + \sigma \sum_k \frac{\partial f_i}{\partial z_k}\, \varepsilon_k + \frac{\sigma^2}{2} \sum_{k, l} \frac{\partial^2 f_i}{\partial z_k \partial z_l}\, \varepsilon_k \varepsilon_l + O(\sigma^3 \lVert \varepsilon \rVert^3) .

Take the expectation: E[εk]=0\mathbb{E}[\varepsilon_k] = 0 removes the first-order term, E[εkεl]=[k=l]\mathbb{E}[\varepsilon_k \varepsilon_l] = [k = l] keeps only the diagonal of the second, and the third-order term has expectation 0 because odd moments of a centred Gaussian vanish, so the error is O(σ4)O(\sigma^4):

E[fi(z+σε)]=fi(z)+σ22∑k∂2fi∂zk2+O(σ4). \mathbb{E}\big[f_i(z + \sigma\varepsilon)\big] = f_i(z) + \frac{\sigma^2}{2} \sum_k \frac{\partial^2 f_i}{\partial z_k^2} + O(\sigma^4) .

The softmax’s first derivatives are ∂fi/∂zk=fi([i=k]−fk)\partial f_i / \partial z_k = f_i([i = k] - f_k). Differentiate once more in zkz_k by the product rule:

∂2fi∂zk2=∂fi∂zk([i=k]−fk)−fi∂fk∂zk=fi([i=k]−fk)2−fifk(1−fk). \frac{\partial^2 f_i}{\partial z_k^2} = \frac{\partial f_i}{\partial z_k}\big([i = k] - f_k\big) - f_i \frac{\partial f_k}{\partial z_k} = f_i\big([i = k] - f_k\big)^2 - f_i f_k (1 - f_k) .

Sum over kk. The first part is fi[(1−fi)2+∑k≠ifk2]=fi[1−2fi+∥f∥2]f_i\big[(1 - f_i)^2 + \sum_{k \ne i} f_k^2\big] = f_i\big[1 - 2 f_i + \lVert f \rVert^2\big], and the second is −fi∑k(fk−fk2)=−fi[1−∥f∥2]-f_i \sum_k (f_k - f_k^2) = -f_i\big[1 - \lVert f \rVert^2\big], so

∑k∂2fi∂zk2=2fi(∥f∥2−fi),E[f(z+σε)]≈f+σ2f⊙(∥f∥2−f), \sum_k \frac{\partial^2 f_i}{\partial z_k^2} = 2 f_i\big(\lVert f \rVert^2 - f_i\big), \qquad \mathbb{E}\big[f(z + \sigma\varepsilon)\big] \approx f + \sigma^2 f \odot \big(\lVert f \rVert^2 - f\big) ,

with ⊙\odot the elementwise product. ∥f∥2=∑kfk2=Ek∼f[fk]\lVert f \rVert^2 = \sum_k f_k^2 = \mathbb{E}_{k \sim f}[f_k], the average probability weighted by itself, so noise lowers every probability above that average and raises every one below it: it flattens the report. The largest probability is always at or above it, since ∑kfk2≤maxkfk∑kfk\sum_k f_k^2 \le \max_k f_k \sum_k f_k. To make the flattened mean equal pp, the optimum’s raw report must be sharper than pp, overconfident, by an amount of order σ2\sigma^2 while σ\sigma is small. That is prediction P5 below, with its direction: the temperature fitted afterwards on source labels should come out above 1, and grow with σ\sigma. How good is the approximation? For z=(0.7,−0.3,0.2,−1.1)z = (0.7, -0.3, 0.2, -1.1), softmax(z)0=0.4674\mathrm{softmax}(z)_0 = 0.4674; its noisy mean over 200,000 draws and the second-order formula are 0.4634 and 0.4635 at σ=0.25\sigma = 0.25, 0.4533 and 0.4518 at σ=0.5\sigma = 0.5, and 0.4245 and 0.4052 at σ=1\sigma = 1 (experiment_checks.py, the same on talos, straylight and titan). At σ=1\sigma = 1 the expansion overshoots and only the direction survives. A temperature rescales the logits, which is not the same map as this flattening, so it can absorb part of the bias and not, in general, all of it.

Covariate shift moves the inputs and keeps the conditional: x∼N(μ,I)x \sim \mathcal{N}(\mu, I) with ∣μ∣=1.5\lvert \mu \rvert = 1.5, and p(y∣x)p(y \mid x) as before. If p^(⋅∣x)=p(⋅∣x)\hat p(\cdot \mid x) = p(\cdot \mid x) at every xx, the error is zero under any distribution of xx, so a well-specified model that has found the truth stays calibrated; what can move is its estimation error, which is small. A misspecified model has no such protection. The best linear fit minimises ExKL(p∥p^)\mathbb{E}_x \mathrm{KL}(p \Vert \hat p) averaged over the source xx, trading errors in one region against another by the source’s weights, and the target weighs the regions differently. Here the shift also moves the missing term: under x=μ+ux = \mu + u with u∼N(0,I)u \sim \mathcal{N}(0, I), each product is xixj=uiuj+μiuj+μjui+μiμjx_i x_j = u_i u_j + \mu_i u_j + \mu_j u_i + \mu_i \mu_j, so the misspecified truth gains logit terms linear in uu and a constant, none of which the source fit saw.

Label shift moves the class priors and keeps the class-conditional inputs: p′(x∣y)=p(x∣y)p'(x \mid y) = p(x \mid y), and p′(y)=πy′p'(y) = \pi'_y where the source had πy\pi_y. By Bayes’ rule in the target, and then in the source, p(x∣y)=p(y∣x)p(x)/πyp(x \mid y) = p(y \mid x)\, p(x) / \pi_y:

p′(y∣x)=p(x∣y)πy′∑jp(x∣j)πj′=p(y∣x)p(x)πy′/πy∑jp(j∣x)p(x)πj′/πj=p(y∣x)ay∑jp(j∣x)aj,ay=πy′πy. \begin{aligned} p'(y \mid x) &= \frac{p(x \mid y)\, \pi'_y}{\sum_j p(x \mid j)\, \pi'_j} = \frac{p(y \mid x)\, p(x)\, \pi'_y / \pi_y}{\sum_j p(j \mid x)\, p(x)\, \pi'_j / \pi_j} \\[0.6em] &= \frac{p(y \mid x)\, a_y}{\sum_j p(j \mid x)\, a_j}, \qquad a_y = \frac{\pi'_y}{\pi_y} . \end{aligned}

p(x)p(x) cancels. In logits, logp′(y∣x)=zy+logay−log∑jezj+logaj\log p'(y \mid x) = z_y + \log a_y - \log \sum_j e^{z_j + \log a_j}: the correction adds the constant vector logπ′−logπ\log \pi' - \log \pi, shape (4,)(4,), to every item’s logits, and a model’s answer can be corrected the same way once π′\pi' is known. shifted builds the target by rejection: draw (x,y)(x, y) from the source and keep it with probability ay/maxjaja_y / \max_j a_j. The kept pairs have joint density proportional to p(x)p(y∣x)ayp(x)\, p(y \mid x)\, a_y, so their conditional is p(y∣x)ayp(y \mid x) a_y renormalised, the formula above; their prior is proportional to πyay=πy′\pi_y a_y = \pi'_y; and the acceptance depends on yy alone, so p(x∣y)p(x \mid y) is untouched. The source prior πy=Exp(y∣x)\pi_y = \mathbb{E}_x\, p(y \mid x) has no closed form and is estimated from 200,000 draws; π′\pi' is a Dirichlet(1, 1, 1, 1) draw per seed.

Estimating π′\pi' by EM. A deployed gate sees target inputs without labels. Saerens, Latinne and Decaestecker (2002) estimate π′\pi' from them by expectation maximisation. The target inputs have the mixture density p′(x)=∑yπy′p(x∣y)p'(x) = \sum_y \pi'_y\, p(x \mid y), so the log-likelihood of unlabelled x1,…,xNx_1, \ldots, x_N is

L(π′)=∑nlog∑yπy′p(xn∣y)=∑nlog∑yπy′p(y∣xn)πy+∑nlogp(xn), L(\pi') = \sum_n \log \sum_y \pi'_y\, p(x_n \mid y) = \sum_n \log \sum_y \pi'_y\, \frac{p(y \mid x_n)}{\pi_y} + \sum_n \log p(x_n) ,

using p(x∣y)=p(y∣x)p(x)/πyp(x \mid y) = p(y \mid x) p(x) / \pi_y again; the last sum does not depend on π′\pi', so only the model’s conditional and the source prior are needed. Treat the missing labels as latent. Given a current estimate π^′\hat\pi', the E-step computes each item’s posterior over its label under that estimate,

wny=p^(y∣xn)π^y′/πy∑jp^(j∣xn)π^j′/πj, w_{ny} = \frac{\hat p(y \mid x_n)\, \hat\pi'_y / \pi_y}{\sum_j \hat p(j \mid x_n)\, \hat\pi'_j / \pi_j} ,

the label-shift correction of the model’s answer, with WW of shape (N,4)(N, 4) and rows summing to 1. The M-step maximises the expected complete-data log-likelihood, Q(π′)=∑n∑ywny[logπy′+logp(xn∣y)]Q(\pi') = \sum_n \sum_y w_{ny} \big[\log \pi'_y + \log p(x_n \mid y)\big], over distributions π′\pi'. The second term does not involve π′\pi'. With a Lagrange multiplier λ\lambda for ∑yπy′=1\sum_y \pi'_y = 1, setting the derivative of ∑n,ywnylogπy′−λ(∑yπy′−1)\sum_{n,y} w_{ny} \log \pi'_y - \lambda(\sum_y \pi'_y - 1) in πy′\pi'_y to zero gives ∑nwny/πy′=λ\sum_n w_{ny} / \pi'_y = \lambda, so πy′=1λ∑nwny\pi'_y = \frac{1}{\lambda}\sum_n w_{ny}; summing over yy, 1=1λ∑n∑ywny=N/λ1 = \frac{1}{\lambda} \sum_n \sum_y w_{ny} = N/\lambda, and

π^y′←1N∑nwny, \hat\pi'_y \leftarrow \frac{1}{N} \sum_n w_{ny} ,

the mean corrected answer. (It is a maximum: QQ is a positive combination of logarithms, concave in π′\pi'.) Why iterating never lowers LL: for each item, with fny=πy′p(xn∣y)f_{ny} = \pi'_y p(x_n \mid y) and the E-step’s weights wnyw_{ny} computed at π^′\hat\pi', the concavity of log\log (Jensen’s inequality over the distribution wn⋅w_{n\cdot}) gives

log∑yfny=log∑ywnyfnywny≥∑ywnylogfnywny, \log \sum_y f_{ny} = \log \sum_y w_{ny} \frac{f_{ny}}{w_{ny}} \ge \sum_y w_{ny} \log \frac{f_{ny}}{w_{ny}} ,

with equality at π′=π^′\pi' = \hat\pi', where fny/wny=∑jf^njf_{ny}/w_{ny} = \sum_j \hat f_{nj} is the same for every yy. Summed over nn, the right side is Q(π′)Q(\pi') minus a term that does not depend on π′\pi': a lower bound on LL that touches it at π^′\hat\pi'. The M-step raises the bound, so L(new)≥bound(new)≥bound(π^′)=L(π^′)L(\text{new}) \ge \text{bound(new)} \ge \text{bound}(\hat\pi') = L(\hat\pi'). em_priors starts from the source prior and stops when no component moves by more than 10−1010^{-10}, or after 100 steps. In run, π\pi in both the E-step and the correction is the model’s own source prior, π^s\hat\pi_s, the mean of its tempered answers on the source calibration set, not the true π\pi: a gate knows its own average answer, not the truth’s. With that choice an unshifted target is a fixed point of EM up to sampling noise, since the first E-step then leaves every answer unchanged and their mean is π^s\hat\pi_s again.

Concept shift changes the conditional itself: p′(y∣x)=p(y∣Rx)p'(y \mid x) = p(y \mid R x), with R=QBQ⊤R = Q B Q^\top, QQ a random orthogonal matrix and BB block-diagonal with eight 2×22 \times 2 rotations by 60∘60^\circ, so RR turns each input’s component in each of eight orthogonal planes by 60∘60^\circ within that plane, and the angle between any xx and RxRx is 60∘60^\circ (“The experiment” shows x⋅Rx=12∥x∥2x \cdot Rx = \frac{1}{2}\lVert x \rVert^2). The inputs are drawn exactly as in the source. And since N(0,I)\mathcal{N}(0, I) is invariant under any orthogonal map, even RxRx has the source’s distribution: nothing computed from unlabelled target inputs can tell this target from the source, let alone correct for it. Labels can; a temperature is one number, and it cannot rotate WW.

The yardsticks. For each target test item the program holds the true p=p′(⋅∣x)p = p'(\cdot \mid x) and the model’s p^\hat p, both shape (4,)(4,). The true calibration error is the mean over the test items of

12∥p^−p∥1=12∑k∣p^k−pk∣, \tfrac{1}{2} \lVert \hat p - p \rVert_1 = \tfrac{1}{2} \sum_k \lvert \hat p_k - p_k \rvert ,

beside the mean of KL(p∥p^)\mathrm{KL}(p \Vert \hat p). The first is the largest error the model makes on the probability of any event. For a set of classes AA, p^(A)−p(A)=∑k∈A(p^k−pk)\hat p(A) - p(A) = \sum_{k \in A} (\hat p_k - p_k) is at most the sum of the positive differences; the differences sum to 0, so the positive ones and the negative ones have equal totals, each half of ∥p^−p∥1\lVert \hat p - p \rVert_1; and AA = the classes where p^k>pk\hat p_k > p_k attains it. So 12∥p^−p∥1=maxA∣p^(A)−p(A)∣\frac{1}{2}\lVert \hat p - p \rVert_1 = \max_A \lvert \hat p(A) - p(A) \rvert: a bound on the error of the top label’s probability, of any cumulative probability such as chapter 21’s at_least, and of a noul, all at once. The second is the log loss the model pays above the truth’s: by the decomposition of “Proper scoring rules”, Ey∼p[−logp^y]=H(p)+KL(p∥p^)\mathbb{E}_{y \sim p}[-\log \hat p_y] = H(p) + \mathrm{KL}(p \Vert \hat p). Both are exact for each item; the mean over 20,000 items is a Monte Carlo estimate over xx, with a standard error of 0.00014 for the true ℓ1\ell_1 of seed 0’s cross-entropy fit at T=1T = 1 in the well-specified arm and 0.00064 in the misspecified one (experiment_checks.py on straylight and titan), small beside every difference discussed below. Beside them the table prints the NLL and the three ECEs of “Measuring calibration”, 15 bins each, computed from sampled labels as they would be on real data.

Temperature is fitted on the source calibration set and applied to every target. A refit curve then fits it again on m∈{0,25,100,400}m \in \{0, 25, 100, 400\} labelled items drawn from the target (m=0m = 0 keeps the source’s), and reports the true ℓ1\ell_1 at each. For label shift the table also reports EM’s correction: p^′∝p^⊙π^′/π^s\hat p' \propto \hat p \odot \hat\pi' / \hat\pi_s, computed by correct_priors as softmax(Zt / T + log(prior / pi_hat)). For REINFORCE it reports the in-distribution true ℓ1\ell_1 of the raw report softmax(z)\mathrm{softmax}(z) and of the noisy report’s mean, Eεsoftmax(z+σε)\mathbb{E}_\varepsilon \mathrm{softmax}(z + \sigma\varepsilon) by 256 draws, both before any temperature.

Predictions, stated before the run, and the wording the verdicts are judged against (for P1 and P2 it is softer than the design’s “breaks” and “fixes”):

  • P1. Calibration survives covariate shift in the well-specified arm (the true ℓ1\ell_1 stays within the seed spread of its in-distribution value) and degrades in the misspecified arm.
  • P2. Label shift breaks calibration predictably, and the EM prior correction restores most of it.
  • P3. Concept shift breaks calibration, and neither refitting the temperature on up to 400 target labels nor anything unsupervised restores it.
  • P4. Cross-entropy and REINFORCE reach the same calibration in distribution, up to optimisation variance, with REINFORCE the noisier.
  • P5. With σ>0\sigma > 0 the reward is paid on the noisy report, so the raw report is biased, overconfident, and the bias grows with σ\sigma; the temperature fitted afterwards absorbs part of it.

What happened. The full grid ran on straylight (x86-64) and on titan (arm64) on 2026-09-30, ten seeds per row, and “The experiment” prints its table: the true ℓ1\ell_1 after the source temperature, as mean ± sample standard deviation over the seeds. The two hosts printed identical tables, and experiment_checks.py, which produces the side checks quoted below, printed the same digits on both except in the fifth decimal of the cross-entropy step-count check. Identical printed digits do not make the arithmetic identical: the seeds fix the data, not the floating-point summation order, which differs between the two CPUs’ kernels. Every comparison below holds on both hosts.

Every learner of a seed is scored on the same calibration and test sets (“The experiment” says how), so the comparisons that matter are per-seed differences. They are given as mean ± sample standard deviation over the ten seeds, with t=mean/(sd/10)t = \text{mean} / (\text{sd}/\sqrt{10}), the mean in units of its own standard error. With ten seeds, ∣t∣|t| above about 2.3 would arise by chance less than one time in twenty if the true mean difference were 0.

  • P1: confirmed, with a modest second half. In the well-specified arm the error under covariate shift is the in-distribution error to within the seed spread: covariate minus none is +0.0010 ± 0.0032 for cross-entropy (t=1.0t = 1.0) and +0.0006 to +0.0009 for REINFORCE (tt from 0.6 to 1.2). In the misspecified arm it is +0.0159 ± 0.0048 for cross-entropy (t=10.4t = 10.4), a rise of 12% on 0.1295: unmistakable, and modest. The estimated ECEs do not see it at all: the equal-mass ECE of the misspecified cross-entropy fit went from 0.0188 to 0.0178, down, while its true ℓ1\ell_1 went from 0.130 to 0.145. Top-label ECE asks only whether the top answer’s confidence matches its hit rate, averaged within bins of items, a marginal property, and a misspecified fit can meet it while its whole distribution is off by 0.13 on average per item (for seed 0 at T=1T = 1, from 0.024 to 0.306 between the 5th and 95th percentiles of items); the true ℓ1\ell_1 is a property of each item’s distribution.
  • P2: confirmed. Label shift raised the well-specified cross-entropy fit’s error from 0.037 to 0.244, 6.7-fold, and EM’s correction brought it back to 0.051: 93% of the added error removed. EM’s estimate of π′\pi' was off, in its worst component, by 0.035 on average over the seeds. In the misspecified arm the correction took 0.313 to 0.124, below the in-distribution 0.130. The shifted inputs are not why: scored against the source’s conditional at the same shifted inputs, the uncorrected fit’s error is 0.133, above 0.130, so moving the inputs alone made it worse. The prior tilt is why. Correcting with the true priors instead of EM’s gives 0.112 in the misspecified arm and 0.030 in the well-specified one, both below their in-distribution errors (experiment_checks.py, both hosts). Multiplying the fit’s answer and the truth by the same uneven ratio aya_y and renormalising moves both toward the favoured classes, and two distributions that both put most of their mass on the same class are close in ℓ1\ell_1; Dirichlet(1, 1, 1, 1) priors are often lopsided. Under label shift the equal-mass ECE rose from 0.016 to 0.044, by 0.028, while the true error rose by 0.208: the ECE reads the top answer alone, averaged within bins, and registered about 13% of the rise. The two measure different things, so the ratio only illustrates the gap.
  • P3: confirmed. Concept shift raised the error to 0.343 (well specified) and 0.354 (misspecified), the largest of the four, and the refit curve barely moved it: 400 target labels brought it to 0.321 and 0.341. Nothing unsupervised was tried, because nothing can work: the target inputs have the source’s distribution.
  • P4: refuted as run, confirmed in the limit; “the noisier” in one arm only. At the prescribed 1,500 steps REINFORCE was measurably worse in distribution. In the well-specified arm REINFORCE minus cross-entropy is +0.0020 ± 0.0020 (t=3.2t = 3.2) at σ=0.25\sigma = 0.25, +0.0020 ± 0.0020 (t=3.1t = 3.1) at 0.5 and +0.0018 ± 0.0019 (t=3.0t = 3.0) at 1, above 0 on nine seeds of ten; the three σ\sigma rows share their data and noise draws (“The experiment”), so they are one comparison three times. In the misspecified arm the gap is smaller and steadier, +0.0007 to +0.0010 (tt from 6.2 to 9.4). So as run, the two learners did not reach the same calibration. The shared optimum survives in the limit. Cross-entropy has converged at 500 steps: 2,000 steps change its error by less than 0.0001 on seeds 0 to 2 (on talos, straylight and titan, which differ in the fifth decimal). REINFORCE’s Adam, with a constant learning rate and a noisy gradient, has not settled at its end, and experiment_checks.py measures what happens when it is run on from where it stopped. Continued for 1,500 more steps at a tenth of the learning rate, it closed most of the gap: to +0.0005 or +0.0006 in the well-specified arm (tt from 2.0 to 3.6, a small residual that has not gone away), and to between −0.0001 and +0.0001 in the misspecified arm. The per-seed change is clear in the misspecified arm (tt from −6.4 to −11.3, every seed improving) and weaker in the well-specified one (−0.0014 ± 0.0022, t≈−2t \approx -2, six seeds of ten improving). Continued for 3,000 steps at the original rate, it did not close the gap: +0.0033 to +0.0040 in the well-specified arm and +0.0009 to +0.0013 in the misspecified one, and the mean per-seed change from the fit as run was positive in every row (+0.0015 to +0.0020, tt from 2.1 to 2.5, well specified; +0.0002 to +0.0003, tt from 0.6 to 1.3, misspecified). Whether running on at that rate widens the gap, this check does not settle: tt values near 2 in what is one comparison three times are weak evidence. Optimisation noise is not symmetric here, since the true error is least at the optimum and any displacement adds to it, so it shows up as a one-sided cost. “The noisier” held only in the well-specified arm, and only just: across seeds REINFORCE’s standard deviation was 0.0065 to 0.0067 against cross-entropy’s 0.0059; in the misspecified arm it was 0.0062 to 0.0064 against 0.0062, no noisier.
  • P5: confirmed, and the temperature absorbed more than “part”. In the well-specified arm the raw report’s true ℓ1\ell_1, before any temperature, was 0.0375, 0.0441 and 0.0779 for σ\sigma = 0.25, 0.5 and 1, while the noisy report’s mean stayed at 0.0367 to 0.0411, and the fitted temperature was 1.020, 1.082 and 1.284: always above 1, the raw report overconfident, as the Mechanism’s expansion said it must be. After that temperature the three rows’ errors are 0.0387, 0.0386 and 0.0385, a paired comparison since the rows differ only in σ\sigma: one scale factor removed almost all of the bias. In the misspecified arm the bias disappears into the fit’s own error at small σ\sigma (raw 0.1279 against noisy 0.1283 at σ\sigma = 0.25) and shows at σ\sigma = 1 (0.1380 against 0.1289).

What this says about RLCD, as far as a linear model on a known truth can say anything: reinforcement learning with a strictly proper reward did not calibrate better than cross-entropy. As run it did slightly worse; given a falling learning rate it reached nearly the same place, more slowly, and it added a bias of its own, the noise’s, that a temperature fitted afterwards had to remove. Calibration then failed or held by the kind of shift, not by the learner: each row of the tables has the same shape for both. A gate’s calibration is a property of the data it sees, and the defence the tables support is to measure it on that data, with labels, which is what chapter 21’s reports do.

Walkthrough

Scores, ECE and temperature

scoring.py holds the four rules, each a loss of shape (N,) for answers P of shape (N, K) and outcomes y of shape (N,):

def log_loss(P, y):
    """-log p_y: the log score (chapter 4's surprise), unbounded."""
    P = np.asarray(P, dtype=np.float64)
    with np.errstate(divide="ignore"):
        return -np.log(P[np.arange(len(y)), y])


def brier(P, y):
    """sum_k (p_k - [y = k])^2, in [0, 2]."""
    P = np.asarray(P, dtype=np.float64)
    E = np.zeros_like(P)
    E[np.arange(len(y)), y] = 1.0
    return np.sum((P - E) ** 2, axis=1)


def spherical(P, y):
    """-p_y / |p|_2: the spherical score, negated to a loss, in [-1, 0]."""
    P = np.asarray(P, dtype=np.float64)
    return -P[np.arange(len(y)), y] / np.sqrt(np.sum(P ** 2, axis=1))


def rps(P, y):
    """Ranked probability score for ordered classes: sum_{k=0}^{K-2} (F_k - [y <= k])^2 with F the
    cumulative distribution. It is the Brier score of the K-1 events Y <= k, added up."""
    P = np.asarray(P, dtype=np.float64)
    K = P.shape[1]
    F = np.cumsum(P, axis=1)[:, :-1]
    step = (np.asarray(y)[:, None] <= np.arange(K - 1)[None, :]).astype(np.float64)
    return np.sum((F - step) ** 2, axis=1)

Each is its Mechanism formula with the rows as items. P[np.arange(len(y)), y] picks each row’s probability of its own outcome, the pyp_y of the log and spherical scores. brier builds the one-hot matrix E and sums the squared differences along each row. rps takes the cumulative sums, drops the last column (always 1), and compares them with the step [y <= k], built by broadcasting y of shape (N, 1) against arange(K - 1) of shape (1, K-1). The module’s expected_loss(rule, p, q) computes S¯(p,q)\bar S(p, q) exactly: it scores one report against every outcome at once, rule(np.tile(p, (K, 1)), np.arange(K)), and weights the KK losses by qq. The lab’s properness tests use the same construction: for 50 random truths qq they check that 20 random perturbations each score no better than qq itself, and that a report at distance 0.02 from qq in a random direction scores strictly worse. Those tests are a check, not a proof; the proofs are the Mechanism’s.

calibration.py bins:

def _mass_bins(conf, bins):
    order = np.argsort(conf, kind="stable")
    return [b for b in np.array_split(order, bins) if len(b)]


def ece_equal_width(conf, correct, bins=15):
    """sum_b (n_b / N) |acc_b - conf_b| over bins [0, 1/bins), [1/bins, 2/bins), ..., [.., 1]."""
    conf, correct = np.asarray(conf, dtype=np.float64), np.asarray(correct, dtype=np.float64)
    idx = np.minimum((conf * bins).astype(int), bins - 1)
    total = 0.0
    for b in range(bins):
        sel = idx == b
        if sel.any():
            total += sel.sum() * abs(correct[sel].mean() - conf[sel].mean())
    return total / len(conf)


def ece_equal_mass(conf, correct, bins=15):
    """The same sum over bins holding (nearly) equal numbers of items, split in order of conf."""
    conf, correct = np.asarray(conf, dtype=np.float64), np.asarray(correct, dtype=np.float64)
    return sum(len(b) * abs(correct[b].mean() - conf[b].mean()) for b in _mass_bins(conf, bins)) / len(conf)


def ece_debiased(conf, correct, bins=15):
    """Debiased l2 calibration error over equal-mass bins:
    sqrt(max(0, sum_b (n_b / N) [(acc_b - conf_b)^2 - acc_b (1 - acc_b) / (n_b - 1)])).
    acc_b (1 - acc_b) / (n_b - 1) is an unbiased estimate of Var(acc_b), the part of E[(acc_b -
    conf_b)^2] that sampling noise alone contributes."""
    conf, correct = np.asarray(conf, dtype=np.float64), np.asarray(correct, dtype=np.float64)
    total = 0.0
    for b in _mass_bins(conf, bins):
        n, acc, c = len(b), correct[b].mean(), conf[b].mean()
        total += n * ((acc - c) ** 2 - (acc * (1 - acc) / (n - 1) if n > 1 else 0.0))
    return math.sqrt(max(0.0, total / len(conf)))

ece_equal_width finds each item’s bin as int(conf * bins), which puts a confidence of exactly 1.0 in bin bins, one past the last, so np.minimum(…, bins - 1) moves it into the last bin: the last interval is closed, [1−1/B,1][1 - 1/B, 1]. _mass_bins sorts the items by confidence and cuts the order into bins runs with np.array_split, which makes the first N % bins runs one item longer than the rest; kind="stable" fixes the order of tied confidences, so the bins do not depend on the sorting algorithm. Empty runs, which appear only when there are fewer items than bins, are dropped. ece_debiased is the formula derived above, with a bin of one item subtracting nothing, since nb−1=0n_b - 1 = 0 leaves the noise estimate undefined.

The temperature:

def fit_temperature(nll, lo=0.05, hi=20.0, iters=80):
    """The T in [max(lo, T_MIN), hi] minimising nll(T), by golden-section search on log T.

    For a softmax, nll is convex in beta = 1/T (a log-sum-exp minus a linear function), so it is
    unimodal in log T and the search finds the minimum. The result is clamped into the bracket,
    since exp(log(lo)) can round below lo."""
    lo = max(lo, T_MIN)
    a, b = math.log(lo), math.log(hi)
    g = (math.sqrt(5) - 1) / 2
    c, d = b - g * (b - a), a + g * (b - a)
    fc, fd = nll(math.exp(c)), nll(math.exp(d))
    for _ in range(iters):
        if fc <= fd:
            b, d, fd = d, c, fc
            c = b - g * (b - a)
            fc = nll(math.exp(c))
        else:
            a, c, fc = c, d, fd
            d = a + g * (b - a)
            fd = nll(math.exp(d))
    return min(max(math.exp((a + b) / 2), lo), hi)


def choice_nll(logits, Y, T=1.0):
    """Mean cross-entropy of softmax(logits / T) against Y: class indices (N,) or soft targets (N, K)."""
    logq = log_softmax(np.asarray(logits, dtype=np.float64) / T)
    Y = np.asarray(Y)
    if Y.ndim == 1:
        return float(-logq[np.arange(len(Y)), Y].mean())
    return float(-np.sum(Y * np.where(Y > 0, logq, 0.0)) / len(Y))     # 0 * log 0 counts as 0

fit_temperature takes the NLL as a function of TT, so the same search fits a softmax through choice_nll and chapter 21’s score and noul heads through their own log losses. c and d are the interior points b−gLb - gL and a+gLa + gL, on logT\log T. When fc <= fd the bracket becomes [a,d][a, d]: the old c becomes the new d, its value fc is kept as fd, and only the new c is evaluated; the other branch mirrors it. The first line raises lo to T_MIN, and test_fit_temperature_never_returns_less_than_the_floor hands the search f(T)=Tf(T) = T, which falls all the way down, with lo at 10−910^{-9}, and checks that the answer is the floor. choice_nll accepts class indices, shape (N,), or soft targets, shape (N, K); in the soft case a target of 0 against a log-probability of −∞-\infty (a masked option) would be 0⋅(−∞)0 \cdot (-\infty), NaN, so the log-probabilities are zeroed where the target is 0 before the product, for the same reason chapter 21’s choice_loss keeps only the live entries.

calibration_lab.py prints the oracle’s ECEs. Run from py/ with PYTHONPATH=. uv run python labs/ch20/calibration_lab.py; on talos it took 0.9 seconds and printed:

host talos; 15 bins; mean over 20 draws of each size
     n  oracle: width    mass  debiased   bound  overconfident: mass
   100         0.1080  0.1363    0.0290  0.1545               0.2041
   300         0.0639  0.0828    0.0199  0.0892               0.1722
  1000         0.0356  0.0446    0.0143  0.0489               0.1573
  3000         0.0213  0.0271    0.0092  0.0282               0.1623
 10000         0.0108  0.0136    0.0040  0.0155               0.1610
 30000         0.0068  0.0077    0.0024  0.0089               0.1614

The truth is drawn once, W of shape (4, 16) and b of shape (4,), and each row’s label is sampled from its own probabilities by inverting the cumulative distribution: a uniform draw uu lands in class kk when Fk−1<u≤FkF_{k-1} < u \le F_k, and counting the FkF_k below uu gives kk (np.minimum(…, 3) guards against F3F_3 rounding to just under 1). “bound” is 2/π15/(4n)\sqrt{2/\pi}\sqrt{15/(4n)}; “Measuring calibration” reads the columns.

The experiment

experiment.py holds the whole experiment. The truth:

def make_truth(seed, arm):
    """The true model for one seed: weights, the covariate shift's mean, the label shift's priors
    and the concept shift's rotation (60 degrees in each of 8 random orthogonal planes)."""
    rng = np.random.default_rng(seed)
    t = {"arm": arm, "W": rng.normal(0.0, 0.35, (K, D)), "b": rng.normal(0.0, 0.5, K)}
    if arm == "mis":
        t["Wp"] = rng.normal(0.0, 0.05, (K, D * (D - 1) // 2))
    u = rng.normal(size=D)
    t["mu"] = 1.5 * u / np.linalg.norm(u)
    t["prior"] = rng.dirichlet(np.ones(K))
    Q, _ = np.linalg.qr(rng.normal(size=(D, D)))                     # a random orthonormal basis
    c, s = math.cos(math.pi / 3), math.sin(math.pi / 3)
    R = np.zeros((D, D))
    for i in range(0, D, 2):
        R[i:i + 2, i:i + 2] = [[c, -s], [s, c]]
    t["R"] = Q @ R @ Q.T                                              # rotates every direction by 60 degrees
    return t


def true_probs(t, X, concept=False):
    """p(y | x), (N, K); with concept=True the shifted truth p(y | R x)."""
    X = X @ t["R"].T if concept else X
    Z = X @ t["W"].T + t["b"]
    if t["arm"] == "mis":
        i, j = np.triu_indices(D, 1)
        Z = Z + (X[:, i] * X[:, j]) @ t["Wp"].T
    return softmax(Z)

make_truth draws everything a seed needs from one generator, in a fixed order: W∗W^*, b∗b^*, then WpW_p for the misspecified arm, then the covariate shift’s direction, the label shift’s priors and the rotation’s basis. Because WpW_p is drawn in the middle, the two arms of one seed share W∗W^* and b∗b^* but not the shifts. The rotation is built as the Mechanism describes it: np.linalg.qr of a 16×1616 \times 16 standard normal matrix gives an orthogonal QQ, the loop fills eight 2×22 \times 2 blocks of BB with (cos60∘−sin60∘sin60∘cos60∘)\begin{pmatrix} \cos 60^\circ & -\sin 60^\circ \\ \sin 60^\circ & \cos 60^\circ \end{pmatrix}, and R=QBQ⊤R = Q B Q^\top is orthogonal because each factor is. test_truth_is_deterministic_and_the_rotation_is_orthogonal checks RR⊤=IR R^\top = I and that a random direction moves: for a unit vector xx whose squared components in the eight planes are c1,…,c8c_1, \ldots, c_8, x⋅Rx=∑icicos60∘=12x \cdot R x = \sum_i c_i \cos 60^\circ = \frac{1}{2} exactly, whatever xx is. true_probs computes the pair features with np.triu_indices(16, 1), the 120 index pairs above the diagonal, as X[:, i] * X[:, j], shape (N, 120), and with concept=True it evaluates the truth at X @ R.T, whose rows are RxnR x_n.

The shifts:

def source_prior(t, rng, n=200_000):
    """pi_y = E_x p(y | x) under the source x distribution, by Monte Carlo."""
    return true_probs(t, rng.normal(size=(n, D))).mean(axis=0)


def shifted(t, kind, n, rng, pi=None):
    """n target draws (X, y, P) under one shift. Label shift keeps p(x | y) and moves the priors to
    t["prior"]: draw (x, y) from the source and keep it with probability a_y / max a, where
    a_y = prior_y / pi_y; then the kept pairs have p'(y | x) proportional to p(y | x) a_y exactly."""
    if kind == "none":
        return sample(t, n, rng)
    if kind == "covariate":
        return sample(t, n, rng, mu=t["mu"])
    if kind == "concept":
        X = rng.normal(size=(n, D))
        P = true_probs(t, X, concept=True)
        return X, _draw(P, rng), P
    if kind == "label":
        a = t["prior"] / pi
        a = a / a.max()
        Xs, ys, Ps = [], [], []
        while sum(len(y) for y in ys) < n:
            X, y, P = sample(t, 4 * n, rng)
            keep = rng.random(len(y)) < a[y]
            Xs.append(X[keep]), ys.append(y[keep])
            Q = P[keep] * a
            Ps.append(Q / Q.sum(axis=1, keepdims=True))
        return np.concatenate(Xs)[:n], np.concatenate(ys)[:n], np.concatenate(Ps)[:n]
    raise ValueError(f"unknown shift {kind!r}")

_draw, outside the listing, samples one class per row by inverting the cumulative distribution, as the calibration lab does. The label shift’s loop draws source pairs in batches of 4n4n and keeps each with probability a[y], until nn are kept; the stored P for a kept pair is its source conditional times a, renormalised, the target’s conditional derived in the Mechanism. test_label_shift_moves_the_priors_and_keeps_p_x_given_y checks both halves on 20,000 pairs: the kept labels’ frequencies match π′\pi' within 0.02, and the stored conditionals average to π′\pi' as well, which is what Ex∼p′[p′(y∣x)]=πy′\mathbb{E}_{x \sim p'}[p'(y \mid x)] = \pi'_y requires of them.

The learners:

def fit_ce(X, y, steps=500, lr=0.05):
    """Learner (a): linear softmax by cross-entropy on the sampled labels (full batch, Adam)."""
    Y = np.eye(K)[y]

    def loss(p):
        logq = log_softmax(_logits(p, X))
        G = (np.exp(logq) - Y) / len(y)
        return float(-np.sum(Y * logq) / len(y)), {"W": G.T @ X, "b": G.sum(axis=0)}
    p, _ = adam_fit(loss, {"W": np.zeros((K, D)), "b": np.zeros(K)}, steps, lr)
    return p


def _reward(Q, y, w_sph=0.5):
    """S(q, y) = log q_y + w_sph q_y / |q|_2, for rows of Q (..., K) and labels y broadcast to them."""
    qy = np.take_along_axis(Q, y[..., None], axis=-1)[..., 0]
    return np.log(qy) + w_sph * qy / np.linalg.norm(Q, axis=-1)


def reinforce_grad(Z, y, sigma, G, rng):
    """REINFORCE estimate of d E[S(softmax(Z + sigma eps), y)] / dZ, (N, K), with G noise draws per
    item and the group-mean baseline: mean_g (R_g - mean R) (Z~_g - Z) / sigma^2."""
    eps = rng.normal(size=(Z.shape[0], G, K))
    Zt = Z[:, None, :] + sigma * eps                                 # (N, G, K) noisy reports
    R = _reward(softmax(Zt), np.broadcast_to(y[:, None], Zt.shape[:2]))
    A = R - R.mean(axis=1, keepdims=True)                            # (N, G) advantages
    return np.mean(A[..., None] * (Zt - Z[:, None, :]), axis=1) / sigma ** 2


def fit_reinforce(X, y, sigma=0.5, G=8, steps=1500, lr=0.02, rng=None):
    """Learner (b): the same linear softmax, trained by gradient ascent on the REINFORCE estimate."""
    rng = np.random.default_rng(0) if rng is None else rng

    def loss(p):
        Z = _logits(p, X)
        g = -reinforce_grad(Z, y, sigma, G, rng) / len(y)            # descend the negated reward
        return float("nan"), {"W": g.T @ X, "b": g.sum(axis=0)}
    p, _ = adam_fit(loss, {"W": np.zeros((K, D)), "b": np.zeros(K)}, steps, lr)
    return p

fit_ce is a softmax’s log loss with nothing but a bias and a linear map (chapter 21’s choice head adds a bilinear term): the gradient in the logits is (P^−Y)/N(\hat P - Y)/N, shape (N, 4), and its products with X and with a column of ones are the gradients in W and b. _reward takes rows of reports of any leading shape, (..., 4), and labels broadcast to the leading shape; np.take_along_axis picks each row’s q~y\tilde q_y. reinforce_grad draws eps of shape (N, G, 4), forms all NGN G noisy reports at once, and computes the rewards R, shape (N, G), the advantages A by subtracting each item’s group mean, and g^\hat g as the mean over the group of advantage times z~−z\tilde z - z, divided by σ2\sigma^2. The mutation that divides by σ\sigma once scales the estimate by σ\sigma, which the 400,000-draw comparison with the pathwise gradient catches; the one that drops the baseline changes nothing in expectation, so test_the_group_baseline_lowers_the_variance checks its spread instead: at z=0z = 0 over 2,000 items, the estimate with the baseline must have less than half the variance of the one without. fit_reinforce passes Adam the negated estimate, since adam_fit descends, and a loss of NaN, since it never computes the reward’s mean; adam_fit only records the loss.

The yardsticks and EM:

def true_calibration(Phat, P):
    """The exact yardsticks, averaged over the items: 1/2 |p_hat - p|_1 and KL(p || p_hat)."""
    l1 = 0.5 * np.abs(Phat - P).sum(axis=1).mean()
    kl = np.sum(P * (np.log(P) - np.log(Phat)), axis=1).mean()
    return float(l1), float(kl)


def em_priors(Phat, pi_src, iters=100, tol=1e-10):
    """Saerens et al.'s EM for the target priors from unlabelled target predictions Phat (N, K):
    reweight p_hat(y | x) by w_y = pi'_y / pi_y, renormalise, and set pi' to the mean."""
    pi = pi_src.copy()
    for _ in range(iters):
        Q = Phat * (pi / pi_src)
        Q = Q / Q.sum(axis=1, keepdims=True)
        new = Q.mean(axis=0)
        if np.abs(new - pi).max() < tol:
            return new
        pi = new
    return pi


def correct_priors(Z, T, prior, pi_src):
    """The label-shift correction of tempered answers: softmax(Z / T) reweighted by prior / pi_src
    and renormalised, as softmax(Z / T + log(prior / pi_src)). The ratio goes on after T."""
    return softmax(Z / T + np.log(prior / pi_src))

true_calibration is the two formulas averaged over rows. test_true_calibration_of_the_truth_is_zero_and_positive_otherwise checks that the truth scores exactly (0,0)(0, 0) against itself and that a flattened copy scores above zero on both. em_priors is the E-step and M-step, one line each: Phat * (pi / pi_src) reweights each column, the division by the row sum renormalises, and the column means are the new priors. test_em_recovers_the_target_priors_from_the_true_model hands it the true conditionals of 20,000 label-shifted inputs and the true source prior and requires π′\pi' within 0.02; the mutation that reweights by π′\pi' twice fails it.

run puts one seed together:

def run(seed, arm, learner, sizes=SIZES, sigma=0.5, steps=None, ms=(0, 25, 100, 400)):
    """One seed of one arm and learner: {shift: metrics} on the target test set, with T fitted on
    the source calibration set; "refit" gives true_l1 after refitting T on m target labels; the
    label shift also reports the EM prior correction. The training set and the learner's noise come
    from one generator, every evaluation set from another, so each learner of a seed is scored on
    the same calibration, test and refit sets."""
    rng = np.random.default_rng(1000 + seed)                         # training set, then the learner's noise
    ev = np.random.default_rng((1000 + seed, 1))                     # calibration, test and refit sets
    t = make_truth(seed, arm)
    X, y, _ = sample(t, sizes["train"], rng)
    if learner == "ce":
        p = fit_ce(X, y, **({"steps": steps} if steps else {}))
    else:
        p = fit_reinforce(X, y, sigma=sigma, rng=rng, **({"steps": steps} if steps else {}))
    Xc, yc, _ = sample(t, sizes["cal"], ev)
    T = fit_temperature(lambda T: choice_nll(_logits(p, Xc), yc, T))
    pi = source_prior(t, ev)
    pi_hat = softmax(_logits(p, Xc) / T).mean(axis=0)               # the model's own source prior
    out = {"T": T}
    for kind in ("none", "covariate", "label", "concept"):
        Xt, yt, Pt = shifted(t, kind, sizes["test"], ev, pi)
        Zt = _logits(p, Xt)
        res = evaluate(softmax(Zt / T), yt, Pt)
        Xm, ym, _ = shifted(t, kind, max(max(ms), 1), ev, pi)          # m target labels for the refit
        res["refit"] = {m: true_calibration(softmax(Zt / (T if m == 0 else fit_temperature(
            lambda T2: choice_nll(_logits(p, Xm[:m]), ym[:m], T2)))), Pt)[0] for m in ms}
        if kind == "label":
            prior = em_priors(softmax(Zt / T), pi_hat)
            res["em_prior_error"] = float(np.abs(prior - t["prior"]).max())
            res["corrected"] = evaluate(correct_priors(Zt, T, prior, pi_hat), yt, Pt)
        if kind == "none" and learner != "ce":
            res["noisy_l1"] = true_calibration(noisy_report(Zt, sigma, rng), Pt)[0]   # before any T
            res["raw_l1"] = true_calibration(softmax(Zt), Pt)[0]
        out[kind] = res
    return out

run uses two generators. The one seeded with 1000+s1000 + s draws the training set and then, for REINFORCE, the noise of every training step and the 256 draws of the noisy report. The one seeded with (1000+s,1)(1000 + s, 1) draws everything the fit is scored on, in program order: the calibration set, the Monte Carlo source prior, and for each shift its test set and its refit sample. The split matters. Were there one generator, the REINFORCE run would consume it between the training set and the calibration set, so the two learners of a seed would be scored on different calibration and test sets, and the calibration set is not a small source of noise: refitting TT for seed 0’s cross-entropy fit on 100 fresh calibration sets of 1,000 moves its true ℓ1\ell_1 with a standard deviation of 0.0019 (experiment_checks.py, straylight and titan), against a test-set standard error of 0.00014. With two generators every learner of a seed meets the same sets, so a per-seed difference between learners is the learners’ difference alone; test_every_learner_of_a_seed_is_scored_on_the_same_sets checks that every set shifted returns is the same array for both. The three REINFORCE runs of one seed draw noise arrays of the same shape whatever σ\sigma is, so they see the same ε\varepsilon at every step, scaled by σ\sigma, and the same data after it: the three σ\sigma rows are one experiment with one knob turned, not three independent repetitions. The refit uses the first mm of one sample of 400 target items for every mm, so the curve’s points are nested, and refit stores only the true ℓ1\ell_1. correct_priors puts the prior ratio on after the temperature, and test_the_prior_correction_goes_on_after_the_temperature checks it against the tempered answer reweighted and renormalised by hand, which the order of exercise (i) fails. test_run_reports_every_shift_and_the_corrections runs a small version (2,000, 500 and 4,000 items, 200 steps) and checks that the EM correction improves on the uncorrected label-shift answer and that concept shift at least doubles the in-distribution error; test_reinforce_learner_runs_small runs REINFORCE for 100 steps.

py/labs/ch20/run_experiment.py runs every seed of every arm and learner, cross-entropy and then REINFORCE at each σ\sigma, and prints one line per shift: the true ℓ1\ell_1 as mean ± sample standard deviation over the seeds, then the means of the KL, the NLL, the equal-width, equal-mass and debiased ECEs, and the refit curve. A label+EM line gives EM’s corrected ℓ1\ell_1 and its worst prior component’s error, a sigma bias line gives REINFORCE’s raw and noisy ℓ1\ell_1 and its mean temperature, and the last block gives per-seed differences, the comparison that removes the variation between truths, each with its tt, the mean over its standard error. Run on straylight with tools/remote/straylight.sh ch20-exp -- bash py/labs/ch20/remote.sh run_experiment.py --seeds 10 --json exp.json, it printed (after uv’s three lines creating the environment; the # lines are each row’s time):

host straylight (x86_64), 2026-09-30 08:39, seeds 0..9
# well ce: 4s
# well rf s=0.25: 85s
# well rf s=0.5: 95s
# well rf s=1.0: 94s
# mis ce: 7s
# mis rf s=0.25: 91s
# mis rf s=0.5: 83s
# mis rf s=1.0: 95s
arm learner        shift             true l1      KL     NLL   ECE-w   ECE-m   ECE-d  refit l1 at m=0/25/100/400
well ce            none       0.0366±0.0059  0.0056  0.9560  0.0157  0.0164  0.0135  0.037/0.061/0.041/0.036
well ce            covariate  0.0377±0.0072  0.0061  0.9346  0.0143  0.0155  0.0111  0.038/0.082/0.040/0.040
well ce            label      0.2444±0.0425  0.2322  0.9893  0.0441  0.0440  0.0467  0.244/0.247/0.244/0.241
well ce            concept    0.3434±0.0218  0.4931  1.4422  0.1915  0.1915  0.2126  0.343/0.324/0.324/0.321
well ce            label+EM   0.0513  (prior error 0.0354)
well rf s=0.25     none       0.0387±0.0065  0.0063  0.9567  0.0152  0.0164  0.0124  0.039/0.061/0.043/0.038
well rf s=0.25     covariate  0.0392±0.0079  0.0066  0.9350  0.0144  0.0152  0.0099  0.039/0.084/0.042/0.041
well rf s=0.25     label      0.2457±0.0417  0.2336  0.9906  0.0438  0.0441  0.0464  0.246/0.248/0.246/0.243
well rf s=0.25     concept    0.3432±0.0207  0.4916  1.4407  0.1912  0.1911  0.2122  0.343/0.324/0.324/0.321
well rf s=0.25     label+EM   0.0519  (prior error 0.0353)
well rf s=0.25     sigma bias: raw report l1 0.0375, noisy report l1 0.0367, T 1.020
well rf s=0.5      none       0.0386±0.0066  0.0063  0.9567  0.0159  0.0170  0.0142  0.039/0.061/0.043/0.038
well rf s=0.5      covariate  0.0392±0.0079  0.0066  0.9350  0.0141  0.0154  0.0105  0.039/0.084/0.042/0.041
well rf s=0.5      label      0.2455±0.0416  0.2331  0.9902  0.0441  0.0447  0.0467  0.245/0.248/0.245/0.242
well rf s=0.5      concept    0.3432±0.0207  0.4914  1.4405  0.1912  0.1912  0.2123  0.343/0.324/0.324/0.321
well rf s=0.5      label+EM   0.0519  (prior error 0.0353)
well rf s=0.5      sigma bias: raw report l1 0.0441, noisy report l1 0.0379, T 1.082
well rf s=1.0      none       0.0385±0.0067  0.0062  0.9566  0.0159  0.0163  0.0122  0.038/0.062/0.043/0.038
well rf s=1.0      covariate  0.0394±0.0077  0.0066  0.9350  0.0142  0.0162  0.0121  0.039/0.084/0.042/0.041
well rf s=1.0      label      0.2451±0.0413  0.2321  0.9892  0.0441  0.0451  0.0474  0.245/0.247/0.244/0.241
well rf s=1.0      concept    0.3434±0.0208  0.4919  1.4410  0.1920  0.1919  0.2129  0.343/0.325/0.324/0.321
well rf s=1.0      label+EM   0.0517  (prior error 0.0352)
well rf s=1.0      sigma bias: raw report l1 0.0779, noisy report l1 0.0411, T 1.284
mis ce             none       0.1295±0.0062  0.0701  0.9897  0.0175  0.0188  0.0182  0.130/0.147/0.133/0.129
mis ce             covariate  0.1454±0.0083  0.0883  1.0016  0.0161  0.0178  0.0154  0.145/0.173/0.152/0.147
mis ce             label      0.3125±0.0877  0.3656  1.1120  0.0701  0.0701  0.0766  0.312/0.323/0.318/0.313
mis ce             concept    0.3535±0.0211  0.5007  1.4206  0.1735  0.1735  0.1938  0.353/0.339/0.341/0.341
mis ce             label+EM   0.1235  (prior error 0.0433)
mis rf s=0.25      none       0.1305±0.0062  0.0710  0.9906  0.0172  0.0181  0.0161  0.131/0.147/0.134/0.130
mis rf s=0.25      covariate  0.1462±0.0087  0.0892  1.0023  0.0165  0.0172  0.0150  0.146/0.173/0.153/0.147
mis rf s=0.25      label      0.3125±0.0885  0.3664  1.1129  0.0697  0.0696  0.0763  0.312/0.323/0.318/0.313
mis rf s=0.25      concept    0.3544±0.0217  0.5030  1.4229  0.1741  0.1740  0.1943  0.354/0.340/0.342/0.342
mis rf s=0.25      label+EM   0.1250  (prior error 0.0445)
mis rf s=0.25      sigma bias: raw report l1 0.1279, noisy report l1 0.1283, T 1.064
mis rf s=0.5       none       0.1304±0.0063  0.0709  0.9905  0.0169  0.0181  0.0162  0.130/0.147/0.134/0.130
mis rf s=0.5       covariate  0.1461±0.0087  0.0891  1.0022  0.0164  0.0173  0.0144  0.146/0.173/0.153/0.147
mis rf s=0.5       label      0.3127±0.0887  0.3666  1.1130  0.0703  0.0702  0.0770  0.313/0.323/0.319/0.314
mis rf s=0.5       concept    0.3543±0.0216  0.5026  1.4224  0.1739  0.1739  0.1944  0.354/0.339/0.342/0.342
mis rf s=0.5       label+EM   0.1251  (prior error 0.0447)
mis rf s=0.5       sigma bias: raw report l1 0.1279, noisy report l1 0.1283, T 1.128
mis rf s=1.0       none       0.1302±0.0064  0.0708  0.9904  0.0167  0.0181  0.0167  0.130/0.147/0.134/0.129
mis rf s=1.0       covariate  0.1459±0.0088  0.0889  1.0020  0.0159  0.0174  0.0151  0.146/0.173/0.153/0.147
mis rf s=1.0       label      0.3131±0.0888  0.3666  1.1130  0.0713  0.0711  0.0781  0.313/0.323/0.319/0.314
mis rf s=1.0       concept    0.3540±0.0214  0.5015  1.4214  0.1739  0.1738  0.1946  0.354/0.339/0.342/0.342
mis rf s=1.0       label+EM   0.1250  (prior error 0.0447)
mis rf s=1.0       sigma bias: raw report l1 0.1380, noisy report l1 0.1289, T 1.338
paired by seed, true l1: mean ± sd over seeds of the per-seed difference, and t
well ce            covariate - none +0.0010±0.0032 t   1.0
well rf s=0.25     covariate - none +0.0006±0.0027 t   0.6   rf - ce (none) +0.0020±0.0020 t   3.2
well rf s=0.5      covariate - none +0.0006±0.0025 t   0.8   rf - ce (none) +0.0020±0.0020 t   3.1
well rf s=1.0      covariate - none +0.0009±0.0024 t   1.2   rf - ce (none) +0.0018±0.0019 t   3.0
mis ce             covariate - none +0.0159±0.0048 t  10.4
mis rf s=0.25      covariate - none +0.0157±0.0050 t   9.9   rf - ce (none) +0.0010±0.0003 t   9.4
mis rf s=0.5       covariate - none +0.0157±0.0050 t   9.9   rf - ce (none) +0.0009±0.0003 t   8.6
mis rf s=1.0       covariate - none +0.0157±0.0051 t   9.8   rf - ce (none) +0.0007±0.0004 t   6.2

On titan, with AEC_REMOTE=titan in front of the same command, the table and the paired block came out identical to straylight’s in every line; only the host line and the timings differ:

host titan.local (arm64), 2026-09-30 08:39, seeds 0..9
# well ce: 5s
# well rf s=0.25: 134s
# well rf s=0.5: 293s
# well rf s=1.0: 312s
# mis ce: 21s
# mis rf s=0.25: 189s
# mis rf s=0.5: 118s
# mis rf s=1.0: 121s

The Mechanism reads the table. From the per-row timings, the grid took about 9.2 minutes on straylight and 20 on titan, each sharing its machine with experiment_checks.py at the time, and nearly all of it is REINFORCE: 1,500 steps, each drawing 40,000 noisy reports of four logits for 5,000 items.

py/labs/ch20/experiment_checks.py produces every other number the Mechanism and the exercises quote about the experiment, in sections: the expansion check, the standard errors and the calibration-set spread, the cross-entropy step count, the label-shift decomposition of P2, exercise (j)’s refits, exercise (h)’s σ\sigma sweep and P4’s annealing check. Its eval_sets replays the evaluation generator of run for a seed, so every section scores on the tables’ own sets, and the label section asserts that its replay reproduces run’s in-distribution error exactly. The annealing section continues each REINFORCE fit from where run left it, with noise from generators of its own, so the continued fits are scored on the same sets as the fit they started from; it runs its 60 fits in parallel (--jobs) and took 279 seconds on straylight with eight processes and 796 on titan with six.

Exercises

(a) Two outcomes, true probabilities q=(0.7,0.3)q = (0.7, 0.3). Compute the linear score’s expected loss, −q⋅p-q \cdot p, for the honest report, for (0.8,0.2)(0.8, 0.2) and for (1,0)(1, 0). Then show that for any qq with q0>1/2q_0 > 1/2 the linear score’s best report is (1,0)(1, 0), and say what happens at q0=1/2q_0 = 1/2.

Answer

Honest: −(0.7⋅0.7+0.3⋅0.3)=−0.58-(0.7 \cdot 0.7 + 0.3 \cdot 0.3) = -0.58. (0.8,0.2)(0.8, 0.2): −(0.56+0.06)=−0.62-(0.56 + 0.06) = -0.62. (1,0)(1, 0): −0.70-0.70 (talos, with expected_loss). Each step away from the truth toward certainty lowers the charge. In general, with p=(p0,1−p0)p = (p_0, 1 - p_0),

−q⋅p=−(q0p0+q1(1−p0))=−q1−p0(q0−q1), -q \cdot p = -\big(q_0 p_0 + q_1 (1 - p_0)\big) = -q_1 - p_0 (q_0 - q_1),

a straight line in p0p_0 with slope −(q0−q1)=−(2q0−1)-(q_0 - q_1) = -(2q_0 - 1). For q0>1/2q_0 > 1/2 the slope is negative, so the loss is least at the largest allowed p0p_0, 1. At q0=1/2q_0 = 1/2 the slope is 0 and every report scores −1/2-1/2: the honest report ties with every dishonest one, the one truth for which honesty is among the best reports, and even then it only ties. A forecaster paid by the linear score rounds every belief to 0 or 1.

(b) Take K=2K = 2, the truth q=(0.7,0.3)q = (0.7, 0.3) and the report p=(0.6,0.4)p = (0.6, 0.4). Compute the expected Brier score directly, by averaging over the two outcomes, and again from the Mechanism’s decomposition. Then show that for K=2K = 2 the ranked probability score is exactly half the Brier score, whatever pp and yy.

Answer

If y=0y = 0 (probability 0.7): (0.6−1)2+(0.4−0)2=0.32(0.6 - 1)^2 + (0.4 - 0)^2 = 0.32. If y=1y = 1 (probability 0.3): (0.6−0)2+(0.4−1)2=0.72(0.6 - 0)^2 + (0.4 - 1)^2 = 0.72. Expected: 0.7⋅0.32+0.3⋅0.72=0.224+0.216=0.440.7 \cdot 0.32 + 0.3 \cdot 0.72 = 0.224 + 0.216 = 0.44. From the decomposition: ∑k(pk−qk)2=0.01+0.01=0.02\sum_k (p_k - q_k)^2 = 0.01 + 0.01 = 0.02 and ∑kqk(1−qk)=0.21+0.21=0.42\sum_k q_k (1 - q_k) = 0.21 + 0.21 = 0.42, total 0.44, the honest report’s 0.42 plus the distance term 0.02 (talos agrees). With two outcomes, p1−[y=1]=(1−p0)−(1−[y=0])=−(p0−[y=0])p_1 - [y = 1] = (1 - p_0) - (1 - [y = 0]) = -(p_0 - [y = 0]), so the Brier score’s two terms are equal and it is 2(p0−[y=0])22 (p_0 - [y = 0])^2. The RPS has one term, k=0k = 0, with F0=p0F_0 = p_0 and [y≤0]=[y=0][y \le 0] = [y = 0]: (p0−[y=0])2(p_0 - [y = 0])^2, half of it. The RPS only differs from the Brier score when there is an order to exploit, which needs three levels or more.

(c) Laya’s proper_reward (commit 6d942c9, laya/common.py) computes its log score as log(q.clamp_min(1e-12)).clamp_min(-9.21): the logarithm is floored at −9.21≈log10−4-9.21 \approx \log 10^{-4}. It adds 0.5 times the spherical score, both as rewards (higher is better). Is the floored log score proper? Does adding the spherical term rescue the sum? Try the truth t=(1−5×10−5, 5×10−5)t = (1 - 5 \times 10^{-5},\ 5 \times 10^{-5}) against the reports tt and (1,0)(1, 0), and say whether it matters for the gates of this book.

Answer

The floor makes every probability below e−9.21=1.0003×10−4e^{-9.21} = 1.0003 \times 10^{-4} earn the same reward, so a forecaster loses nothing by rounding such a probability down to 0 and gains by moving the freed mass to the other outcomes. With tt as above, the floored log reward of reporting tt is (1−5×10−5)log(1−5×10−5)+5×10−5⋅(−9.21)=−0.00051050(1 - 5 \times 10^{-5})\log(1 - 5 \times 10^{-5}) + 5 \times 10^{-5} \cdot (-9.21) = -0.00051050, and of reporting (1,0)(1, 0) it is 0+5×10−5⋅(−9.21)=−0.000460500 + 5 \times 10^{-5} \cdot (-9.21) = -0.00046050: certainty earns 5.0×10−55.0 \times 10^{-5} more. The spherical rewards are ∥t∥=0.9999500013\lVert t \rVert = 0.9999500013 for the honest report and t0=0.9999500000t_0 = 0.9999500000 for certainty, a difference of about 1.3×10−91.3 \times 10^{-9}, far too small to make up the gap. The totals, log plus 0.5 times spherical, are 0.49946450 for the honest report and 0.49951450 for certainty (talos). So neither the floored log score nor the sum is proper: the “sums of proper rules” argument needs every term proper, and the floored term is not. The damage is confined to probabilities below about 10−410^{-4}, which are never learned. A threshold like the t∗=1/100t^* = 1/100 of “Why this layer exists” is a hundred times above that, so the floor does not bias a decision at such a threshold, but it does mean that a head trained this way cannot be trusted to say one in a hundred thousand. Chapter 21’s heads train on the unfloored log loss and get their stability from computing in log space instead.

(d) The reader’s hand-labelled gold set, the optional part of chapter 21’s lab, holds about 200 items per decision. Compute the oracle floor bound for N=200N = 200 and 10 equal-mass bins, with and without the normal approximation. What does an ECE of 0.08 on that set say about a head? How many items would bring the bound down to 0.02 with 10 bins, and what else could be done with 200?

Answer

2/π10/800=0.0892\sqrt{2/\pi}\sqrt{10/800} = 0.0892, and without the normal approximation, from E∣X∣≤EX2\mathbb{E}|X| \le \sqrt{\mathbb{E} X^2}, 10/800=0.1118\sqrt{10/800} = 0.1118. On talos, the lab’s truth scored against itself over 2,000 draws of 200 items gave a mean 10-bin equal-mass ECE of 0.0809, a 95th percentile of 0.1139 and a maximum of 0.1711. So an ECE of 0.08 on 200 items is what a perfectly calibrated head scores on average; it cannot distinguish a calibrated head from one whose true error is several hundredths, and one run above 0.1 is not evidence of miscalibration either. Solving 2/π10/(4N)=0.02\sqrt{2/\pi}\sqrt{10/(4N)} = 0.02 gives N=(2/π)⋅10/(4⋅0.0004)=3,979N = (2/\pi) \cdot 10 / (4 \cdot 0.0004) = 3{,}979 items. With 200: fewer bins (5 bins give a bound of 0.0631, at the cost of a coarser diagram); the debiased estimator, which subtracts the floor; the bootstrap bands of the reliability diagram, which show which bins’ deviations are noise; and, first of all, the log loss and Brier score, which need no bins.

(e) “Measuring calibration” showed that a noul forecaster answering the base rate π\pi every time is calibrated and useless. Let pp be any calibrated noul forecaster, meaning E[y∣p]=p\mathbb{E}[y \mid p] = p, with base rate π=E[y]\pi = \mathbb{E}[y]. Show that its expected one-term Brier score is E[(p−y)2]=π(1−π)−Var(p)\mathbb{E}[(p - y)^2] = \pi(1 - \pi) - \mathrm{Var}(p). What does this say about ranking calibrated forecasters by the Brier score?

Answer

Expand: E[(p−y)2]=E[p2]−2E[py]+E[y2]\mathbb{E}[(p - y)^2] = \mathbb{E}[p^2] - 2\,\mathbb{E}[p y] + \mathbb{E}[y^2]. Since y∈{0,1}y \in \{0, 1\}, y2=yy^2 = y and E[y2]=π\mathbb{E}[y^2] = \pi. For the middle term, condition on pp: E[py]=E[pE[y∣p]]=E[p2]\mathbb{E}[p y] = \mathbb{E}\big[p\, \mathbb{E}[y \mid p]\big] = \mathbb{E}[p^2]. And calibration gives E[p]=E[E[y∣p]]=π\mathbb{E}[p] = \mathbb{E}\big[\mathbb{E}[y \mid p]\big] = \pi. So

E[(p−y)2]=E[p2]−2E[p2]+π=π−E[p2], \mathbb{E}[(p - y)^2] = \mathbb{E}[p^2] - 2\,\mathbb{E}[p^2] + \pi = \pi - \mathbb{E}[p^2] ,

and with E[p2]=Var(p)+(Ep)2=Var(p)+π2\mathbb{E}[p^2] = \mathrm{Var}(p) + (\mathbb{E} p)^2 = \mathrm{Var}(p) + \pi^2,

E[(p−y)2]=π−π2−Var(p)=π(1−π)−Var(p). \mathbb{E}[(p - y)^2] = \pi - \pi^2 - \mathrm{Var}(p) = \pi(1 - \pi) - \mathrm{Var}(p) .

Among calibrated forecasters of the same event, the Brier score is lower by exactly the variance of the forecasts: the more a calibrated forecaster commits, the better it scores, and the base-rate forecaster, with Var(p)=0\mathrm{Var}(p) = 0, scores worst of all, π(1−π)\pi(1 - \pi). On talos, 400,000 draws with π≈0.3\pi \approx 0.3 gave Brier scores of 0.2100 for the base rate, 0.1750 for forecasts drawn from a Beta(1.5, 3.5) distribution and 0.1052 for a Beta(0.3, 0.7) one. With π=0.3\pi = 0.3 and the distributions’ variances, αβ/((α+β)2(α+β+1))=0.0350\alpha\beta/\big((\alpha + \beta)^2(\alpha + \beta + 1)\big) = 0.0350 and 0.1050, the formula gives 0.2100, 0.1750 and 0.1050, each within 0.0002 of the simulation. ECE sees these three forecasters as equal; the Brier score orders them by how much they say.

(f) Take K=2K = 2 and one item whose logits are (z1,z2)(z_1, z_2), with label 1, and write Δ=z1−z2\Delta = z_1 - z_2. Show directly that ℓ(β)=−logσ(βΔ)\ell(\beta) = -\log \sigma(\beta \Delta), compute ℓ′′(β)\ell''(\beta), and check it against the Mechanism’s Varpβ(z)\mathrm{Var}_{p_\beta}(z). Then fit a temperature to two items: one right with margin Δ=2\Delta = 2 and one wrong with margin Δ=−1\Delta = -1. Find the minimising β\beta from a polynomial equation, and explain why the wrong item keeps the answer away from the floor.

Answer

pβ,1=eβz1/(eβz1+eβz2)=1/(1+e−βΔ)=σ(βΔ)p_{\beta,1} = e^{\beta z_1}/(e^{\beta z_1} + e^{\beta z_2}) = 1/(1 + e^{-\beta\Delta}) = \sigma(\beta\Delta), so ℓ=−logσ(βΔ)\ell = -\log\sigma(\beta\Delta). With ddxlogσ(x)=1−σ(x)=σ(−x)\frac{d}{dx}\log\sigma(x) = 1 - \sigma(x) = \sigma(-x), ℓ′(β)=−Δσ(−βΔ)\ell'(\beta) = -\Delta\,\sigma(-\beta\Delta), and with σ′(x)=σ(x)σ(−x)\sigma'(x) = \sigma(x)\sigma(-x), ℓ′′(β)=Δ2σ(βΔ)σ(−βΔ)≥0\ell''(\beta) = \Delta^2 \sigma(\beta\Delta)\sigma(-\beta\Delta) \ge 0. Under pβp_\beta the logit is z1z_1 with probability s=σ(βΔ)s = \sigma(\beta\Delta) and z2z_2 with 1−s1 - s, a two-point distribution whose variance is (z1−z2)2s(1−s)=Δ2s(1−s)(z_1 - z_2)^2 s (1 - s) = \Delta^2 s(1 - s): the same.

For the two items, NLL(β)=12(−logσ(2β)−logσ(−β))\mathrm{NLL}(\beta) = \frac{1}{2}\big(-\log\sigma(2\beta) - \log\sigma(-\beta)\big), and setting the derivative 12(−2σ(−2β)+σ(β))\frac{1}{2}\big(-2\sigma(-2\beta) + \sigma(\beta)\big) to zero gives σ(β)=2σ(−2β)\sigma(\beta) = 2\sigma(-2\beta). With u=eβu = e^\beta, σ(β)=u/(1+u)\sigma(\beta) = u/(1 + u) and σ(−2β)=1/(1+u2)\sigma(-2\beta) = 1/(1 + u^2), so u(1+u2)=2(1+u)u (1 + u^2) = 2(1 + u), that is u3−u−2=0u^3 - u - 2 = 0, whose real root is u=1.5214u = 1.5214, so β=logu=0.4196\beta = \log u = 0.4196 and T=2.383T = 2.383. fit_temperature returns T=2.3831T = 2.3831 on talos, lowering the NLL from 0.7201 at T=1T = 1 to 0.6420. The right item alone would drive TT to the bottom of the bracket (0.05, the default lo, on talos), since its loss falls toward 0 as β\beta grows. The wrong item’s loss, −logσ(−β)=β+log(1+e−β)-\log\sigma(-\beta) = \beta + \log(1 + e^{-\beta}), grows without bound, about linearly in β\beta, so sharpening eventually costs more on the wrong item than it saves on the right one. With no wrong item there is no such balance, the case “Why the result is floored” treats.

(g) Let REINFORCE learn its own noise scale: the report is softmax(z+σε)\mathrm{softmax}(z + \sigma\varepsilon) with logσ\log \sigma a parameter beside zz. Derive the score-function estimate of the gradient in logσ\log\sigma and check that its baseline term has mean zero. Then, for the log reward alone, say which way the expected gradient pushes σ\sigma, and what that does to the estimator of the gradient in zz.

Answer

With z~=z+σε\tilde z = z + \sigma\varepsilon, the log-density is −Klogσ−K2log2π−∥z~−z∥2/2σ2-K \log\sigma - \frac{K}{2}\log 2\pi - \lVert \tilde z - z \rVert^2 / 2\sigma^2. Its derivative in σ\sigma is −K/σ+∥z~−z∥2/σ3-K/\sigma + \lVert \tilde z - z \rVert^2/\sigma^3; multiplying by dσ/dlogσ=σd\sigma/d\log\sigma = \sigma and writing z~−z=σε\tilde z - z = \sigma\varepsilon,

∂∂logσlogπ(z~)=∥ε∥2−K, \frac{\partial}{\partial \log\sigma} \log \pi(\tilde z) = \lVert \varepsilon \rVert^2 - K ,

so the estimate is 1G∑g(Rg−R¯)(∥εg∥2−K)\frac{1}{G}\sum_g (R_g - \bar R)(\lVert\varepsilon_g\rVert^2 - K), which the group baseline shrinks by (G−1)/G(G-1)/G, as it does the estimate in zz. The baseline term has mean zero because ∥ε∥2\lVert\varepsilon\rVert^2 is a sum of KK squared standard normals, with mean KK.

For the log reward, the Mechanism’s computation gives the expected reward p⋅z−g(σ)p \cdot z - g(\sigma) with g(σ)=Eε[LSE(z+σε)]g(\sigma) = \mathbb{E}_\varepsilon[\mathrm{LSE}(z + \sigma\varepsilon)]. As a function of σ\sigma over the whole real line, gg is convex (a convex function of an affine function of σ\sigma, averaged over ε\varepsilon) and even (ε\varepsilon and −ε-\varepsilon have the same distribution). A convex even function is least at 0, since g(0)≤12g(σ)+12g(−σ)=g(σ)g(0) \le \frac{1}{2}g(\sigma) + \frac{1}{2}g(-\sigma) = g(\sigma), and it does not decrease on σ≥0\sigma \ge 0: for 0≤σ1<σ20 \le \sigma_1 < \sigma_2, σ1\sigma_1 lies between −σ2-\sigma_2 and σ2\sigma_2, so g(σ1)≤max(g(−σ2),g(σ2))=g(σ2)g(\sigma_1) \le \max(g(-\sigma_2), g(\sigma_2)) = g(\sigma_2). So the expected reward never rises with σ\sigma, and a learned σ\sigma is pushed toward 0: under a proper reward the model gains nothing from its own noise, and as σ\sigma falls the Mechanism’s bias goes with it. The estimator in zz stays usable on the way down because of the baseline. Its terms are (Rg−R¯)εg/σ(R_g - \bar R)\,\varepsilon_g/\sigma. For small σ\sigma, Rg≈R(z)+σ∇R⋅εgR_g \approx R(z) + \sigma\, \nabla R \cdot \varepsilon_g, so Rg−R¯≈σ∇R⋅(εg−ε¯)R_g - \bar R \approx \sigma\, \nabla R \cdot (\varepsilon_g - \bar\varepsilon) and each term is about (∇R⋅(εg−ε¯))εg\big(\nabla R \cdot (\varepsilon_g - \bar\varepsilon)\big)\,\varepsilon_g, of order 1 whatever σ\sigma is. Without the baseline the terms are Rgεg/σR_g\, \varepsilon_g / \sigma, and the part R(z)εg/σR(z)\,\varepsilon_g/\sigma, zero in expectation, has a variance that grows like 1/σ21/\sigma^2. The experiment fixes σ\sigma because RLCD, as Laya reads it, fixes it, and because the question is how the bias depends on it.

(h) The tables try three noise scales. Before running anything, use the Mechanism’s second-order formula to predict how the raw report’s true ℓ1\ell_1, the noisy report’s, the fitted TT and the true ℓ1\ell_1 after TT move as σ\sigma goes from 0.1 to 2. Then run run(0, "well", "rf", sigma=s, ms=(0,)) for s∈{0.1,0.25,0.5,1,2}s \in \{0.1, 0.25, 0.5, 1, 2\}, plot the four numbers against σ\sigma, and say where the prediction held.

Answer

The prediction: the noisy report’s mean is what the reward pins to the truth, so its ℓ1\ell_1 should stay near cross-entropy’s whatever σ\sigma is; the raw report is sharpened by about σ2f⊙(∥f∥2−f)\sigma^2 f \odot (\lVert f \rVert^2 - f), so its ℓ1\ell_1 should grow, quadratically while σ\sigma is small; the temperature should rise above 1 to undo the sharpening; and if the sharpening were exactly a temperature, the ℓ1\ell_1 after TT would not depend on σ\sigma at all. Seed 0 gave, identically on straylight and titan (the sigma section of experiment_checks.py):

sigma   raw l1   noisy l1   T       after T
0.1     0.0346   0.0345     1.011   0.0344
0.25    0.0356   0.0350     1.030   0.0345
0.5     0.0423   0.0364     1.093   0.0347
1.0     0.0766   0.0399     1.298   0.0346
2.0     0.1561   0.0435     1.866   0.0336

The raw report’s ℓ1\ell_1 grows, and so does T−1T - 1 (0.011, 0.030, 0.093, 0.298, 0.866), but not as σ2\sigma^2: doubling σ\sigma from 0.25 to 0.5 multiplied T−1T - 1 by 3.1, and from 0.5 to 1 by 3.2, against the formula’s 4, and from 1 to 2 by 2.9. The formula is a small-σ\sigma statement, and the Mechanism’s single-item check already showed it overshooting at σ=1\sigma = 1. The noisy report’s ℓ1\ell_1 drifts up slowly, from 0.0345 to 0.0435. Two causes are possible and this run does not separate them: the spherical term moves the optimum off the log term’s exact condition, and a linear zz may be unable to meet that condition at every xx at once, since the noisy mean of a linear softmax is not itself a linear softmax. After the temperature, the five runs sit within 0.0011 of each other: on this seed one number absorbed almost all of the bias, even at σ=2\sigma = 2, where the raw report is off by 0.156. The five runs share their noise draws (“The experiment”), so the comparison between them is paired; a second seed is the check that the pattern is not this seed’s.

(i) run corrects label shift with softmax(Zt / T + log(prior / pi_hat)): temperature first, then the prior ratio. A reader writes softmax((Zt + log(prior / pi_hat)) / T) instead. What correction does that apply, in which direction is it wrong when T>1T > 1, and which order does Bayes’ rule ask for? Which probabilities must EM’s E-step use?

Answer

Dividing the sum by TT gives softmax(z/T+1Tloga)\mathrm{softmax}(z/T + \frac{1}{T}\log a) with a=π^′/π^sa = \hat\pi'/\hat\pi_s: it multiplies each probability by ay1/Ta_y^{1/T} instead of aya_y. With T>1T > 1 the ratio is raised to a power below 1, so every prior ratio is pulled toward 1 and the correction is too weak; with T<1T < 1 it is too strong. For T=1.3T = 1.3 and a class whose prior quadrupled, the corrected odds move by 41/1.3=2.94^{1/1.3} = 2.9 instead of 4. Bayes’ rule, as the Mechanism derived it, multiplies p(y∣x)p(y \mid x) by aya_y, and the model’s estimate of p(y∣x)p(y \mid x) is its calibrated answer, softmax(z/T)\mathrm{softmax}(z/T), so the ratio goes on after the temperature. For the same reason the E-step reweights the tempered answers, and the source prior in the ratio is the mean of the tempered answers on the source, which is what run passes to em_priors as pi_hat. An EM run on untempered answers estimates the priors of a different, miscalibrated model.

(j) In the refit columns of the tables, a temperature refitted on 25 target labels is often worse than the source temperature, even with no shift at all. Why can more information make the answer worse, and how many labels does a refit need before it helps?

Answer

A temperature fitted on mm labels is an estimate with a sampling spread, and when the source temperature is already right, any spread can only add error: the true ℓ1\ell_1 is smallest near the right TT and rises on both sides of it. On seed 0 of the well-specified arm with cross-entropy, the source temperature is 1.005 and the true ℓ1\ell_1 at it 0.0309. Refitting on 200 independent samples of in-distribution labels gave temperatures whose 5th to 95th percentiles ran from 0.560 to 1.551 at m=25m = 25, 0.818 to 1.245 at m=100m = 100 and 0.908 to 1.149 at m=400m = 400, with mean true ℓ1\ell_1 of 0.0711, 0.0444 and 0.0356; the refit was worse than the source temperature in 99%, 96% and 90% of the draws (the refit section of experiment_checks.py, identical on straylight and titan). The NLL of 25 items is a flat and noisy function of TT, and its minimum lands wherever those 25 labels put it. A refit pays only when the shift moves the right temperature by more than the refit’s spread, which at 400 labels is still about ±0.12\pm 0.12 here; under label and concept shift, where one number cannot fix the error, the tables show it barely moving at any mm.

Lab

Implement the stubs in py/labs/ch20/starter.py and run

make lab CH=20 IMPL=mine

It runs py/labs/ch20/test_scoring.py against your functions. IMPL=ref runs the same tests against tinygpt.decide. Three more scripts in the directory run on the reference and print the numbers of the sections above: calibration_lab.py, run_experiment.py and experiment_checks.py. The chapter prints or quotes their output, and the paragraphs below say what the test file checks and what to change in each script.

The test file, py/labs/ch20/test_scoring.py, pins the scoring rules, the ECEs and the temperature search. Implement log_loss, brier, spherical (as a loss, negated) and rps over rows of answers; ece_equal_width, ece_equal_mass and ece_debiased; and fit_temperature. The tests check each rule on a worked case, then check properness and strict properness numerically against random truths with expected_loss’s construction, and the RPS against the Brier scores of its cumulative events. For the ECEs: a calibrated forecaster scores small but positive, and less with a hundred times the data; a forecaster always 90% sure and right 60% of the time scores 0.3 on every estimator; equal-width bins are cut by value, with a confidence of exactly 1 in the last bin; equal-mass bins by count in sorted order; and the debiased estimate comes out below the plain root mean square. For the temperature: the search finds the minimum of (logT−log2.5)2(\log T - \log 2.5)^2 to a relative 10−610^{-6}, never returns less than 10−310^{-3} however low lo is set, and on logits whose truth is the same logits divided by 3 finds a TT between 2 and 4.5 that lowers the NLL it fits. top_label, reliability, choice_nll and auroc are the reference’s, used by later sections and by chapter 21.

py/labs/ch20/calibration_lab.py is the oracle experiment of “Measuring calibration”, and runs on the reference. Run it, then change it: fit a temperature to the overconfident copy on half of each draw with fit_temperature and choice_nll, and print the other half’s ECE beside the truth’s.

py/labs/ch20/run_experiment.py runs the controlled experiment on the reference and prints the tables of “The experiment”. Start small, from py/: OPENBLAS_NUM_THREADS=1 PYTHONPATH=. uv run python labs/ch20/run_experiment.py --seeds 2 --sigmas 0.5 took 56 seconds on talos. The full grid, ten seeds and three noise scales, took about 9 minutes on straylight; run it on two machines with tools/remote/straylight.sh ch20-exp -- bash py/labs/ch20/remote.sh run_experiment.py --seeds 10, adding AEC_REMOTE=titan (or dixie, orion) for the second, and read which comparisons between close numbers hold on both. Before you run it, write down your own predictions for the changes below; then change it. Raise the misspecified arm’s pair scale from 0.05 to 0.12 and see whether P1’s second half becomes plain. Replace _reward with the linear score of “Proper scoring rules”, q~y\tilde q_y alone, and watch what REINFORCE does to the raw report and to the fitted temperature. Then run py/labs/ch20/experiment_checks.py the same way (its anneal section is the slow one; --jobs sets its processes), which prints every other number the Mechanism quotes about the experiment, P4’s annealing check among them, and compare your machine’s digits with the Mechanism’s. Last, extend that check: give REINFORCE a learning rate that decays over all 1,500 steps instead of dropping once, and see whether the well-specified arm’s small residual gap closes.

Further reading

results matching ""

    No results matching ""