LLM calibration: what does 80% confidence mean?
语言模型校准
Fit answer-confidence temperature on a calibration split and inspect ranking, bins and shift.
llm-calibrationEighty percent of what?
An assistant gives one hundred answers, each with “80% confidence.” If only fifty are correct, its confidence is poorly calibrated on that group. This does not tell us whether the answers were useful, whether the model ranks its mistakes well, or whether another task would produce the same gap. Calibration asks whether stated probabilities match observed frequencies for a specified event.
Define that event first: a proposed answer is correct under a fixed rubric. A token’s probability is a probability of a particular next token, not automatically the probability that an entire answer is factually correct. Equivalent wording, answer length and the grading rule all matter. A non-AI starting point is to report the observed correctness frequency of a comparable held-out group, with sample counts, instead of inventing a confidence score for each answer.
Kadavath and colleagues distinguish evaluating a particular proposed answer, P(True), from estimating whether the model can answer a question, P(IK). Their results depend on tasks, formats and training. These are operational measurements, not evidence of conscious self-knowledge. Study
Change the probability scale without changing the order
Let Y be binary answer correctness and P the reported probability. Ideal calibration on the evaluation distribution means:
A finite sample cannot establish this equality at every real-valued probability. We group examples or fit a restricted calibration model. For probabilities strictly between zero and one, convert to log odds:
Temperature scaling multiplies these fixed log odds by a positive inverse temperature beta. The program fits beta only on a calibration split, within [0.05,10]. This is a binary answer-correctness model, not a change to the generator’s token sampling temperature.
Fit by minimizing average negative log-likelihood, with natural logarithms and therefore units of nats per answer:
Differentiate using the sigmoid derivative. The nonnegative second derivative makes this a convex one-dimensional problem. Bisection finds the derivative’s root, or chooses a boundary when the unconstrained optimum lies outside our interval.
Two additional summaries are the Brier score and a binned absolute calibration error. B denotes a nonempty equal-width probability bin; its confidence and accuracy are sample means.
This explicitly named L1 ECE differs from the squared bin-error convention printed in the first version of Tian and colleagues’ paper. That work studies elicited verbal confidence, label probes and temperature scaling under particular models and question sets. A model saying “80%” is an input to evaluate, not a calibration guarantee. Study
Fit once, then inspect two other populations
Run the program with Python 3.12 and NumPy 1.26.4. It constructs four confidence groups of one hundred answers each. Calibration-group correct counts are 54,61,71,86; untouched test-group counts are 52,63,70,84; a shifted population has 30,40,50,60. These labels are authored fixtures, not random draws or language-model observations. No random seed is needed.
"""Answer-correctness calibration on authored confidence groups; no model inference."""
import json,math
import numpy as np
def checked(scores,labels,strict=True):
p=np.asarray(scores,dtype=float);y=np.asarray(labels,dtype=float)
if p.ndim!=1 or not len(p) or p.shape!=y.shape or not np.isfinite(p).all() or (np.any((p<=0)|(p>=1)) if strict else np.any((p<0)|(p>1))) or not np.isin(y,[0,1]).all():raise ValueError('aligned probabilities, binary labels, and the declared endpoint domain required')
return p,y
def scale(scores,beta):
p,_=checked(scores,np.zeros(len(scores)))
if isinstance(beta,bool) or not math.isfinite(beta) or not .05<=beta<=10:raise ValueError('inverse temperature in[.05,10] required')
z=beta*(np.log(p)-np.log1p(-p))
# Clip only the exponent argument; all declared confidence profiles are far from this bound.
return 1/(1+np.exp(-np.clip(z,-700,700)))
def fit(scores,labels):
p,y=checked(scores,labels);z=np.log(p)-np.log1p(-p);lo,hi=.05,10.
def grad(beta):return float(np.mean((scale(p,beta)-y)*z))
if grad(lo)>=0:return lo
if grad(hi)<=0:return hi
for _ in range(80):
mid=(lo+hi)/2
if grad(mid)>0:hi=mid
else:lo=mid
return (lo+hi)/2
def metrics(scores,labels,bins=5):
p,y=checked(scores,labels,strict=False)
if type(bins) is not int or not 1<=bins<=100:raise ValueError('bin count1..100 required')
indices=np.minimum((p*bins).astype(int),bins-1);rows=[];ece=0.
for i in range(bins):
keep=indices==i;n=int(keep.sum())
if n:
conf=float(p[keep].mean());acc=float(y[keep].mean());ece+=n/len(p)*abs(conf-acc);rows.append(dict(bin=i,count=n,confidence=conf,accuracy=acc))
with np.errstate(divide='ignore'):
losses=np.where(y==1,-np.log(p),-np.log1p(-p))
return dict(nll=float(np.mean(losses)),brier=float(np.mean((p-y)**2)),ece_l1=float(ece),bins=rows)
def selective(scores,labels,fraction):
p,y=checked(scores,labels,strict=False)
if not math.isfinite(fraction) or not 0<fraction<=1:raise ValueError('coverage fraction in(0,1] required')
n=max(1,math.ceil(len(p)*fraction));idx=np.argsort(-p,kind='stable')[:n]
return dict(coverage=n/len(p),accuracy=float(y[idx].mean()),indices=idx.tolist())
def profile(correct_counts):
if len(correct_counts)!=4 or any(type(n) is not int or not 0<=n<=100 for n in correct_counts):raise ValueError('four counts0..100 required')
p=np.repeat([.6,.75,.9,.99],100);y=np.concatenate([np.r_[np.ones(n),np.zeros(100-n)] for n in correct_counts])
return p,y
def demo():
p,train=profile([54,61,71,86]);_,test=profile([52,63,70,84]);_,shift=profile([30,40,50,60]);beta=fit(p,train);q=scale(p,beta)
rows={}
for name,y in [('calibration',train),('test',test),('shift',shift)]:rows[name]=dict(raw=metrics(p,y),scaled=metrics(q,y))
fractions=[.25,.5,.75,1.0];curves=[]
for f in fractions:
a=selective(p,test,f);b=selective(q,test,f);assert a['indices']==b['indices'];curves.append(dict(coverage=a['coverage'],raw_accuracy=a['accuracy'],scaled_accuracy=b['accuracy']))
return dict(beta=beta,temperature=1/beta,raw_confidences=[.6,.75,.9,.99],scaled_confidences=scale([.6,.75,.9,.99],beta).tolist(),metrics=rows,risk_coverage=curves,bin_sensitivity={str(n):metrics(q,test,n)['ece_l1'] for n in [1,5,10,20]},cases_per_split=400)
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
The fitted beta is about 0.399184, or T=2.505109. It maps confidences 0.6,0.75,0.9,0.99 to about 0.5404,0.6079,0.7062,0.8623. Test NLL falls from 0.727354 to 0.601449; five-bin L1 ECE falls from 0.1375 to 0.014629. On the shifted population, the same calibrated scores have ECE about 0.229196. A calibration learned on one population can be inappropriate on another.
Positive temperature scaling is strictly increasing in exact arithmetic. Selecting the highest quarter of confidences therefore retains the same examples and the same selective accuracy. Better probability values do not necessarily improve error ranking. Finite-precision saturation can create ties; the program uses stable ordering and its demonstration stays well away from saturation.
With n examples and J bisection steps, fitting costs O(Jn) arithmetic and O(n) working memory; J=80 here. Sorting a selective-accuracy curve costs O(n log n). The metrics allow probabilities zero and one: a correct certain prediction has zero NLL, an incorrect certain prediction has infinite NLL. The fit itself requires interior probabilities so its log odds exist.
One good average can conceal two bad groups
ECE depends on binning and sample size. Predictions 0.2 and 0.8 with labels 1 and 0 have one-bin ECE zero because both means are 0.5, yet two-bin ECE is 0.8. Report bin definitions, counts and a proper scoring rule such as NLL or Brier alongside reliability plots. Subgroups and error costs may matter more than the overall number.
For a deployment study, freeze answer generation and grading, split calibration from final evaluation, fit without test labels, and inspect both same-distribution and shifted tasks. Record failures of answer extraction or grading separately. A refusal threshold should reflect the cost of wrong answers and abstentions, not merely minimize ECE. Temperature cannot repair incorrect answers or add missing knowledge. See hallucination detection.
Probability, rank and scope
- Is the probability of the first answer token a calibrated probability that the whole answer is true?
Answer: Not by definition. The events differ; whole-answer correctness needs a stated grading rule and empirical evaluation.
- Compute Brier score and NLL for probabilities 0.2,0.8 and labels 0,1.
Answer: Each squared error is 0.04, so Brier is 0.04. Each correct-label probability is 0.8, so average NLL is −log(0.8), about 0.223144 nats.
- Why can temperature improve NLL while leaving accuracy at 25% coverage unchanged?
Answer: It changes probability values but preserves their order for positive temperature in exact arithmetic. The top quarter contains the same answers; their correctness labels do not change.
- A calibrator works on short factual questions. Can its refusal threshold be reused for long technical proofs without checking?
Answer: No. The correctness event, score distribution and error costs may differ. Obtain labeled target cases and evaluate transfer; fit on a separate target calibration split if needed.
What the confidence studies establish
The cited studies motivate specifying how confidence is obtained and what event it predicts. The present finite experiment independently implements binary temperature fitting, rather than reproducing either paper’s model runs. Keep the probability transformation, the elicitation prompt and the correctness judge as separate parts of an evaluation.
Make a prediction, then check
Does a strictly increasing confidence transformation change which answers rank first?
Learning objectives
- Define the correctness event, calibrate without test leakage and distinguish reliability from ranking.
- Run the original finite experiment and explain its counterexample and scope.
Prerequisites & connections
Explore related knowledge →References
- Language Models (Mostly) Know What They Know — v1
Saurav Kadavath; Tom Conerly; Amanda Askell and coauthors · 2022 - Just Ask for Calibration: Strategies for Eliciting Calibrated Confidence Scores from Language Models Fine-Tuned with Human Feedback — v1
Katherine Tian; Eric Mitchell; Allan Zhou; Archit Sharma; Rafael Rafailov; Huaxiu Yao; Chelsea Finn; Christopher D. Manning · 2023
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author. Viewed PDF10/11/13/14: P(True), P(IK), temperature and task/format dependence. Viewed PDF2/3: verbal confidence, label probes and inverse temperature; v1 ECE uses squared bin error, unlike our explicitly named L1 ECE. 6 paired equations and four explained exercises. Binary answer event, convex inverse-temperature fitting, endpoints, stable ranking, bin cancellation and distribution shift checked; explicit L1 ECE differs from cited squared convention.
- Binary answer event, convex inverse-temperature fitting, endpoints, stable ranking, bin cancellation and distribution shift checked; explicit L1 ECE differs from cited squared convention.
- Four computed SVG variants per topic;11 numeric/geometry tests and36 responsive cases passed. Twelve selected final captures directly viewed. Full article acceptance recorded separately.
Source locations checked:
- Language Models (Mostly) Know What They Know — v1 · Viewed PDF10/11/13/14: P(True), P(IK), temperature and task/format dependence.
- Just Ask for Calibration: Strategies for Eliciting Calibrated Confidence Scores from Language Models Fine-Tuned with Human Feedback — v1 · Viewed PDF2/3: verbal confidence, label probes and inverse temperature; v1 ECE uses squared bin error, unlike our explicitly named L1 ECE.
Related topics