Calibration of Language Models
When a model says 0.9, is it right nine times in ten? For a next-token distribution over thousands of words the question splits into a strong form no corpus can test and a weak form any corpus can; every log loss separates into what the text cannot tell us, what the model's context discards, and what a recalibration could recover
Overview & Motivation
Score Topic 3’s Kneser–Ney trigram on tokens of new text from the generator that wrote its training corpus. For every token, write down the probability the model gave its single likeliest next word, and whether that word is the one that came. Sort the tokens into fifteen bins by that probability, and in each bin compare the average probability with the fraction of hits. The fifteen points lie almost on the diagonal: the model’s mean confidence is and its accuracy . Now do the same on tokens of real MD&A text from EDGAR filings. The model’s mean confidence is ; its accuracy is . It reads as overconfident by a factor of more than two, and most of that reading, we will see, is one token.
That comparison is a calibration check, and this page makes it precise for language models. The sampling topic treated temperature as a decoding choice that trades quality against diversity. Here the same operation is a repair: the temperature that makes the model’s probabilities honest. We develop it in order:
- What calibration means for a 3,427-way forecast. The strong form, that the whole distribution is right, is the same as being the true conditional, and no corpus can check it. The weak form, that the top probability is right, any corpus can check.
- What miscalibration costs. Every log loss splits into three exact parts, and only one of them can be recalibrated away.
- How to measure it honestly. The standard estimator is biased in both directions, and a calibrated twin of the model measures one of the biases.
- One dial. Temperature scaling is a convex fit that matches one moment; it keeps every argmax but not the order of confidences.
- Why . Maximum likelihood leaves the training-data temperature at exactly when the model can scale its own logits, and below when it is penalized.
- Calibrated sets. Calibration is what makes a nucleus a prediction set.
Then we measure both corpus engines on three test sets and return to the filings.
What calibration means for a 3,427-way forecast
We write for the context a model conditions on (the trigram’s last two words, or the decoder’s whole prefix), for the next token, and for the model’s forecast, a point of the probability simplex over the vocabulary . The truth is , the next-token distribution given everything the model sees. The recalibration of is
the distribution of the next token among all contexts that receive the same forecast. Geometrically, sends contexts to points of the simplex; averages the truth over each point’s preimage.
Definition 1 (Calibration of a next-token forecaster).
is canonically calibrated if almost surely. With and the likeliest token (ties to the lower token id), is top-label calibrated if , and its top-label calibration error is .
The formalML uncertainty-quantification topic defines calibration for a binary outcome, where there is only one probability to check. A next-token forecast has free coordinates, and the two notions above sit at the two ends of what one could ask of them.
Proposition 1 (Canonical, top-label, and the truth).
(a) Canonical calibration implies top-label calibration.
(b) The converse fails: with one context, truth , and forecast , the forecaster is top-label calibrated and not canonically calibrated.
(c) If gives distinct contexts distinct forecasts, then . So is canonically calibrated if and only if .
Proof.
(a) If , then . The confidence is a function of , so by the tower property .
(b) The forecaster says for its top token and is right with probability , but .
(c) Each level set is a single context, so .
∎Part (c) is why canonical calibration is out of reach for a language model. Most contexts the trigram has seen have a row of their own ( seen contexts sit on distinct rows in the test text below), so checking canonical calibration means checking that nearly every row is the true conditional over outcomes, from a few occurrences of each context. What a corpus can check is top-label calibration, one number per token, and that is what every corpus number on this page measures. Canonical calibration we test exactly, on small finite worlds where every expectation is a sum.
What miscalibration costs
The log loss of a forecaster is its cross-entropy, . Calibration is one part of it, and the decomposition is clearest first for the Brier score , where is the corner of the simplex at the token that occurred. Three points sit in the simplex for each context: the forecast , its recalibration , and the truth . Conditional on , the outcome averages to ; conditional on , it averages to . So the squared distance from to the outcome splits by Pythagoras, twice.
Theorem 1 (Three-term decomposition).
Every term is nonnegative. The recalibrated forecaster keeps the first two terms and loses the third, and the reliability term is zero exactly when is canonically calibrated.
Proof.
Brier. Expand . Given , the vectors and are fixed and , so the cross term has conditional mean . Repeat with , , and conditioning on : is a function of and , so . Finally .
Log loss. Given , the next token has law , so . Next, is a function of and , so . Nonnegativity is Gibbs’s inequality, and exactly when .
∎The three terms answer three questions. The irreducible term is what the text cannot tell any forecaster that sees the same context, the floor that only a longer context lowers. The refinement gap is what throws away by sending different contexts to the same forecast. The reliability term is what a recalibration of the forecast, a function applied to alone, could recover. Bröcker (2009, Eq. 10) gives the split into and the reliability term for any proper score, and his §3 on sufficiency gives the second split; for binned binary forecasts under the Brier score it is Murphy’s (1973) partition, which the formalML topic proves as its Theorem 3. DeGroot and Fienberg (1983) named the two halves calibration and refinement.
Corollary 1 (No recalibration recovers more than the reliability term).
For any map of the forecast, . In particular, no temperature lowers the log loss of a canonically calibrated forecaster.
Proof.
Let . Theorem 1 applied to gives . Since is a function of and ,
and is the loss minus the reliability term.
∎So the drop in held-out log loss that any fitted map of the forecast achieves estimates a lower bound on how miscalibrated the model is. It is only an estimate, from a sample, and it needs to be an honest one, since a temperature fit and scored on the same tokens flatters itself. We cross-fit: fit on the even sentences and score the odd ones, then swap, and average the two by their token counts. And it is only a lower bound, for the one map we tried. Temperature’s can be far from tight, as the finance case study will show. The harness checks Theorem 1 and Corollary 1 to on random finite worlds, against temperatures each.
Measuring calibration honestly
On a corpus we see tokens, not conditional distributions, and the standard estimator bins them.
Definition 2 (The binned calibration error).
Partition into equal-width bins and put each token in the bin of its confidence. With tokens in bin , mean confidence , and fraction of hits , the plug-in ECE is . Its population counterpart is , where .
The formalML topic notes that ECE depends on the bin count, biased toward zero with too few bins and upward with too many. Both directions can be made exact, and the second can be measured.
Theorem 2 (Two biases of the binned estimator).
(a) Binning hides. If the bins refine the bins , then the top-label calibration error. In particular .
(b) Sampling inflates. Suppose that, given their confidences, the tokens’ hits are independent with probabilities . Then , the sample’s own binned error, strictly in every bin where can take both signs. A perfectly calibrated model therefore shows a positive estimated error.
(c) The square can be corrected. In each bin,
Proof.
(a) A bin is a function of the confidence, so , and Jensen’s inequality gives . Summing over bins compares a partition with the finest one, and the same argument inside each cell of compares with .
(b) Jensen again, inside a bin: , with equality only if has one sign almost surely.
(c) Let count the hits, so , , and, with , . Then . The hits are or , so is their sample variance, and . Subtracting leaves the stated right side.
∎Part (c) is the correction Bröcker (2012) and Ferro and Fricker (2012) derived for the Brier score’s reliability term; Kumar, Liang, and Ma (2019) state it for binned models (their Definition 5.2), where every token in a bin shares one , , and the estimator is exactly unbiased, and they prove it needs far fewer samples than the plug-in. For a model whose confidences vary inside a bin, the remaining bias is the small negative heterogeneity term. Roelofs and colleagues (2022) find the binned estimator’s bias most severe for perfectly calibrated models, which is part (b).
Part (b) also suggests a measurement. Keep the model’s confidences and redraw every token’s hit as a coin with that confidence: this calibrated twin is calibrated by construction, so its estimated ECE is pure estimator noise. On the trigram’s in-distribution tokens, at bins, twins average with a standard deviation of , while the trigram itself scores , about ten standard deviations above the floor. The miscalibration is real, and small. The twin’s floor rises with the bin count, from at one bin to at ; it grows like , at about . The trigram’s own plug-in ECE rises too, from to , but that is not part (a) at work. Part (a) is about the population ECE and nested bins, and the plug-in also carries the noise of part (b): the twin’s floor alone rises of that . Bin counts of and are not nested in any case. The harness checks part (a) along on worlds, and parts (b) and (c) by exact Poisson-binomial expectations on random bins.
One dial: temperature scaling
A recalibration map has to be fit, and the simplest has one parameter. With the log-probabilities of a row and , temperature scaling replaces the row by , exactly the operation of the sampling topic, now chosen to minimize the held-out log loss
Proposition 2 (Temperature scaling is a convex moment match).
(a) and , where . So is convex, and strictly convex unless every row is constant on its support.
(b) A minimizer, if one exists, is unique, and it is the at which the expected logit equals the observed one: .
(c) Every row keeps its argmax, so accuracy does not change. But for the order of confidences across rows can: the rows and have confidences , and at they have .
Proof.
(a) The derivative of in is , and its second derivative is .
(b) A strictly convex function has at most one minimizer, and it is where .
(c) is increasing in each coordinate of , so it keeps the order within a row. At the first row stays , and the second becomes proportional to , with top probability .
∎Part (a) is the formalStatistics exponential-families topic’s Theorem 7.1 for a one-parameter family whose natural parameter is , and part (b) is its Theorem 7.4: the maximum-likelihood fit matches the sufficient statistic’s mean. Guo and colleagues (2017, Supplement S2) characterize temperature scaling the same way, as the maximum-entropy distribution subject to that one moment. The harness fits by Newton’s method from and checks that at the result on every engine and test set (by convexity, the global optimum); on the two EDGAR sets it also agrees with a bounded scalar search to .
Part (c) separates temperature scaling from the recalibrations of the formalRAG significance-testing topic, whose Theorem 2 shows that a monotone map of a score preserves every ranking. Temperature is not a function of the confidence: two rows with the same top probability can land on different ones. On the trigram’s in-distribution rows, Kendall’s between the confidences at and at is over distinct rows and about over tokens. A selective-prediction rule that ranks contexts by confidence changes when the temperature does, though not by much at the top: a rule that keeps the fifth of the tokens with the highest confidence keeps of the same tokens from to , and its accuracy goes from to .
Fewer bins average miscalibration away and more bins invent it (Theorem 2): the twin, calibrated by construction, shows how much of an ECE is noise at this sample size. Temperature moves tokens between bins, so the circles can jump, and only the overall accuracy readout stays fixed (Proposition 2). In distribution both engines sit near the diagonal. On the EDGAR filings the trigram’s coverage can’t pass its share of known words at any temperature, because the unknown-word token is last in every row (Proposition 3); the decoder’s comes close only at high τ.
Accuracy does not move with τ; confidence does. Facts seen twice or more are always right but underconfident, so their loss falls as τ falls; facts never seen are overconfident, so theirs falls as τ rises toward the uniform forecast. The pooled optimum (1.179) serves neither.
Why τ = 1 at all
In distribution, the trigram’s NLL-optimal temperature is , as if the model came out of training exactly where temperature scaling would put it. That number is a balance, not a law: on the words the trigram knows, is , and the <unk> tokens pull it back up. A Kneser–Ney trigram is no likelihood optimum and has no direction that scales its logits, so nothing pins its temperature. For some families, though, something does.
Theorem 3 (Where maximum likelihood leaves the temperature).
Suppose a model family has a reparametrization , differentiable at with , that scales its logits, , and a penalty that scales as . If is a stationary point of , then
So an unpenalized stationary point has training-data temperature exactly . With , the training-data optimum has : the model is underconfident on its own training data.
Proof.
Let . By the chain rule is the gradient of the penalized loss at applied to , which is at a stationary point. The penalty contributes to , so the training loss contributes its negative. When that is negative, the training loss decreases as passes , and by Proposition 2’s convexity its minimizer has .
∎This is the score equation of the formalStatistics maximum-likelihood topic (its Theorem 1) read along one direction of parameter space. A log-linear bigram, whose logits are a matrix indexed by the previous token, has the direction exactly: , and the L2 penalty scales as required. Fit on the shared filings over the decoder’s tokens, at ten penalties from to , the derivative at and agree to six decimals every time. Seven of the ten:
| penalty | |||||||
|---|---|---|---|---|---|---|---|
| derivative at | |||||||
| , training | |||||||
| , continuation | |||||||
| , held | |||||||
| , EDGAR |
The training row is the theorem: the more penalty, the more underconfident. Without the penalty there is no finite optimum to be stationary at: the logits of word pairs never seen in training run off to , and with them the held-out likelihood of any text that contains one. The penalty that keeps the model usable is what makes it underconfident on its training data. The other rows are text the theorem says nothing about, and the temperatures there are not pinned. On the continuation crosses near , on EDGAR between and , and on held it never crosses on this grid. (The test sets, continuation, held, and EDGAR, are defined below.)
Topic 14’s decoder has no such direction. Its final layer normalization has no learned gain, its output matrix is its input embedding scaled by a fixed , and scaling the embedding moves the inputs as well as the outputs. Nor is it a stationary point: its steps of Adam end with a nonzero gradient over the training windows. Neither hypothesis of Theorem 3 holds, so nothing pins its temperature. On every second training sentence the NLL-optimal is , and it is to across Topic 14’s four training seeds.
The same dial appeared in the sampling topic for the opposite reason. There, temperature reshaped a model deliberately, to trade predictability for diversity.
Corollary 2 (Sampling temperature miscalibrates).
If is canonically calibrated and , the sampler has reliability term unless every forecast is uniform on its support.
Proof.
The map is one-to-one, so conditioning on is conditioning on , and the recalibration of is . Theorem 1 gives its reliability term as , which is zero only where .
∎Calibrated sets
The sampling topic’s nucleus keeps the shortest list of likeliest tokens whose mass reaches . It is also a prediction set: a claim that the next token is in the list. Calibration is what makes the claim honest.
Proposition 3 (Calibrated sets cover their kept mass).
If is canonically calibrated, then every set chosen from the forecast alone covers the next token with probability equal to its expected kept mass: . A nucleus of mass therefore covers at least , and a coverage that differs from the kept mass certifies miscalibration.
Proof.
, and the tower property averages both sides.
∎In distribution the trigram’s nucleus of mass keeps of the mass on average and covers of the tokens; the decoder’s keeps and covers . Both are close, in opposite directions. The harness checks the proposition exactly on calibrated worlds, and on the trigram’s own rows with outcomes drawn from the model, where coverage matches kept mass within four standard errors. A guarantee of coverage that does not need calibration at all comes from choosing the threshold on held-out data, which is split conformal prediction.
On the corpus
Both engines are the sampling topic’s. Topic 3’s interpolated Kneser–Ney trigram has outcomes, word types plus </s> and <unk>. Topic 14’s two-block decoder has tokens, words plus <s>, </s>, and <unk>, and <s> is never scored. Here both score every token of a text, so the unknown-word token <unk> is an outcome like any other; the decoder sees only the first positions of each sentence. Three test sets:
- continuation: the generator that wrote the training corpus, run on for more documents. The same source: a best case, in which of its sentences repeat a training sentence word for word.
- held: Topic 3’s held-out split, a fresh run of the generator whose word frequencies differ from the training text’s.
- EDGAR: the public MD&A excerpts, real filings, sentences and trigram tokens.
The table gives mean confidence and accuracy, the ECE at bins beside the calibrated twin’s floor, the NLL-optimal temperature , and the coverage and kept mass of the nucleus of mass .
| engine, test set | conf. / acc. | ECE / twin | nucleus cover / kept | |
|---|---|---|---|---|
| trigram, continuation | / | / | / | |
| trigram, held | / | / | / | |
| decoder, continuation | / | / | / | |
| decoder, held | / | / | / |
In distribution, both engines are close to calibrated, and a cross-fitted temperature recovers almost nothing: under nats for the trigram, for the decoder. The trigram’s reliability diagram has a shape, though. Bins with confidence between and are overconfident and every bin above is underconfident. Kneser–Ney’s discounts, which take mass from what was seen and give it to what was not, explain half of that. Refit the trigram with scaled discounts and score the same tokens in every column (gaps are accuracy minus confidence):
| discount, Ney’s | capped at | ||||
|---|---|---|---|---|---|
| gap, to | |||||
| gap, above |
The gap above flips sign with the discount, so that underconfidence is the discounts’ doing. The overconfidence between and is there at every discount and shrinks as the discount grows, so it is not their signature. The top bin holds of the tokens at accuracy : the generator’s fixed phrases, like “cost → of” and “from its head → office”, which turn up anywhere in a sentence. They are not sentence openers. Of that bin’s tokens, fall at positions to , against of all tokens, and only of a sentence’s first three tokens land in it, against overall.
Under the held-out split’s mild shift the two engines move in opposite directions: the trigram becomes slightly overconfident, and the decoder reads as underconfident. Nearly all of the decoder’s gap sits on rows whose top label is <unk> ( tokens, confidence , accuracy ), as <unk> rises from of its tokens to . Rows with a word on top read and . Shift does not have a sign.
Where this sits
Everything on this page is the calibration of one next-token distribution at a time. The calibration of whole generations is a different property: Braverman and colleagues (2020) show that the entropy rate of a model’s samples drifts upward with length, the long-horizon face of Corollary 2, and correct it with a one-parameter fit of their own. Desai and Durrett (2020) find pre-trained transformers calibrated in domain and less so out of domain, the pattern of the table above, and Ovadia and colleagues (2019) show that calibration measured on in-distribution data does not survive dataset shift. For large models the question moves to the confidence of a chosen answer: Kadavath and colleagues (2022) measure it on multiple-choice questions and on the model’s own judgments of its answers, and the GPT-4 report (OpenAI 2023, Figure 8) finds the pre-trained model well calibrated and the post-trained one much less so. Neither finding is a case of Theorem 3, whose hypotheses ask for a stationary point of a penalized likelihood and a direction that scales the logits. What to do with a calibrated confidence, answering or abstaining, is the formalRAG selective-generation topic.
Honest caveats
Implementation
The companion notebook (notebookPath) imports language_model_calibration.py, which owns every number on this page. That module imports the sampling topic’s module for temperature, the nucleus, and the fact model, and through it the beam-search topic’s trigram and trained decoder. It implements finite worlds with exact recalibration, the plug-in and debiased estimators and the calibrated twin, a Newton temperature fit on deduplicated rows, the log-linear bigram fit by L-BFGS, and per-temperature statistics for both engines on all three test sets. A harness of assertion-based tests runs in about two and a half minutes on a laptop CPU. The tests cover:
- Proposition 1, Theorem 1, and Corollary 1 exactly on random finite worlds, and Proposition 1’s counterexample.
- Theorem 2(a) on nested bins, (b) and (c) by exact Poisson-binomial expectations, and the calibrated twin’s floor on the corpus.
- Proposition 2’s derivatives against finite differences, the Newton fit’s stationarity on every set and against a scalar search on EDGAR, the invariance of accuracy, and the reordering of confidences by rows and by tokens.
- Theorem 3’s identity on the log-linear bigram at ten penalties, where held-out temperatures land on that grid, and the decoder’s temperature across four seeds with its nonzero gradient.
- Proposition 3 exactly on calibrated worlds and on the trigram’s rows, Corollary 2, and the fast nucleus against the sampling topic’s own.
- The in-distribution, held-out, and EDGAR findings, the Kneser–Ney reliability shape and the discount refits, the known-word cut,
<unk>’s rank and the coverage ceiling, the map onto<unk>, and the fact regimes, including that no row mixes them.
The laboratory reads its data from a JSON file that one of those tests requires to equal the module’s viz_payload() exactly, so the figure cannot drift from the code.
References & Further Reading
- paper On Calibration of Modern Neural Networks — Chuan Guo, Geoff Pleiss, Yu Sun, and Kilian Q. Weinberger (2017) ICML 2017, PMLR 70: 1321–30. ECE with 15 bins (their Eq. 3), temperature scaling (§4.2), and its maximum-entropy characterization (Supplement S2, Claim 1), the moment condition of Proposition 2
- paper The Comparison and Evaluation of Forecasters — Morris H. DeGroot and Stephen E. Fienberg (1983) The Statistician 32 (1/2): 12–22. Calibration and refinement as the two parts of a forecaster's quality
- paper A New Vector Partition of the Probability Score — Allan H. Murphy (1973) Journal of Applied Meteorology 12 (4): 595–600. The reliability–resolution–uncertainty partition of the Brier score
- paper Reliability, Sufficiency, and the Decomposition of Proper Scores — Jochen Bröcker (2009) Quarterly Journal of the Royal Meteorological Society 135 (643): 1512–19. The decomposition of any proper score (his Eqs. 10 and 13) and forecast sufficiency (§3), the two steps of Theorem 1
- paper Strictly Proper Scoring Rules, Prediction, and Estimation — Tilmann Gneiting and Adrian E. Raftery (2007) Journal of the American Statistical Association 102 (477): 359–78. Proper scores, their entropies, and their divergences
- paper Evaluating Model Calibration in Classification — Juozas Vaicenavicius, David Widmann, Carl Andersson, Fredrik Lindsten, Jacob Roll, and Thomas B. Schön (2019) AISTATS 2019, PMLR 89. Calibration of the whole predicted distribution (their Eq. 1), the canonical calibration of Definition 1
- paper Obtaining Well Calibrated Probabilities Using Bayesian Binning — Mahdi Pakdaman Naeini, Gregory F. Cooper, and Milos Hauskrecht (2015) AAAI 29 (1). The expected calibration error
- paper Estimating Reliability and Resolution of Probability Forecasts through Decomposition of the Empirical Score — Jochen Bröcker (2012) Climate Dynamics 39: 655–67. The bias of the empirical reliability term and its correction
- paper A Bias-Corrected Decomposition of the Brier Score — Christopher A. T. Ferro and Thomas E. Fricker (2012) Quarterly Journal of the Royal Meteorological Society 138 (668): 1954–60. The corrected reliability term behind Theorem 2(c)
- paper Verified Uncertainty Calibration — Ananya Kumar, Percy Liang, and Tengyu Ma (2019) NeurIPS 2019. The plug-in and debiased estimators of the squared calibration error (their Defs. 5.1–5.2) and their sample complexities (Thms 5.3–5.4)
- paper Mitigating Bias in Calibration Error Estimation — Rebecca Roelofs, Nicholas Cain, Jonathon Shlens, and Michael C. Mozer (2022) AISTATS 2022. Binned ECE is biased, most severely for perfectly calibrated models
- paper Can You Trust Your Model's Uncertainty? Evaluating Predictive Uncertainty under Dataset Shift — Yaniv Ovadia, Emily Fertig, Jie Ren, Zachary Nado, D. Sculley, Sebastian Nowozin, Joshua V. Dillon, Balaji Lakshminarayanan, and Jasper Snoek (2019) NeurIPS 2019. Calibration degrades under dataset shift, and calibration on held-out in-distribution data does not transfer
- paper Calibration of Pre-trained Transformers — Shrey Desai and Greg Durrett (2020) EMNLP 2020, 295–302. Pre-trained transformers are calibrated in domain and less so out of domain; temperature scaling helps
- paper Calibration, Entropy Rates, and Memory in Language Models — Mark Braverman, Xinyi Chen, Sham Kakade, Karthik Narasimhan, Cyril Zhang, and Yi Zhang (2020) ICML 2020, PMLR 119. Calibration of a language model's generations: their entropy rate drifts upward, and a one-parameter correction fixes it
- paper Language Models (Mostly) Know What They Know — Saurav Kadavath and colleagues (2022) Calibration of large language models on multiple-choice questions and of their own self-evaluations
- paper GPT-4 Technical Report — OpenAI (2023) Figure 8: the pre-trained model is highly calibrated on a subset of MMLU, and post-training reduces its calibration