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 (a false positive: an interruption and a delay); letting a harmful call run unasked costs (a false negative). If is the probability that the call is harmful, asking has expected cost , since the ask was wasted exactly when the call was harmless, and not asking has expected cost . Asking is the cheaper action when
If a missed harmful call costs 99 times as much as a needless prompt, : ask whenever the chance of harm exceeds one in a hundred. The derivation took 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 , the statement is true a fraction 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 , shape , be a distribution over outcomes, non-negative and summing to 1, and let be the outcome that happens. A scoring rule is the charge; here every rule is written as a loss, so lower is better. If the outcome is drawn from a distribution , also of shape , the expected charge for reporting is
is proper if for every and every : reporting the distribution the outcome is really drawn from is never beaten. It is strictly proper if, in addition, equality holds only at : every other report is beaten. A forecaster who believes and wants to minimise its expected charge reports 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 over outcomes drawn from is pushed toward , and the gates need exactly that number, since the threshold 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, , chapter 4’s surprise of the outcome under the forecast. Its expectation is chapter 4’s cross-entropy from to , which splits into two parts by adding and subtracting :
does not depend on the report. Gibbs’ inequality (chapter 4) says , with equality only at . So , with equality only at : 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 has expected charge , 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, , the squared distance between the forecast and the one-hot vector of the outcome, between 0 and 2. By linearity of expectation, . Expand one term:
An indicator is 0 or 1, so , and its expectation is the probability of its event, . So
where the last step adds and subtracts : is , and is what is left. Summing over ,
The second sum is fixed by ; the first is a sum of squares, zero only when every . 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 , the probability of the outcome divided by the forecast’s Euclidean length; as a loss, , between and 0. The expected reward is
Cauchy–Schwarz bounds it, and the bound’s proof also gives its equality case. For nonzero vectors and , the squared length of the difference of their unit vectors is
so , with equality only when the two unit vectors coincide, that is when for some . The expected reward is therefore at most , and attains it: . Any maximiser has , and both sum to 1, so , and . Strictly proper. The division by is what makes it so: a forecast spread thin has a small length (the uniform forecast has length ), 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 and 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 puts its bulk one level from the truth and two. With the forecast’s cumulative distribution, the ranked probability score is
where the term is left out because always. Each term is a one-term Brier score for the binary event , forecast with probability . Under that event has probability , and the Brier expansion above, with the event in place of , gives each term’s expectation:
Summing, , least exactly when for every . The cumulative values determine the forecast, with and , so means . Strictly proper. For the two forecasts above, and against the steps give for and for (talos). The reason is visible in a forecast that puts all its mass on one level : then , which differs from exactly for the from to , so . 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, , which sounds as reasonable as any. Its expectation is , a linear function of . Let be a most likely outcome, . Then
with equality at , all the mass on . The honest report scores , and , with equality only when every equals . So unless is uniform over the outcomes it allows, reporting certainty on the mode strictly beats reporting . 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 is strictly proper, proper and , then is strictly proper: , a sum of a term that is positive for 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 (exercise (c)).
Why cross-entropy training seeks calibration
Properness is about one distribution. Training faces one per input: a state has a true conditional distribution over the answers, shape , and the model gives its own, , computed from parameters . The same letters as the last section: the truth, the report. Over the population of inputs, the expected log loss is
the log score’s decomposition applied inside the outer expectation, one at a time. The entropy term does not depend on , and each KL term is at least 0, with equality only where . So if some reproduces the true conditional for every input, it minimises , and every minimiser reproduces it, except on a set of inputs of probability 0.
A model that reproduces the truth is calibrated. Let be its top answer and its confidence. The event is decided by alone, so the probability of being right on it can be computed by first conditioning on (the tower property of conditional expectation) and then using :
because given , the chance that equals the fixed answer is . With , and then the definition of as the probability of the top answer, the right-hand side is
The same argument works for any probability the model reports and the event it is about: among the yes-or-no answers that say , the statement is true a fraction 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 . 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 , shape (chapter 13’s distillation gradient at ; fit_ce below uses it, and chapter 21 derives it for its choice head), so the gradient in a per-option bias is the column sums of , and here is not penalised. At a stationary point of the training loss that gradient is zero, so for every option
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: 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 , the statement is true a fraction of the time. For a choice this is usually checked on the top answer: with confidence and top answer , calibrated means for every . 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 , 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 and correct the gold label.
With finite data the condition cannot be checked at each , since no two confidences are equal. So the items are grouped into bins by confidence. For bin , holding of the items, let be its mean confidence and the fraction of its items whose event happened. A reliability diagram plots each bin as the point ; 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:
Two ways of drawing the bins are in use. Equal width cuts into intervals of width ; Guo, Pleiss, Sun and Weinberger’s 2017 study of neural-network calibration, whose recommended remedy is the temperature scaling below, reports it with . Equal mass sorts the items by confidence and cuts them into runs of (nearly) equal count. Confidences are not spread evenly over : 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 with confidences and outcomes . Calibrated means that, given the confidences, each is a Bernoulli draw with probability , independently. Then
has mean 0, and, since independent terms’ variances add and ,
is at most 1/4. Write for the bin’s mean confidence: , 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 , the last because is largest at . A variable with mean 0 is not 0, and its absolute value has a positive mean. Two estimates of that mean:
- For any distribution, , because the difference is . So , for every .
- For a bin of a few dozen items or more, is a mean of many independent terms and nearly normal (the central limit theorem). For , by symmetry and ,
Summing the bins with their weights, and using the normal approximation and ,
With equal-mass bins, and , so
For any other binning with non-empty bins, Cauchy–Schwarz gives , 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 and grows like . 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 to 0.0077 at , a factor of 17.7 for a factor of 300 in , against , 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 with , so the sum is , and by Jensen’s inequality for the concave square root, , where is exactly the sample’s mean , since the bins hold equal numbers of items. This truth’s mean is 0.2096 (200,000 items, talos), which shrinks the bound by , to 0.0258 at . 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 on, because its error does not shrink with data, but at 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, . With and the confidences fixed,
the bin’s true squared error plus the noise. The noise can be estimated from the bin itself. Suppose the bin’s outcomes are independent draws with one probability , and write for their mean. Then and , so
using , and collecting terms,
Dividing by ,
an unbiased estimate of the noise term. Subtracting it in every bin estimates the squared calibration error without the floor,
where the sum can come out negative by chance, when a bin’s estimated noise exceeds its squared gap, hence the . 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 error, the root of a weighted mean square, so its numbers are not on the scale of the ECEs beside it in the lab’s table. It assumed one per bin; if the true probabilities in a bin have mean and variance , then , and repeating the computation above gives : 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 in the lab. The root of the plain weighted mean square, the same quantity with nothing subtracted, is 0.1598 for the truth at against a debiased 0.0280, and 0.0103 against 0.0032 at (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, every time, is calibrated: among its answers that say , which are all of them, the statement is true a fraction of the time. It is also useless, because it ranks no state above another. On talos, 10,000 items with 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 scores, give each its rank from 1, with tied scores sharing the average of their ranks, and let 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 , with ties averaged, summing to ; 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 . So
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 assumes calibration, and it is only worth having if the probabilities also discriminate.
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 , and the truth’s bars are 0.07 to 0.12 long, about the 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 , shape , the model answers for a temperature . Dividing by a positive number keeps the logits’ order, so the top answer, and with it the accuracy, is the same at every . pulls the distribution toward uniform, sharpens it, and the limits are the uniform distribution as and all the mass on the top answer as . Models train at (chapter 21’s exercise (i) says why), and 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 fitted to one sample is tuned to that sample.
The NLL is convex in . For one item with label , write . Its log loss is
Differentiate the log-sum-exp: its derivative is , so
Next, each probability’s derivative: , so and . Then
the variance of the logits under the model’s own distribution. is convex in , 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 gives every option positive probability. With soft targets , the first term becomes , still linear in , and the second derivative is the same. A logistic answer is the softmax of the two logits , 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 . A convex function of on 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 . It need not be convex there, but unimodality is all a golden-section search needs. Searching on treats 0.1 and 10 alike, and the default bracket is symmetric about in it, and .
Golden-section search keeps a bracket known to contain a minimiser, and two interior points . If , not every minimiser can lie beyond : were every minimiser beyond , would be strictly falling on and . So a minimiser lies in , which becomes the bracket. Otherwise one lies in . Each step evaluates at one new point only if the surviving interior point lands where the next step needs one. With bracket length , put and . After keeping , of length , the next step wants its upper interior point at , and the old sits at . They coincide when
the positive root; by symmetry the other case needs the same . Every step then costs one evaluation and shrinks the bracket by the factor . fit_temperature runs 80 steps: the bracket of starts wide and ends 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 is the item’s largest logit and some other logit is smaller, for every , and the NLL keeps falling as . The search then runs to the bottom of its bracket. fit_temperature raises the bracket’s bottom to T_MIN whatever lo it is given, and clamps its answer into the bracket, since need not give back : 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 minimise the fitting split’s NLL over the bracket. The default bracket contains , so . The search keeps a minimiser inside its bracket at every step and returns a point of the final bracket, within about of in , so the fitted temperature satisfies the same inequality up to that rounding. The inequality is strict unless is already a minimiser: if at , a small step in one direction lowers the NLL. Setting the mean of to zero gives the condition the fitted temperature meets when it lands inside the bracket,
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. was chosen for a different sample, and on the evaluation split its NLL can come out higher than at . 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 undoes the doubling, one draw of 3,000 items split in half gives (talos): at on the fitting half, positive, so lowering , raising , helps; a fitted ; 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 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 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 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 draws one truth (make_truth). Inputs are , shape , and there are classes. With weights of shape , entries drawn from , and a bias of shape from , the well-specified arm has
The misspecified arm adds a term the learners cannot represent: with the 120 products for , shape , and of shape from ,
The scale 0.05 leaves a linear model a usable approximation rather than a hopeless one. Both learners are linear softmax models, with of shape and of shape , both started at 0: in the first arm the truth is in their family, in the second it is not. Each seed trains on 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 the model’s logits , shape , are perturbed to with ; the report is , and it earns the reward
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 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 . 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 are a Gaussian with mean and covariance , whose density is
Its log is , and differentiating in gives , so
Write the reward of a draw as ; it depends on only through the draw. Chapter 13’s log-derivative trick, with an integral over in place of the sum over replies, moves the gradient onto the density:
(Moving inside the integral is allowed here: the density is smooth in and its Gaussian tails dominate the reward, which is bounded above and grows no faster than linearly in below.) A constant baseline subtracts nothing in expectation, because ; this is chapter 13’s argument, where did the same work. With draws , rewards and their mean , the estimate is
contains itself, so it is not a constant. Chapter 13’s leave-one-out step repairs it: with the mean of the other rewards, , and is independent of draw , so : the true gradient times for . 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 in the denominator).
The logits of all items are , with of shape and of shape . The objective is the mean reward, , and depends on through , so and . The chain rule then gives, with stacked into of shape ,
This reward is differentiable, so there is a second route to the same expectation: , 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 differs from 1 by ) against finite differences of the reward. REINFORCE never differentiates ; 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 , 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 .
For (b), fix , write for , shape , and for the expected reward of report . The population objective at is . At that is , and strict properness makes its only maximiser: the same optimum as (a). At the report is a random vector, and no choice of makes every draw equal . For the log term the optimum can be found exactly. Since , with ,
The gradient of is the softmax, so the gradient in is . is convex, an average of convex functions is convex, and so the objective is concave: its stationary points are its maxima, and they satisfy
Under the log reward it is the noisy report’s mean that the optimum makes equal to the truth, exactly; the noise-free report , 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 .
How far is from its noisy mean? Write and expand one component to second order around :
Take the expectation: removes the first-order term, 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 :
The softmax’s first derivatives are . Differentiate once more in by the product rule:
Sum over . The first part is , and the second is , so
with the elementwise product. , 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 . To make the flattened mean equal , the optimum’s raw report must be sharper than , overconfident, by an amount of order while 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 . How good is the approximation? For , ; its noisy mean over 200,000 draws and the second-order formula are 0.4634 and 0.4635 at , 0.4533 and 0.4518 at , and 0.4245 and 0.4052 at (experiment_checks.py, the same on talos, straylight and titan). At 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: with , and as before. If at every , the error is zero under any distribution of , 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 averaged over the source , 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 with , each product is , so the misspecified truth gains logit terms linear in and a constant, none of which the source fit saw.
Label shift moves the class priors and keeps the class-conditional inputs: , and where the source had . By Bayes’ rule in the target, and then in the source, :
cancels. In logits, : the correction adds the constant vector , shape , to every item’s logits, and a model’s answer can be corrected the same way once is known. shifted builds the target by rejection: draw from the source and keep it with probability . The kept pairs have joint density proportional to , so their conditional is renormalised, the formula above; their prior is proportional to ; and the acceptance depends on alone, so is untouched. The source prior has no closed form and is estimated from 200,000 draws; is a Dirichlet(1, 1, 1, 1) draw per seed.
Estimating by EM. A deployed gate sees target inputs without labels. Saerens, Latinne and Decaestecker (2002) estimate from them by expectation maximisation. The target inputs have the mixture density , so the log-likelihood of unlabelled is
using again; the last sum does not depend on , so only the model’s conditional and the source prior are needed. Treat the missing labels as latent. Given a current estimate , the E-step computes each item’s posterior over its label under that estimate,
the label-shift correction of the model’s answer, with of shape and rows summing to 1. The M-step maximises the expected complete-data log-likelihood, , over distributions . The second term does not involve . With a Lagrange multiplier for , setting the derivative of in to zero gives , so ; summing over , , and
the mean corrected answer. (It is a maximum: is a positive combination of logarithms, concave in .) Why iterating never lowers : for each item, with and the E-step’s weights computed at , the concavity of (Jensen’s inequality over the distribution ) gives
with equality at , where is the same for every . Summed over , the right side is minus a term that does not depend on : a lower bound on that touches it at . The M-step raises the bound, so . em_priors starts from the source prior and stops when no component moves by more than , or after 100 steps. In run, in both the E-step and the correction is the model’s own source prior, , the mean of its tempered answers on the source calibration set, not the true : 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 again.
Concept shift changes the conditional itself: , with , a random orthogonal matrix and block-diagonal with eight rotations by , so turns each input’s component in each of eight orthogonal planes by within that plane, and the angle between any and is (“The experiment” shows ). The inputs are drawn exactly as in the source. And since is invariant under any orthogonal map, even 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 .
The yardsticks. For each target test item the program holds the true and the model’s , both shape . The true calibration error is the mean over the test items of
beside the mean of . The first is the largest error the model makes on the probability of any event. For a set of classes , 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 ; and = the classes where attains it. So : 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”, . Both are exact for each item; the mean over 20,000 items is a Monte Carlo estimate over , with a standard error of 0.00014 for the true of seed 0’s cross-entropy fit at 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 labelled items drawn from the target ( keeps the source’s), and reports the true at each. For label shift the table also reports EM’s correction: , computed by correct_priors as softmax(Zt / T + log(prior / pi_hat)). For REINFORCE it reports the in-distribution true of the raw report and of the noisy report’s mean, 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 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 the reward is paid on the noisy report, so the raw report is biased, overconfident, and the bias grows with ; 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 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 , the mean in units of its own standard error. With ten seeds, 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 () and +0.0006 to +0.0009 for REINFORCE ( from 0.6 to 1.2). In the misspecified arm it is +0.0159 ± 0.0048 for cross-entropy (), 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 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 , from 0.024 to 0.306 between the 5th and 95th percentiles of items); the true 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 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 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 ; 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 () at , +0.0020 ± 0.0020 () at 0.5 and +0.0018 ± 0.0019 () at 1, above 0 on nine seeds of ten; the three 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 ( 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.pymeasures 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 ( 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 ( from −6.4 to −11.3, every seed improving) and weaker in the well-specified one (−0.0014 ± 0.0022, , 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, from 2.1 to 2.5, well specified; +0.0002 to +0.0003, from 0.6 to 1.3, misspecified). Whether running on at that rate widens the gap, this check does not settle: 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 , before any temperature, was 0.0375, 0.0441 and 0.0779 for = 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 : one scale factor removed almost all of the bias. In the misspecified arm the bias disappears into the fit’s own error at small (raw 0.1279 against noisy 0.1283 at = 0.25) and shows at = 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 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 exactly: it scores one report against every outcome at once, rule(np.tile(p, (K, 1)), np.arange(K)), and weights the losses by . The lab’s properness tests use the same construction: for 50 random truths they check that 20 random perturbations each score no better than itself, and that a report at distance 0.02 from 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, . _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 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 , 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 and , on . When fc <= fd the bracket becomes : 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 , which falls all the way down, with lo at , 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 (a masked option) would be , 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 lands in class when , and counting the below gives (np.minimum(…, 3) guards against rounding to just under 1). “bound” is ; “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: , , then for the misspecified arm, then the covariate shift’s direction, the label shift’s priors and the rotation’s basis. Because is drawn in the middle, the two arms of one seed share and but not the shifts. The rotation is built as the Mechanism describes it: np.linalg.qr of a standard normal matrix gives an orthogonal , the loop fills eight blocks of with , and is orthogonal because each factor is. test_truth_is_deterministic_and_the_rotation_is_orthogonal checks and that a random direction moves: for a unit vector whose squared components in the eight planes are , exactly, whatever 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 .
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 and keeps each with probability a[y], until 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 within 0.02, and the stored conditionals average to as well, which is what 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 , 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 . reinforce_grad draws eps of shape (N, G, 4), forms all noisy reports at once, and computes the rewards R, shape (N, G), the advantages A by subtracting each item’s group mean, and as the mean over the group of advantage times , divided by . The mutation that divides by once scales the estimate by , 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 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 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 within 0.02; the mutation that reweights by 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 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 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 for seed 0’s cross-entropy fit on 100 fresh calibration sets of 1,000 moves its true 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 is, so they see the same at every step, scaled by , and the same data after it: the three rows are one experiment with one knob turned, not three independent repetitions. The refit uses the first of one sample of 400 target items for every , so the curve’s points are nested, and refit stores only the true . 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 , and prints one line per shift: the true 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 and its worst prior component’s error, a sigma bias line gives REINFORCE’s raw and noisy and its mean temperature, and the last block gives per-seed differences, the comparison that removes the variation between truths, each with its , 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 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 . Compute the linear score’s expected loss, , for the honest report, for and for . Then show that for any with the linear score’s best report is , and say what happens at .
Answer
Honest: . : . : (talos, with expected_loss). Each step away from the truth toward certainty lowers the charge. In general, with ,
a straight line in with slope . For the slope is negative, so the loss is least at the largest allowed , 1. At the slope is 0 and every report scores : 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 , the truth and the report . Compute the expected Brier score directly, by averaging over the two outcomes, and again from the Mechanism’s decomposition. Then show that for the ranked probability score is exactly half the Brier score, whatever and .
Answer
If (probability 0.7): . If (probability 0.3): . Expected: . From the decomposition: and , total 0.44, the honest report’s 0.42 plus the distance term 0.02 (talos agrees). With two outcomes, , so the Brier score’s two terms are equal and it is . The RPS has one term, , with and : , 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 . 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 against the reports and , and say whether it matters for the gates of this book.
Answer
The floor makes every probability below 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 as above, the floored log reward of reporting is , and of reporting it is : certainty earns more. The spherical rewards are for the honest report and for certainty, a difference of about , 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 , which are never learned. A threshold like the 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 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
, and without the normal approximation, from , . 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 gives 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 every time is calibrated and useless. Let be any calibrated noul forecaster, meaning , with base rate . Show that its expected one-term Brier score is . What does this say about ranking calibrated forecasters by the Brier score?
Answer
Expand: . Since , and . For the middle term, condition on : . And calibration gives . So
and with ,
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 , scores worst of all, . On talos, 400,000 draws with 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 and the distributions’ variances, 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 and one item whose logits are , with label 1, and write . Show directly that , compute , and check it against the Mechanism’s . Then fit a temperature to two items: one right with margin and one wrong with margin . Find the minimising from a polynomial equation, and explain why the wrong item keeps the answer away from the floor.
Answer
, so . With , , and with , . Under the logit is with probability and with , a two-point distribution whose variance is : the same.
For the two items, , and setting the derivative to zero gives . With , and , so , that is , whose real root is , so and . fit_temperature returns on talos, lowering the NLL from 0.7201 at to 0.6420. The right item alone would drive to the bottom of the bracket (0.05, the default lo, on talos), since its loss falls toward 0 as grows. The wrong item’s loss, , grows without bound, about linearly in , 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 with a parameter beside . Derive the score-function estimate of the gradient in and check that its baseline term has mean zero. Then, for the log reward alone, say which way the expected gradient pushes , and what that does to the estimator of the gradient in .
Answer
With , the log-density is . Its derivative in is ; multiplying by and writing ,
so the estimate is , which the group baseline shrinks by , as it does the estimate in . The baseline term has mean zero because is a sum of squared standard normals, with mean .
For the log reward, the Mechanism’s computation gives the expected reward with . As a function of over the whole real line, is convex (a convex function of an affine function of , averaged over ) and even ( and have the same distribution). A convex even function is least at 0, since , and it does not decrease on : for , lies between and , so . So the expected reward never rises with , and a learned is pushed toward 0: under a proper reward the model gains nothing from its own noise, and as falls the Mechanism’s bias goes with it. The estimator in stays usable on the way down because of the baseline. Its terms are . For small , , so and each term is about , of order 1 whatever is. Without the baseline the terms are , and the part , zero in expectation, has a variance that grows like . The experiment fixes 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 , the noisy report’s, the fitted and the true after move as goes from 0.1 to 2. Then run run(0, "well", "rf", sigma=s, ms=(0,)) for , plot the four numbers against , and say where the prediction held.
Answer
The prediction: the noisy report’s mean is what the reward pins to the truth, so its should stay near cross-entropy’s whatever is; the raw report is sharpened by about , so its should grow, quadratically while is small; the temperature should rise above 1 to undo the sharpening; and if the sharpening were exactly a temperature, the after would not depend on 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 grows, and so does (0.011, 0.030, 0.093, 0.298, 0.866), but not as : doubling from 0.25 to 0.5 multiplied 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- statement, and the Mechanism’s single-item check already showed it overshooting at . The noisy report’s 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 may be unable to meet that condition at every 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 , 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 , and which order does Bayes’ rule ask for? Which probabilities must EM’s E-step use?
Answer
Dividing the sum by gives with : it multiplies each probability by instead of . With the ratio is raised to a power below 1, so every prior ratio is pulled toward 1 and the correction is too weak; with it is too strong. For and a class whose prior quadrupled, the corrected odds move by instead of 4. Bayes’ rule, as the Mechanism derived it, multiplies by , and the model’s estimate of is its calibrated answer, , 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 labels is an estimate with a sampling spread, and when the source temperature is already right, any spread can only add error: the true is smallest near the right 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 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 , 0.818 to 1.245 at and 0.908 to 1.149 at , with mean true 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 , 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 here; under label and concept shift, where one number cannot fix the error, the tables show it barely moving at any .
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 to a relative , never returns less than however low lo is set, and on logits whose truth is the same logits divided by 3 finds a 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”, 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
- Glenn W. Brier, “Verification of Forecasts Expressed in Terms of Probability”, Monthly Weather Review 78(1), 1–3 (1950). The quadratic score of “Proper scoring rules”, proposed for verifying probability forecasts of the weather.
- Edward S. Epstein, “A Scoring System for Probability Forecasts of Ranked Categories”, Journal of Applied Meteorology 8(6), 985–987 (1969). The ranked probability score, for forecasts over ordered categories.
- Tilmann Gneiting and Adrian E. Raftery, “Strictly Proper Scoring Rules, Prediction, and Estimation”, Journal of the American Statistical Association 102(477), 359–378 (2007). The general theory behind this chapter’s four proofs: every proper scoring rule comes from a convex function of the forecast, with the log, quadratic, spherical and ranked probability scores as cases.
- Mahdi Pakdaman Naeini, Gregory F. Cooper and Milos Hauskrecht, “Obtaining Well Calibrated Probabilities Using Bayesian Binning” (AAAI, 2015). Binned calibration error as a measurement, and a recalibration method that averages over binnings.
- Chuan Guo, Geoff Pleiss, Yu Sun and Kilian Q. Weinberger, “On Calibration of Modern Neural Networks” (ICML, 2017). Temperature scaling, and the 15-bin equal-width ECE this chapter reports beside the equal-mass one.
- Jeremy Nixon, Michael W. Dusenberry, Linchuan Zhang, Ghassen Jerfel and Dustin Tran, “Measuring Calibration in Deep Learning” (CVPR Workshops, 2019), 38–41. Calibration measured over every class’s probability rather than the top one, and bins adaptive to the data, the equal-mass bins of
ece_adaptive. - Ananya Kumar, Percy Liang and Tengyu Ma, “Verified Uncertainty Calibration” (NeurIPS, 2019). The debiased estimator of “Measuring calibration”, and why binning can understate the calibration error of a model whose outputs are continuous.
- Marco Saerens, Patrice Latinne and Christine Decaestecker, “Adjusting the Outputs of a Classifier to New a Priori Probabilities: A Simple Procedure”, Neural Computation 14(1), 21–41 (2002). The EM estimate of shifted priors from unlabelled data, and the correction of the classifier’s answers that the experiment’s label-shift column applies.
- Ronald J. Williams, “Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning”, Machine Learning 8(3–4), 229–256 (1992). REINFORCE, with baselines, for any policy whose log-probability has a gradient, the Gaussian policy of the experiment included.
- Laya: the source at commit
6d942c9(the repository the Hugging Face model card links to) forproper_reward, the reward of “Sums of proper rules”, exercise (c) and the controlled experiment. - TypeSafe AI, “Introducing System One models and Jev”, which names RLCD, the training method the controlled experiment asks about.