Sub topic 5
Estimating how confident the small model is
A cascade needs one number per request: how likely is it that the small model's answer is good enough to ship? This chapter covers where that number comes from, how to compute it, and how to check that it means what you think it means.
This chapter assumes you can read and write basic Python, call a hosted model through an API, and understand tokens and per-token pricing. It also assumes you have seen the cascade function from the previous chapters, where call_small returns a (text, confidence) pair. Here we look at how that pair gets built.
Why the confidence score decides everything
The cascade has one decision point:
text, confidence = call_small(prompt)
if confidence >= threshold:
return text, "small"
return call_large(prompt), "large"If the score is informative, the cascade keeps the easy requests on the cheap model and escalates the hard ones. If the score is noise, you have two bad options. Either you escalate requests that did not need it, or you ship wrong answers from the small model.
A model does not hand you a trustworthy "I am 83% sure" value. You build one from signals you can observe. Every signal below is a proxy. It correlates with correctness to some degree, and that degree varies by task, model, and prompt style. The rest of the chapter is about measuring that correlation instead of assuming it.
Sources of a confidence signal
There are five common families. They differ in cost, in what they need from the API, and in how reliable they are.
| Signal | What you compute | Extra cost | Needs |
|---|---|---|---|
| Token log-probabilities | Aggregate the probability of the generated tokens | None | API that returns logprobs |
| Label probability | Probability of the chosen class among allowed labels | None | Logprobs for the first token |
| Self-consistency | Agreement among several sampled answers | N extra small-model calls | Sampling with temperature above 0 |
| Verbalized confidence | Ask the model to state a number | A few extra output tokens | Nothing |
| External check | Schema validation, tests, retrieval match, verifier | Varies | A task with checkable output |
Token log-probabilities
When a model generates text, it picks each token from a probability distribution. Many APIs can return the log-probability of each chosen token. A log-probability is the natural log of a probability, so it is 0 for certainty and increasingly negative for less likely tokens. You turn it back into a probability with math.exp.
The free signal here is that a model that was unsure while writing tends to pick low-probability tokens somewhere in the answer. The open question is how to combine many per-token values into one number. Three aggregations are common:
- Mean: the exponential of the average log-probability. This is the geometric mean of the token probabilities, and it is also the inverse of perplexity. It is stable across answer lengths.
- Minimum: the probability of the single least likely token. This catches one shaky token, such as a number or a name, inside an otherwise fluent answer.
- Product: the probability of the whole sequence. It shrinks with every extra token, so long answers always look unconfident.
import math
def confidence_from_logprobs(token_logprobs, how="mean"):
"""Collapse per-token log-probabilities into one value in [0, 1]."""
if not token_logprobs:
return 0.0
if how == "mean":
return math.exp(sum(token_logprobs) / len(token_logprobs))
if how == "min":
return math.exp(min(token_logprobs))
if how == "product":
return math.exp(sum(token_logprobs))
raise ValueError(f"unknown aggregation: {how}")
logprobs = [-0.05, -0.10, -2.30, -0.02]
for how in ("mean", "min", "product"):
print(how, round(confidence_from_logprobs(logprobs, how), 3))This prints mean 0.539, min 0.1, and product 0.085. The same answer gets three very different scores, so the aggregation you pick changes which requests escalate. Treat it as a tunable choice and compare options on labeled data, as described later in this chapter.
Only score the tokens that carry the answer
A long response contains boilerplate such as "Sure, here is the summary:". Those tokens are nearly certain and inflate the mean. If your output has structure, such as JSON with an answer field, score only the tokens inside the field that matters. For free-form text, the minimum is less diluted than the mean.
Label probability for classification
If the task is "pick one of a fixed set of labels", you can do better than aggregating. Constrain the model to answer with a single label and read the probability of that first token. Then normalize over the allowed labels only, so probability mass on irrelevant tokens does not distort the result.
import math
def label_confidence(label_logprobs):
"""label_logprobs maps each allowed label to its log-probability.
Returns (best_label, probability normalized over the allowed labels)."""
probs = {label: math.exp(lp) for label, lp in label_logprobs.items()}
total = sum(probs.values())
best = max(probs, key=probs.get)
return best, probs[best] / total
print(label_confidence({"billing": -0.4, "technical": -1.6, "other": -3.0}))Here billing wins with a normalized probability of about 0.75. Label probabilities are usually the best-behaved of the logprob signals, because the output is one decision and not a sequence.
Self-consistency
If the API gives you no logprobs, or the output is free text, you can sample the small model several times at a temperature above 0 and see whether the answers agree. A question the model really knows produces the same answer each time. A guess produces scattered answers.
from collections import Counter
def agreement_confidence(answers):
"""Return the most common answer and the fraction of samples that agree."""
counts = Counter(a.strip().lower() for a in answers)
best, n = counts.most_common(1)[0]
return best, n / len(answers)
print(agreement_confidence(["42", "42", "41", "42", "42"]))This prints ('42', 0.8). Two practical points matter here.
- Normalize before comparing. The example lowercases and strips whitespace. For numeric or structured answers, parse them first so that
"42","42.0", and" 42 "count as one answer. For free-form prose, exact matching almost never agrees, so you need a task-specific comparison such as extracted fields. - Count the cost. Five samples cost roughly five small-model calls. If the small model is 20 times cheaper than the large one, five samples still cost a quarter of one large call. A request that then escalates pays for the samples and the large call. Use the cost formulas from the cost chapter with
cost_smallset to the full sampling cost.
Samples can run in parallel, so latency grows little. Cost grows linearly.
Verbalized confidence
You can also ask the model to say how sure it is: "Answer, then give a confidence from 0 to 100." It is the only signal that works with any API and adds almost no cost. It is also the weakest. Models tend to report high numbers, often clustered at 90 or 95, whether or not they are right. The scores bunch together, so there is little resolution to separate good answers from bad ones.
Use it as a fallback or as one input among several, and always check it against labeled data. Parse it defensively, because the model may reply with text instead of a number:
import re
def parse_verbalized(reply, default=0.0):
"""Extract a 0-100 number from text like 'Confidence: 85' and scale to [0, 1]."""
match = re.search(r"(\d{1,3}(?:\.\d+)?)\s*%?", reply)
if not match:
return default
return min(float(match.group(1)), 100.0) / 100.0
print(parse_verbalized("Confidence: 85"))This prints 0.85. Note that it grabs the first number in the reply. In a real prompt, put the confidence on its own labeled line and match that line, so that a number inside the answer is not mistaken for it.
External checks
For some tasks you can verify the answer without a model. These checks are the most trustworthy signals when they exist:
- The output parses as valid JSON and matches the schema.
- Generated code compiles, or passes a few unit tests.
- A extracted date or ID appears verbatim in the source document.
- A SQL query runs without error on a test database.
A failed check is strong evidence to escalate. A passed check is weaker evidence of correctness, because well-formed output can still be wrong. A reasonable pattern is to force the confidence to 0 on a failed check and otherwise use a model-based score.
Calibration: does 0.8 mean 80%?
A score is calibrated if, among requests scored near 0.8, about 80% of the small model's answers are correct. Raw signals are often not calibrated. A mean-logprob score of 0.9 might correspond to 70% accuracy on one task and 97% on another.
Calibration matters because you choose a threshold by reading the score as a probability. If the score is poorly calibrated but still ranks requests correctly, the threshold still works, but you must pick it from data, not from the number's apparent meaning. Ranking quality is what the cascade needs most. Calibration is what lets you reason about the number directly.
To check, take a labeled sample, bucket requests by score, and compare each bucket's average score with its observed accuracy:
def reliability(records, bins=5):
"""records: list of (confidence, correct) pairs.
Returns (low, high, count, accuracy) for each non-empty bin."""
rows = []
for i in range(bins):
lo, hi = i / bins, (i + 1) / bins
bucket = [
ok for conf, ok in records
if lo <= conf < hi or (i == bins - 1 and conf == 1.0)
]
if bucket:
rows.append((lo, hi, len(bucket), sum(bucket) / len(bucket)))
return rows
records = [(0.95, True), (0.92, True), (0.85, True), (0.88, False),
(0.60, True), (0.55, False), (0.30, False), (0.25, False)]
for lo, hi, n, acc in reliability(records):
print(f"{lo:.1f}-{hi:.1f} n={n} accuracy={acc:.2f}")The output is:
0.2-0.4 n=2 accuracy=0.00
0.4-0.6 n=1 accuracy=0.00
0.6-0.8 n=1 accuracy=1.00
0.8-1.0 n=4 accuracy=0.75The top bin has an average score near 0.9 but only 75% accuracy, so this signal is overconfident there. Eight records is only enough to show the mechanics. A real check needs hundreds of labeled requests, with enough in each bin for the accuracy figure to mean something.
If the curve is monotonic, meaning accuracy rises with score, you can repair calibration cheaply. Fit a small mapping from raw score to observed accuracy, such as isotonic regression or a lookup table over bins. This is also where a combined score is built: feed several raw signals into a simple logistic regression trained on "was the small answer correct?". That is a lightweight cousin of the learned router covered in a later chapter.
Failure modes
- Confident and wrong. Models can assign high probability to a fluent falsehood. No signal removes this, which is why the evaluation chapter measures how often the cascade lets wrong small answers through.
- Length and format effects. Token-level scores shift with answer length and style. Re-check them if you change the prompt or output format.
- Score drift across tasks. One threshold rarely fits all request types. A score tuned on summarization may behave differently on extraction. Calibrate per task type where volume allows.
- Model version changes. A provider update can change the logprob distribution. Your old threshold may quietly stop meaning what it did.
- Missing logprobs. Some APIs and some model families do not return them. Design the interface so
call_smallcan use whichever signal is available.
Putting it together
A practical call_small for a classification task could combine two signals conservatively, so the cascade escalates if either is weak:
def combined_confidence(label_conf, passed_schema_check):
"""Take the weaker of the model-based score and the external check."""
if not passed_schema_check:
return 0.0
return label_confTaking the minimum is a defensible default, because escalation costs money while a wrong shipped answer costs trust. Whatever rule you choose, treat it as a hypothesis, and test it with the threshold sweep in the evaluation chapter.
Exercise
A small model answers a numeric question five times at temperature 0.7 and returns "18", "18", "18.0", "17", "18". Using the agreement method from this chapter with simple lowercase-and-strip normalization, what confidence do you get, and what one change would improve it?
Show answer
With only lowercasing and stripping, "18.0" counts as a different answer, so the counts are "18": 3, "18.0": 1, "17": 1. The confidence is 3/5 = 0.6. Parsing each answer as a number before counting would merge "18" and "18.0", giving 4/5 = 0.8.
Exercise
A reliability check shows that requests with a mean-logprob score of 0.9 or above are correct only 70% of the time, but accuracy still rises steadily as the score rises. Is the signal useless for a cascade? What do you do about it?
Show answer
No. A signal that ranks requests correctly is useful even when it is miscalibrated. The raw number cannot be read as a probability, so you choose the threshold from labeled data, for example with a sweep, instead of assuming 0.9 means 90%. You can also fit a mapping such as isotonic regression to turn the score into a calibrated probability.