Disclaimer on AI-assisted preparation
Out of respect for the reader and in the interest of full methodological transparency, I disclose that this manuscript was produced with substantial AI assistance within a verified, agentic engineering workflow. AI systems were used for research support, critical review, code generation and review, mathematical typesetting, and prose drafting and editing. Responsibility for the manuscript, its claims, and its conclusions remains with the author. No substantive claim, measurement, or reported data point was accepted solely as the output of an autoregressive generative text-completion process. The workflow was deliberately evidence-first. The initial hypotheses were formulated by the author. AI-assisted research-using Consensus and systems from OpenAI/GPT, Anthropic/Claude, Google/Gemini, Qwen and Moonshot/Kimi-was then used to identify relevant concepts, principles, prior art, and research that the author had not previously considered. Benchmark cases were generated synthetically and manually reviewed. The reported benchmark results themselves were obtained by executing those cases against real, functioning inference systems and models, with repeated runs used to assess reproducibility and stability. The resulting evidence was critically reviewed by the author for plausibility, internal consistency, compatibility with prior art and published research, and agreement with the observed behavior of the implemented systems. The methodology and claims were developed from this evidence, not from model-generated prose. AI systems were additionally used as critics to search for inconsistencies, unsupported claims, methodological weaknesses, and plausible alternative interpretations. Agreement among these systems was treated as a review signal instead of proof. Code supporting the work was verified through unit, integration, and end-to-end testing where applicable. Only after the empirical and engineering evidence had been assembled and critically reviewed was AI used to help draft and edit the manuscript's prose under direct, aware, and detailed instructions from the author. AI assistance was also used to render mathematical formulas efficiently in MathML. The resulting manuscript, together with its supporting evidence and provenance records, was subsequently subjected to further multi-model review and criticism in agentic evaluation harnesses. Where such controls were available, inference systems were configured for low-temperature sampling and the highest available reasoning setting. The author then reviewed the manuscript again and conducted a separate AI-assisted editing pass focused exclusively on writing quality. Finally, the author proofread the complete manuscript and verified its contents, evidence, and presentation to the best of his knowledge and understanding. The use of AI described above should therefore not be understood as a substitute for empirical validation, source criticism, reproducibility, or authorial responsibility but as a part of a careful research, engineering, verification, and editorial workflow under efficiency goals.
This document specifies the calibration protocol used by typed-decision-bench, and first implemented by kyr0/Bonsai-Llama-Jev inference engine. It explains the mathematics behind it, and separates four kinds of statements:
The goal is practical: an engineer should be able to understand what the calibration artifact does, why it is mathematically well behaved, when it is likely to generalize, how to implement it correctly in an inference server, and what evidence is required before making stronger claims about a deployment.
The method has now been exercised end to end on a real typed-decision deployment, not only on synthetic calibration-unit tests. Reference deployment:
bonsai-2-27b/v1/systemoneper_qtypeBonsai-Llama-Jev, commit c805487; reference implementation of the calibration transform: tools/server/server-context.cpp:4608--n 100The run is slightly smaller than the repository's complete 27,598-row corpus because --n 100 caps GPQA Diamond at 100 of its 198 stored rows. The frozen temperatures were:
| parameter | fitted value | interpretation |
|---|---|---|
| pooled/global fallback | 1.011720 | close to identity |
choice
|
1.037240 | very mild flattening |
noul
|
0.765169 | substantial sharpening |
score
|
1.162158 | moderate flattening |
All three qtype fits were interior solutions, not search-bound results. This is useful evidence for qtype stratification: the pooled scalar is close to 1 even though noul and score require corrections in opposite directions. A single pooled slope cannot represent both effects simultaneously.
The temperatures were fitted on split=calibrate only. Applying that frozen artifact offline to the 22,001 disjoint split=test examples produced:
| metric | raw test | calibrated test | relative change |
|---|---|---|---|
| NLL | 0.438015 | 0.434996 | -0.689% |
| Brier | 0.235513 | 0.233939 | -0.668% |
| hard accuracy | 0.832962 | 0.832962 | exactly unchanged offline |
| top-label ECE-15 | 0.011998 | 0.014646 | +22.1% |
The two proper full-distribution scores improved on rows that were never used to fit the temperatures. This is direct empirical evidence that the fitted correction generalized from the calibration partition to the held-out benchmark partition for this deployment. The ECE result is deliberately shown rather than hidden: top-label ECE did not improve globally. Temperature scaling was fitted to NLL, and ECE is a binned top-label diagnostic rather than the optimized full-distribution objective.
| qtype | T | test NLL raw → calibrated | test Brier raw → calibrated | ECE-15 raw → calibrated |
|---|---|---|---|---|
choice
|
1.037240 | 0.488071 → 0.487981 | 0.251921 → 0.251900 | 0.015138 → 0.013787 |
noul
|
0.765169 | 0.277873 → 0.267841 | 0.169659 → 0.165212 | 0.046100 → 0.025605 |
score
|
1.162158 | 0.555333 → 0.551416 | 0.317909 → 0.313074 | 0.068788 → 0.073269 |
noul is the clearest calibration win: held-out NLL fell by about 3.61%, Brier by about 2.62%, and top-label ECE by about 44.5%. score demonstrates why proper scores and ECE must not be conflated: its full-distribution NLL and Brier improved while its binned top-label ECE became slightly worse.
The frozen artifact was then loaded into the same inference server configuration with the C++ calibration path enabled, and the benchmark was run again. The served result almost exactly reproduced the offline prediction:
| metric | offline prediction from raw Run A | actual calibrated Run B | absolute difference |
|---|---|---|---|
| NLL | 0.4349960051 | 0.4349837998 | 0.0000122052 |
| Brier | 0.2339390976 | 0.2339318835 | 0.0000072142 |
| soft accuracy | 0.7645820850 | 0.7645868428 | 0.0000047578 |
| mean confidence | 0.8319436708 | 0.8319458355 | 0.0000021647 |
| top-label ECE-15 | 0.0146457356 | 0.0150875306 | 0.0004417949 |
The larger relative difference in ECE is expected to be more sensitive than NLL or Brier because fixed-width bin membership is discontinuous: a tiny probability change can move an example across a bin boundary. Hard accuracy differed by one test case between the two independent server runs (0.832962 versus 0.833008). Positive temperature scaling cannot cause such an argmax change for an identical raw vector; therefore this is evidence of a tiny cross-run raw-inference difference near a decision boundary, not a property of the calibration transform. The C++ implementation itself also has a direct unit test that compares server-returned calibrated probabilities against the analytic transform.
After Run B - whose probabilities were already calibrated by the frozen artifact - the benchmark fitted another temperature artifact from the same calibration rows. The residual temperatures were:
| parameter | residual T | deviation from identity |
|---|---|---|
| pooled/global | 0.99987869 | -0.0121% |
choice
|
0.99991057 | -0.0089% |
noul
|
0.99959046 | -0.0410% |
score
|
0.99999629 | -0.00037% |
The additional residual fit changed held-out NLL only from 0.4349837998 to 0.4349823236, a relative change of roughly 0.00034%. This is the expected temperature-composition fixed point in practice: after the frozen qtype temperatures are applied, the best additional multiplicative temperature correction is essentially identity. Because the residual fit reuses the same benchmark calibration partition, this is an implementation consistency / fixed-point check, not a second independent generalization experiment. Taken together, the reference experiment establishes four different facts:
That combination is materially stronger evidence than calibration-set improvement alone.
A model is not well calibrated merely because it is accurate. Suppose a binary system emits confidence for 1,000 decisions. A common notion of confidence calibration asks whether decisions reported near are actually correct approximately 80% of the time. For multiclass predictions the full object is a probability vector, Calibration of the complete probability distribution is stronger than calibration of only the largest probability. This distinction matters in this benchmark. For a choice response such as
{
"probabilities": {
"billing": 0.70,
"technical": 0.20,
"sales": 0.10
}
}
the top-label confidence is A top-label reliability diagram or ECE examines whether examples whose maximum probability is approximately are correct approximately 70% of the time. But the full distribution additionally claims that technical is twice as likely as sales. Top-label ECE does not test that claim. For this reason the benchmark reports multiple complementary metrics:
Implementation: top-label confidence as conf = max(p) and the correctness indicator as int(argmax(p) == argmax(y)) in metrics(), scripts/calibration.py:173-201 and case_record(), scripts/score.py:103-119.
Useful introductions:
For a more rigorous treatment of multiclass calibration evaluation, see Vaicenavicius et al., AISTATS 2019 (PMLR)
A System One typed-decision endpoint returns a structured decision rather than a free-form generated answer. Typical answer types are:
choice - a categorical probability distribution over named candidates,noul - a binary probability ,score - a categorical probability distribution over ordered score levels, from which an expected score is derived.The inference engine usually obtains these values from model scores or logits. A softmax converts scores into probabilities: Softmax is excellent at turning relative scores into an ordered probability simplex, but the numerical scale of the logits determines how sharp the resulting distribution is. If all logit differences are too large, the model can be systematically over-confident while still choosing the correct answers. If all logit differences are too small, the model can be systematically under-confident while still choosing the same answers. Temperature scaling directly targets that degree of freedom. Accessible softmax/temperature primer: Softmax function, Wikipedia
Worked example (the softmax over logits runs inside the inference server, not the benchmark):
from math import exp
def softmax(z, T=1.0):
w = [exp(zi / T) for zi in z]
return [wi / sum(w) for wi in w]
softmax([2.0, 1.0, 0.0]) # [0.6652, 0.2447, 0.0900]
softmax([2.0, 1.0, 0.0], T=2) # flatter: [0.5065, 0.3072, 0.1863]
train / calibrate / test split contractSplit membership is stored in the line-aligned metadata/*.jsonl files, not in the System One wire payload. Each metadata row contains exactly one:
{"split":"train"}
{"split":"calibrate"}
{"split":"test"}
| split | may train model | may fit calibration | published benchmark metrics |
|---|---|---|---|
train
|
yes | no | no |
calibrate
|
no | yes | no |
test
|
no | no | yes |
The benchmark currently creates no train rows by default. The one-time migration assigns approximately 20% of each suite to calibrate and the remainder to test by deterministic SHA-256 rank. Runtime tools then read the persisted field; they do not recompute split membership.
make assign-splits
The current repository validation reports:
train: 0
calibrate: 5,520
test: 22,078
total: 27,598
For ordinary 100-case suites this normally means 20 calibration rows and 80 test rows. GPQA Diamond has 198 rows and therefore receives 40 calibration rows and 158 test rows.
By repository structure, the same row is not simultaneously assigned to calibrate and test. This prevents direct calibration/test row reuse.
Disjoint rows are not automatically statistically independent. Synthetic cases can share generators, templates, source families, semantic structure, or latent difficulty factors. METHODOLOGY.md already notes that templated synthetic cases can be correlated. Therefore the scientifically correct interpretation is:
The test split is held out from direct calibration fitting.
It is stronger than evaluating on the calibration rows themselves, but it is not a proof that calibration and test observations are independent random variables, nor that benchmark test performance is an unbiased estimate of every possible production workload.
For one probability vector and temperature , The same operation can be written when every . If the inference engine has the original logits, it is preferable to apply the temperature there: because this avoids taking logarithms of rounded or underflowed probabilities. If only probabilities are available, a numerically stable implementation can use:
def temperature_scale(p, T, eps=1e-12):
logp = [math.log(max(eps, x)) / T for x in p]
m = max(logp)
w = [math.exp(x - m) for x in logp]
z = sum(w)
return [x / z for x in w]
The probability-space and logit-space forms are mathematically identical for strictly positive probabilities. With an implementation epsilon, zero-valued serialized probabilities are approximated rather than exactly inverted.
Implementation: temperature_scale(), scripts/calibration.py:70-80 - the probability-space form above, including the max-subtraction trick.
Assume Then After normalizing across , Therefore: for .
Implementation: the left-hand side is temperature_scale(), scripts/calibration.py:70-80; the right-hand side is the inference server's logit path, which the benchmark never sees.
For any two candidates , Therefore temperature scaling changes the strength of pairwise preference but not its direction. For , , so odds move toward . For , , so odds move farther away from . Hence:
Worked example (pairwise odds are a derived view, computed nowhere in the pipeline):
from math import sqrt
def scaled_odds(p, i, j, T):
return (p[i] / p[j]) ** (1 / T) # equals q[i] / q[j] after normalize(p ** (1/T))
p = [0.7, 0.2, 0.1]
scaled_odds(p, 0, 1, T=2) # sqrt(0.7 / 0.2) = 1.8708
# cross-check through the full transform:
# temperature_scale(p, 2) = (0.5229, 0.2795, 0.1976), and 0.5229 / 0.2795 = 1.8708
For , the function is strictly increasing for . Therefore: So: except for pre-existing exact ties, whose tie-breaking behavior is unchanged by the ideal mathematical transform. This gives an important invariant:
Positive temperature scaling cannot change the winning candidate of one decision.
Consequently hard argmax accuracy is mathematically unchanged. This guarantee applies to candidate ordering within a decision. It does not mean every conceivable ranking metric across different examples is unchanged, because confidence values can move by different amounts across examples.
Implementation: the argmax on each side of the transform at scripts/calibration.py:183-186 and scripts/score.py:109; the invariant is exercised by comparing raw vs calibrated accuracy in build_artifact(), scripts/calibration.py:308-311.
Suppose a noul answer reports Its odds are Set . Pairwise odds become: So the calibrated probabilities have odds : Equivalently: The binary decision remains true, but its probability changes from to . In binary form temperature scaling is: Platt-scaling primer: Platt scaling, Wikipedia. Temperature scaling is more restrictive than full Platt scaling: it uses one positive scale parameter and no learned intercept.
Worked example for the binary specialization (the benchmark always uses the general vector form, temperature_scale(), scripts/calibration.py:70-80, which reduces to this for K=2):
from math import exp, log
def scale_binary(p_true, T):
logit = log(p_true) - log(1 - p_true)
return 1 / (1 + exp(-logit / T))
scale_binary(0.9, T=2) # logit(0.9) = 2.1972; sigma(2.1972 / 2) = 0.75
The benchmark can fit one temperature for each sufficiently represented answer type:
choice
noul
score
This is a predeclared modeling choice, not a theorem that answer type is the only possible source of calibration heterogeneity. Other plausible sources include number of candidates, domain, capability, difficulty, prompt template, quantization, adapter, and model version. The reason to begin with question type is engineering parsimony:
This is substantially less flexible than capability-by-capability calibration and correspondingly harder to overfit. The repository has historically called this qtype-affine calibration. Strictly speaking, the transform used here is a zero-intercept linear scaling of logits within each qtype: "Qtype-stratified temperature scaling" is the more precise mathematical name.
A qtype receives its own fitted only when it reaches the configured minimum number of successful calibration examples. Underrepresented qtypes use the top-level global temperature. The current v2 implementation fits that global temperature on the pooled calibration corpus. This gives a stable fallback estimate, but when some qtypes also have dedicated temperatures it is not mathematically the same as fitting an optimum only on the remaining fallback subset. Accordingly, claims of exact within-family optimality apply to:
The pooled global fallback in a mixed artifact is a stability-oriented fallback, not a theorem that it is the exact optimum for the residual small-qtype subset.
Implementation: the zero-intercept logit scaling beta = 1.0 / temperature applied to log-probabilities at scripts/calibration.py:75-76, the per-qtype fit with the 100-case floor in fit_qtype_temperatures(), scripts/calibration.py:154-170, and the fallback lookup in _temperature_for(), scripts/calibration.py:138-143.
For calibration example , let:
The empirical calibration objective is: with: For the benchmark's deterministic one-hot gold labels this is ordinary mean categorical negative log-likelihood. For soft gold targets the same expression is empirical cross-entropy risk. Cross-entropy primer: Cross-entropy, Wikipedia. Because the implementation supports soft target distributions, empirical cross-entropy minimization is the most general description. For current one-hot benchmark targets, the same objective coincides with categorical maximum-likelihood estimation under the usual independent-case conditional model.
Implementation: the objective is never evaluated directly; its exact gradient drives the fit in _gradient() + fit_temperature(), scripts/calibration.py:83-118, and the same cross-entropy is reported as NLL at scripts/calibration.py:189 and scripts/score.py:112.
Let: and for one example define: Then: The cross-entropy for that example is: Expanding: Differentiate: The first term is an expectation under : or equivalently: Differentiate again: A mean of convex functions is convex, therefore the complete calibration objective is convex in . This gives the implementation an important property:
There are no non-global local minima in inverse-temperature space.
The derivative is monotone non-decreasing, so one-dimensional gradient bisection is sufficient once a search interval is chosen.
Implementation: the boxed gradient is _gradient(), scripts/calibration.py:83-97 verbatim (eq - ey per example), and the monotone bisection it justifies is fit_temperature(), scripts/calibration.py:100-118.
Worked example for the curvature (never evaluated by the implementation - bisection needs no second derivatives):
from math import log
def curvature(p, beta):
a = [log(pi) for pi in p]
q = softmax([beta * ai for ai in a]) # softmax as defined in section 2
mean = sum(qi * ai for qi, ai in zip(q, a))
return sum(qi * (ai - mean) ** 2 for qi, ai in zip(q, a)) # Var_q(a) >= 0
curvature([0.9, 0.1], beta=1) # E[a] = -0.3251, E[a^2] = 0.5402, Var = 0.4345
Convexity guarantees that every local optimum is global. It does not guarantee that the minimizer is always unique. Consider a prediction that is uniform: Then every is equal, so: The objective can therefore be flat in . The rigorous statement is:
The objective has a global minimum. It is unique when the aggregate objective is strictly convex over the relevant interval; degenerate data can produce a flat set of minimizers.
The implementation searches within: A fitted value at one of those search bounds should be interpreted cautiously: the unconstrained optimum may lie outside the supported interval, or the objective may be insufficiently informative near that direction. The artifact records whether the fitted temperature is at a search bound.
Implementation: the bounds MIN_TEMPERATURE / MAX_TEMPERATURE, scripts/calibration.py:48-49; at-bound detection at scripts/calibration.py:106-111, recorded as fit.temperature_at_search_bound at scripts/calibration.py:357-360.
Negative log-likelihood / cross-entropy is a proper scoring rule. Informally, a proper scoring rule is constructed so that, in expectation, a forecaster minimizes its loss by reporting its actual predictive distribution rather than strategically distorting it. For formal background: Tilmann Gneiting and Adrian E. Raftery, Strictly Proper Scoring Rules, Prediction, and Estimation, JASA 2007, doi:10.1198/016214506000001437. Accessible primer: Scoring rule, Wikipedia. NLL is also the exact fitting objective, which makes held-out NLL the most direct measure of whether the fitted transform generalized beyond calibration rows.
Lower is better. It evaluates the complete reported distribution and strongly penalizes assigning very little probability to the true outcome. Use: primary fitting objective and primary held-out calibration comparison.
Implementation: scripts/calibration.py:189 (aggregate) and scripts/score.py:112 (per case).
Lower is better. Brier score is also a proper scoring rule. Use: complementary full-distribution evaluation. Primer: Brier score, Wikipedia
Implementation: scripts/calibration.py:190 (aggregate) and scripts/score.py:113 (per case).
The implementation's ECE uses: and: Examples are placed into confidence bins : This is useful and intuitive, but evaluates only the winning confidence. It does not fully test the multiclass distribution and is bin-dependent. Vaicenavicius et al. discuss these subtleties: AISTATS 2019 (PMLR). ECE should therefore be treated as a diagnostic, not as the sole acceptance criterion.
Implementation: _ece(), scripts/calibration.py:121-135 and ece(), scripts/score.py:121-131; the per-bin breakdown behind the aggregate is reliability_bins(), scripts/calibration.py:204-223.
Positive temperature scaling preserves argmax, therefore: up to implementation/tie-breaking bugs. This is a useful invariant test.
Implementation: argmax comparison and the accuracy mean at scripts/calibration.py:183-198 and per case at scripts/score.py:109-111.
The benchmark also reports: This can be useful as a descriptive agreement measure. It is not invariant under temperature scaling. Example: Then: After : and: It is also not a proper scoring rule for general soft targets. For example: Reporting gives: whereas reporting: gives: So soft accuracy should not be used as the mathematical calibration objective.
Implementation: scripts/calibration.py:191 (aggregate) and scripts/score.py:114 (per case).
Temperature scaling is a one-dimensional shape correction. It is well suited to a common failure mode:
the model's ranking is useful, but the logit scale is systematically too sharp or too flat.
Suppose an ideal model would produce logits , but the deployed model approximately produces: Softmax is invariant to adding the same constant to every candidate: Choosing: gives: In this idealized failure mode, temperature scaling exactly corrects the probability distortion without changing the decision ordering. This is one reason temperature scaling can generalize well when miscalibration is dominated by a stable logit-scale effect.
Worked example for the idealized failure mode (a thought experiment - nothing in the pipeline synthesizes logits):
z_star = [2.0, 1.0, 0.0] # ideal logits
alpha, c = 2, 5 # observed distortion
z = [alpha * zi + c for zi in z_star] # deployed model logits
softmax(z) # [0.8668, 0.1173, 0.0159] - systematically over-confident
softmax(z, T=alpha) # [0.6652, 0.2447, 0.0900] - exactly softmax(z_star)
One scalar cannot express every calibration map. Examples it cannot generally repair perfectly:
low confidence → under-confident
high confidence → over-confident
or:
2-way choices → calibrated
12-way choices → over-confident
or:
domain A → over-confident
domain B → under-confident
when all of those cases share the same fitted temperature. A richer calibrator may be required if held-out diagnostics show structured residual miscalibration. Examples include isotonic regression, vector scaling, class-specific scaling, beta calibration, and instance-conditioned calibration. Kull, Silva Filho and Flach (AISTATS 2017) show why a richer parametric family can outperform simpler logistic calibration when the simple shape is misspecified: Kull, Silva Filho & Flach, AISTATS 2017 (PMLR). The engineering trade-off is capacity:
richer calibrators can fit richer distortions, but they also require more calibration data and create more opportunities to overfit.
The benchmark intentionally begins with a very low-capacity family.
This section is deliberately stronger than "it might work" but weaker than a universal guarantee. There are now two sources of support:
calibrate → held-out test generalization on this benchmark.Guo, Pleiss, Sun and Weinberger studied post-hoc calibration for modern neural networks in ICML 2017. Their practical conclusion was that temperature scaling - a single-parameter variant of Platt scaling - was surprisingly effective on most of the datasets they evaluated. Paper: Guo et al., ICML 2017 (PMLR). That result does not prove temperature scaling will work for every language model or every typed-decision endpoint. It does establish substantial historical empirical evidence that a one-parameter temperature correction can generalize from a held-out calibration set to a same-distribution test set.
A qtype temperature fit learns one scalar. Even with three fitted question types, the deployed calibrator contains only a handful of learned degrees of freedom. It cannot memorize individual benchmark examples, capability names, prompts, or labels. It can only express statements like:
choice distributions are systematically too sharp/flat by this scale
noul distributions are systematically too sharp/flat by this scale
score distributions are systematically too sharp/flat by this scale
That low capacity makes severe row-level overfitting much less plausible than with a flexible nonlinear calibrator. This is not a formal finite-sample guarantee, especially because benchmark cases are correlated, but it is a strong practical reason to expect better generalization behavior than a high-capacity post-hoc map with the same data budget.
The current benchmark reserves 5,520 rows for calibration across hundreds of capabilities. A qtype temperature is therefore learned from many semantically different tasks rather than one narrow classification problem. If a similar fitted temperature improves held-out test NLL across heterogeneous capabilities, that is evidence that the correction captures a deployment-wide property rather than one task-specific accident.
The strongest expected transfer is:
same model weights
same quantization
same inference code
same prompt template
same typed-decision readout
similar task distribution
calibrate rows → held-out test rows
Under those conditions, expecting temperature calibration to generalize is reasonable. The expectation becomes progressively weaker as those conditions change.
Fit only on split=calibrate, freeze the artifact, and evaluate on split=test. If held-out test NLL and Brier improve, then the correction generalized beyond the rows used to fit it on this benchmark. This is the primary generalization claim the benchmark can directly establish. EXPECTED before measurement. EMPIRICALLY SUPPORTED after measurement. For the Bonsai-2-27B reference deployment this Level-A claim has now been observed: held-out NLL and Brier both improved on 22,001 test examples after fitting only on 5,499 calibration examples.
If test improvement is broad across many capabilities, it becomes plausible that the same correction will help new typed decisions from a similar operational distribution. This is stronger than Level A and should remain an expected-transfer claim unless tested on genuinely new cases.
This is not guaranteed. Ovadia et al. studied predictive uncertainty under dataset shift and found that traditional post-hoc calibration can deteriorate as the evaluation distribution moves away from the calibration distribution: Ovadia et al., NeurIPS 2019. Therefore: Calibration should be treated as part of the exact inference configuration and rechecked when that configuration or its traffic distribution changes materially.
Pseudocode for the operational consequence (the benchmark ships no drift detector):
T_bench = fit(split_calibrate_rows) # frozen into calibration.json
T_prod = fit(fresh_labeled_production_rows) # refit after any suspected shift
if abs(T_prod - T_bench) > tolerance: # the distribution moved
recalibrate_and_refreeze() # treat it as a new calibration target
The fit itself minimizes calibration-set NLL, so calibration-set improvement is not evidence of generalization. The important evidence is held out. For each qtype, inspect at least:
test NLL: raw → calibrated
test Brier: raw → calibrated
top-label ECE: raw → calibrated
accuracy: raw = calibrated [invariant check]
Also inspect reliability bins, capability-level breakdowns, candidate-count breakdowns when relevant, raw-confidence distributions, and whether the fitted temperature lies at a search bound. A particularly convincing pattern is:
calibrate NLL improves
test NLL improves
test Brier improves
test ECE improves or remains reasonable
accuracy is unchanged
improvement appears across many capabilities
ECE alone is not enough because it is binned and only tests top-label confidence. The Bonsai-2-27B reference experiment satisfies the central proper-score part of this pattern: held-out NLL and Brier improve while hard accuracy is effectively unchanged. It also provides a useful counterexample to treating ECE as the only criterion: aggregate ECE worsens slightly even while both full-distribution proper scores improve.
The fitted temperature is a one-dimensional empirical risk estimator. Under standard regularity conditions, nondegenerate M-estimators often have sampling error that decreases on the order of: This gives the familiar rule:
multiplying effective sample size by four roughly halves estimator noise.
But that scaling law does not justify a universal numeric confidence interval from raw case count alone. The benchmark cases are not guaranteed IID. Examples within one synthetic family may be correlated, reducing effective sample size. For a general scalar M-estimator , the asymptotic variance has the sandwich form: where:
Only under additional likelihood-model assumptions does this simplify to a pure inverse-Fisher-information expression. Therefore the repository's default per-qtype minimum is best understood as an engineering data floor, not a theorem that 100 examples imply a particular standard error.
Pseudocode (the implementation reports the point fit and the at-bound flag, not a variance estimate):
# sandwich standard error for the fitted inverse temperature beta_hat
g = [grad_r(beta_hat) for r in examples] # per-example E_q[log p] - y . log p
H = mean(curvature_r(beta_hat) for r in examples) # mean Var_q(log p)
J = mean((gi - mean(g)) ** 2 for gi in g) # variance of the estimating equation
se_beta = sqrt(J / (H ** 2) / n) # Var(sqrt(n)(beta_hat - beta*)) ~ J / H^2
se_T = se_beta / beta_hat ** 2 # delta method back to T = 1 / beta
If confidence intervals for are to be published, prefer a bootstrap that respects known correlation structure. A practical version is:
choose clusters = suites or generator/template families
repeat B times:
sample clusters with replacement
collect their calibration examples
fit T
report:
median T
2.5th percentile
97.5th percentile
This is more defensible than pretending every templated row is independent. For qtype-specific fits, bootstrap the relevant qtype examples while preserving cluster membership.
Suppose the same data are used both to choose and to report improvement. The parameter was explicitly selected to minimize loss on those data. Consequently, its in-sample fitted loss is optimistically selected. That is ordinary model-selection bias. The exact amount of optimism depends on assumptions; it is not universally outside regular correctly specified likelihood settings. The benchmark therefore uses: This establishes row-level holdout:
no test row directly contributes to the fitted temperature.
That is the claim we need. We do not need to claim that the partitions are statistically independent in every latent sense.
Implementation: fitting reads only split=calibrate rows (scripts/calibration.py:296-298), and published metrics come from split=test only (split_keys(), scripts/score.py:77-84; build_report(), scripts/score.py:183-205).
Define: Apply , then another temperature : Therefore: Suppose is the interior optimum for a particular dataset and scalar temperature family. If the server applies exactly and the same dataset is fitted again, then the residual optimum should be: subject to numerical tolerance and non-uniqueness/degeneracy.
Implementation: both sides are repeated application of temperature_scale(), scripts/calibration.py:70-80, and the residual-fit fixed point is covered by test_temperature_fit_is_identity_when_prediction_matches_soft_gold, tests/test_calibration.py:25-28. Worked check:
p = [0.7, 0.2, 0.1]; T = 1.16; U = 0.77
temperature_scale(temperature_scale(p, T), U) # (0.735744, 0.180969, 0.083288)
temperature_scale(p, T * U) # (0.735744, 0.180969, 0.083288) - identical
Running the same benchmark again after loading the artifact is useful for detecting:
But if the second run uses the same benchmark rows, it is an implementation consistency check, not a fresh statistical hypothesis test. For stronger external evidence, perform the residual fit on genuinely new labeled data from the same target distribution. In the Bonsai-2-27B reference run, the already calibrated endpoint refitted to choice=0.99991057, noul=0.99959046, and score=0.99999629. This is an extremely close practical realization of the identity fixed point predicted by the composition theorem.
Run the selected benchmark without server-side calibration. Collect raw predictions for:
split=calibrate
split=test
Fit calibration.json from calibrate only. Freeze that artifact.
Before changing the server, apply the frozen artifact offline to Run A's test predictions. This gives:
raw test metrics
vs
offline-calibrated test metrics
Because test was not used to fit , this is the cleanest direct evidence of benchmark generalization.
Load exactly the frozen artifact into the server. Keep constant, as far as practical:
Run the same benchmark under a distinct run name. Then compare case by case: This checks that the production server implements the same transform the benchmark fitted.
Implementation: the right-hand side is the offline application of the frozen artifact by temperature_scale(), scripts/calibration.py:70-80 (exactly the offline evaluation in scripts/calibration.py:308-311); the left-hand side is the C++ calibration path in Bonsai-Llama-Jev.
For every test case:
offline temperature_scale(raw_A, T)
≈
served probability_B
within a documented floating-point tolerance. Also verify:
argmax(raw_A) == argmax(probability_B)
unless an exact pre-existing tie is present.
Recommended layout:
calibration/
├── calibration.json
├── before_stats.jsonl
├── before_cases.jsonl
├── after_stats.jsonl
├── after_cases.jsonl
├── before_calibration.json
├── after_calibration.json
└── provenance.json
Recommended provenance:
{
"model": "...",
"model_sha256": "...",
"quantization": "...",
"server_commit": "...",
"benchmark_commit": "...",
"prompt_template_sha256": "...",
"adapter_sha256": null,
"calibration_sha256": "...",
"before_run": "...",
"after_run": "..."
}
A model name and endpoint URL alone do not uniquely identify quantization, model bytes, prompt template, server implementation, or adapter state.
Apply calibration to the final candidate probability distribution:
prompt
↓
model forward pass
↓
candidate logits / scores
↓
construct final candidate distribution
↓
temperature scaling ← HERE
↓
derive typed answer fields
This matters for engines that construct a large candidate set through several conditional or multi-token readouts. If the benchmark fitted a temperature to the final candidate probabilities, applying temperature separately to intermediate conditional distributions is a different operation.
Compose the complete candidate distribution first, then apply its qtype temperature exactly once.
choiceGiven calibrated probabilities :
probabilities = q
choice = argmax(q)
The choice should equal the raw choice by the ordering proof. Any API-specific derived confidence field should be recomputed from , not copied from the raw response.
Implementation: argmax over the calibrated vector at scripts/score.py:109.
scoreGiven score levels :
probabilities = q
score = Σ k q_k
Temperature scaling preserves the most likely score level but can change the expected numeric score because it changes mass assigned to non-winning levels. Therefore score must be recomputed.
Implementation: the expected score sum(j * p_j) at scripts/score.py:117-118.
noulIf the API stores only: reconstruct: apply temperature scaling, then return the calibrated true probability.
Implementation: the (1 - p, p) reconstruction in distributions(), scripts/score.py:92-95.
confidenceFor calibration analysis, the benchmark derives top-label confidence from the probability vector: That is the value used by top-label ECE. An inference API may additionally expose a field named confidence with its own legacy or compatibility semantics. Those concepts should not be conflated. The calibration artifact modifies the probability distribution. Any derived API confidence field should subsequently be recomputed according to that API's definition.
Implementation: conf = max(p) at scripts/calibration.py:185 and scripts/score.py:111.
The current artifact uses:
{
"schema_version": 2,
"kind": "typed-decision-temperature-calibration",
"method": "temperature_scaling",
"scope": "per_qtype",
"temperature": 1.0,
"temperatures": {
"choice": 1.0,
"noul": 1.0,
"score": 1.0
}
}
Basic lookup:
T = artifact.get("temperatures", {}).get(
question_type,
artifact["temperature"],
)
A loader should at minimum validate:
schema_version == 2
kind == "typed-decision-temperature-calibration"
method == "temperature_scaling"
T is finite
T > 0
and validate deployment provenance when relevant identifiers are available.
deployable: true meansdeployable is a mechanical eligibility flag, not proof that the transform improves every future dataset. In the current implementation it primarily means:
The held-out test split does not control this flag. That separation is intentional: test results should describe evidence, not feed back into parameter selection or artifact eligibility. A production policy may choose to be stricter, for example by rejecting search-bound temperatures, missing exact model hashes, insufficient qtype data, or unacceptable held-out degradation.
The implementation searches: If the optimum is returned at a boundary, the artifact records that fact. A boundary result should be treated as a warning because:
A rigorous deployment policy should inspect or reject at-bound fits.
Implementation: the search bounds at scripts/calibration.py:48-49; the at-bound flag is emitted as fit.temperature_at_search_bound at scripts/calibration.py:357-360.
Calibration is a joint property of predictions and the distribution of outcomes that materialize. A temperature fitted for:
model A
quantization Q
template P
traffic distribution D1
need not be optimal for:
model A
quantization Q
template P
traffic distribution D2
Ovadia et al. provide large-scale evidence that uncertainty quality and post-hoc calibration can degrade under increasing dataset shift: Ovadia et al., NeurIPS 2019. The strongest defensible deployment statement is therefore:
A temperature fitted on representative calibration data is expected to transfer best to future data drawn from a similar distribution and the same inference configuration.
That is a meaningful expectation, not a universal invariance claim.
The reference experiment turns several previous expectations into observed evidence for one exact deployment. The frozen artifact was fitted on 5,499 calibration examples and evaluated on 22,001 disjoint test examples. Test NLL decreased from 0.438015 to 0.434996 and Brier from 0.235513 to 0.233939 in the offline held-out evaluation. The independently rerun calibrated server then produced test NLL 0.434984 and Brier 0.233932 - within approximately and , respectively, of the offline prediction. Finally, fitting another temperature layer to the already calibrated endpoint returned all qtype temperatures within 0.041% of 1. Therefore the following deployment-specific statement is supported:
On the held-out typed-decision-bench test distribution used in the 2026-09-22 Bonsai-2-27B reference experiment, qtype-stratified temperature scaling fitted only on the calibration split improved full-distribution NLL and Brier score, transferred to the independently rerun calibrated C++ server, and reached the expected near-identity residual-temperature fixed point.
This is a substantial empirical result. It still does not imply that the same temperatures are optimal for arbitrary future production distributions or materially different inference configurations.
For the exact reference deployment and benchmark distribution:
noul showed the strongest transfer, including a large ECE reduction;choice was already close to calibrated and required only a mild correction;score improved NLL/Brier even though top-label ECE worsened, demonstrating why no single diagnostic should replace proper-score evaluation;These observations are deployment-specific empirical evidence, not algebraic guarantees for every future model or traffic distribution.
For a large calibration sample from the same typed-decision deployment:
These are reasonable expectations, not algebraic guarantees.
The method does not by itself establish that:
Temperature scaling is an established member of the post-hoc calibration family. Guo et al. describe it as a one-parameter variant of Platt scaling. Full Platt scaling fits a logistic map with slope and intercept. Temperature scaling keeps only a positive scale: This restriction has useful consequences:
Implementation: scripts/calibration.py:75-76.
The benchmark's contribution is therefore not invention of temperature scaling itself. The engineering contribution is the typed-decision protocol around it:
explicit split contract
+ qtype stratification
+ portable calibration artifact
+ held-out evaluation
+ inference-engine loader contract
+ reproducibility/provenance workflow
Any stronger novelty claim should be based on a separate literature review.
Chuan Guo, Geoff Pleiss, Yu Sun, Kilian Q. Weinberger. On Calibration of Modern Neural Networks. ICML 2017, PMLR 70:1321–1330. Key relevance:
Juozas Vaicenavicius, David Widmann, Carl Andersson, Fredrik Lindsten, Jacob Roll, Thomas B. Schön. Evaluating model calibration in classification. AISTATS 2019, PMLR 89:3459–3467. Key relevance:
Yaniv Ovadia, Emily Fertig, Jie Ren, Zachary Nado, D. Sculley, Sebastian Nowozin, Joshua V. Dillon, Balaji Lakshminarayanan, Jasper Snoek. Can You Trust Your Model's Uncertainty? Evaluating Predictive Uncertainty Under Dataset Shift. NeurIPS 2019. Key relevance:
Tilmann Gneiting, Adrian E. Raftery. Strictly Proper Scoring Rules, Prediction, and Estimation. Journal of the American Statistical Association, 2007. Key relevance:
Meelis Kull, Telmo Silva Filho, Peter Flach. Beta calibration: a well-founded and easily implemented improvement on logistic calibration for binary classifiers. AISTATS 2017, PMLR 54:623–631. Key relevance:
Wikipedia is listed as an accessible primer, not as the evidentiary basis for the scientific claims above.
The most useful mental model is:
Temperature scaling does not make a model smarter. It estimates how strongly to trust the probability contrast the model already produces.
When dominant calibration error is a stable scale distortion, a single temperature can correct that distortion extremely efficiently. Because the calibrator has very low capacity and historical experiments have found temperature scaling effective across many same-distribution classification settings, good generalization from a large calibration split to a similar held-out test distribution is a reasonable expectation. The benchmark is designed to measure whether that expectation is actually true for each deployment. For the Bonsai-2-27B reference deployment, the first complete before/after experiment supports that expectation on the benchmark's held-out test partition: proper scores improved, the served calibrated run reproduced the offline prediction, and the residual temperature fit returned essentially identity for all three qtypes. The scientific claim should therefore be neither:
"It is only a heuristic and we know almost nothing."
nor:
"It guarantees honest probabilities everywhere."
The defensible middle is stronger and more useful:
Temperature scaling is a mathematically constrained, established post-hoc calibration method with strong historical empirical support. In this benchmark it is fitted only on explicit calibration rows and evaluated on held-out test rows. Because it learns only one scale parameter per sufficiently represented question type, it is expected to generalize well when calibration and deployment distributions are similar. That expectation is directly falsifiable through held-out NLL, Brier, top-label reliability, per-qtype analysis, and case-by-case verification of the deployed transform.
Two directions look most promising:
typed-decision-bench uses post-hoc temperature scaling: where:
calibrate split,test split.Implementation: temperature_scale(), scripts/calibration.py:70-80.
The benchmark can fit separate temperatures for choice, noul, and score questions when enough calibration examples are available. The method does not retrain the model and does not change its weights. For every finite , the transform preserves candidate ordering: Therefore the predicted answer is unchanged; only the probability distribution around that answer changes. The fitting objective is mean cross-entropy / negative log-likelihood (NLL). When parameterized by inverse temperature that objective is convex. Consequently, the implementation can find a global minimum with deterministic one-dimensional gradient bisection rather than a general-purpose stochastic optimizer. Temperature scaling is not an experimental idea invented for this benchmark. It is an established post-hoc calibration method. Guo et al. (ICML 2017) found that a single fitted temperature was surprisingly effective across most of the classification datasets and neural-network architectures they studied. That historical evidence, combined with the very low capacity of this calibrator (one scalar per sufficiently represented question type), gives a reasonable prior expectation that a temperature fitted on a large calibration split will generalize to a similar held-out distribution from the same deployment. That expectation is deliberately testable rather than assumed:
calibrate split
↓
fit T
↓
freeze calibration.json
↓
test split
↓
measure held-out NLL / Brier / top-label ECE
What does not follow is that one temperature remains optimal under arbitrary distribution shift. Ovadia et al. (NeurIPS 2019) showed that uncertainty and post-hoc calibration can degrade as the evaluation distribution moves away from the calibration distribution. A materially different model, quantization, prompt template, adapter, endpoint, or production distribution should therefore be treated as a new calibration target.
If you use typed-decision-bench or the qtype-stratified temperature scaling method, please cite this work:
@software{homberg2026bonsaillamajev,
author = {Homberg, Aron},
title = {typed-decision-bench: A Held-Out Benchmark And Qtype-Stratified Temperature Scaling Method For Language Models Turned Into Typed Decision Engines},
year = {2026},
version = {5},
publisher = {GitHub},
url = {https://github.com/kyr0/Bonsai-Llama-Jev},
license = {MIT}
}