Sub topic 5
Estimating how confident the small model is
This chapter assumes you can call a hosted model from Python, know what tokens are, and have read the previous chapters on rule-based routing. A cascade needs one number per answer, a confidence score. The threshold check confidence >= threshold is only as good as that number.
What a confidence score is for
In a cascade, the small model answers first. A confidence score estimates how likely that answer is to be correct. High-confidence answers are returned. Low-confidence answers go to the large model.
Models do not report correctness directly, so you build the score from signals you can measure. Three signals are common.
Signal 1: token probabilities
Many APIs can return the log-probability of each generated token. A log-probability is the natural logarithm of the probability the model gave that token. Values are 0 or negative, and values near 0 mean the model was sure.
Averaging these and converting back gives the geometric mean token probability:
import math
def confidence_from_logprobs(logprobs):
"""Geometric mean of token probabilities, in the range 0 to 1."""
if not logprobs:
return 0.0
return math.exp(sum(logprobs) / len(logprobs))
print(confidence_from_logprobs([-0.05, -0.10, -0.02])) # about 0.95
print(confidence_from_logprobs([-1.2, -0.9, -2.0])) # about 0.25This signal costs nothing extra, because the logprobs come with the answer. It works best for short, constrained outputs such as a label or a number. For long free-form text, one unusual word choice lowers the average even when the answer is correct. You can score only the tokens that carry the answer instead of the whole reply.
Signal 2: agreement across samples
Ask the small model the same question several times with a temperature above zero. If the answers mostly match, the model is probably on firm ground. If they scatter, it is probably guessing.
from collections import Counter
def agreement_confidence(answers):
"""Return the most common answer and the fraction of samples that gave it."""
counts = Counter(a.strip().lower() for a in answers)
top, n = counts.most_common(1)[0]
return top, n / len(answers)
print(agreement_confidence(["Paris", "paris", "Paris", "Lyon", "Paris"]))
# ('paris', 0.8)This works for free-form text too, as long as you can decide when two answers match. It multiplies the small model's cost by the number of samples. With five samples, the small model must stay well under one fifth of the large model's price for the cascade to pay off.
Signal 3: self-reported certainty
You can ask the model to rate itself, for example "Answer, then give your confidence from 0 to 100." This needs no special API support. It is also the weakest signal. Small models tend to report high certainty whether or not they are right, and the numbers cluster around 80 to 95. Use it only when the other two are unavailable, and calibrate it as described below.
Making the score fit the cascade
The cascade from the Topic Spine expects call_small to return (text, confidence). This sketch wraps a sampling function so it does:
from collections import Counter
def make_call_small(sample_fn, n=5):
"""sample_fn(prompt) returns one answer string. Returns a call_small function."""
def call_small(prompt):
answers = [sample_fn(prompt) for _ in range(n)]
counts = Counter(a.strip().lower() for a in answers)
top, k = counts.most_common(1)[0]
return top, k / n
return call_small
fake_samples = iter(["4", "4", "4", "5", "4"])
call_small = make_call_small(lambda prompt: next(fake_samples))
print(call_small("What is 2 + 2?")) # ('4', 0.8)Calibration: does 0.8 mean 80% correct?
A score is calibrated when answers scored near 0.8 are correct about 80% of the time. Raw scores usually are not. Models are often overconfident, so a score of 0.9 may correspond to 70% accuracy.
Check this on a labeled sample. Group answers by score and compare each group's average score to its actual accuracy:
def calibration_table(records, bins=5):
"""Each record: {"confidence": float, "correct": bool}."""
rows = []
for i in range(bins):
low, high = i / bins, (i + 1) / bins
group = [r for r in records
if low <= r["confidence"] < high or (i == bins - 1 and r["confidence"] == 1.0)]
if group:
avg_conf = sum(r["confidence"] for r in group) / len(group)
accuracy = sum(r["correct"] for r in group) / len(group)
rows.append((f"{low:.1f}-{high:.1f}", len(group), round(avg_conf, 2), round(accuracy, 2)))
return rowsRows where accuracy is far below average confidence show overconfidence. You do not have to fix the scores to use them. You only need higher scores to mean higher accuracy, because the threshold is then tuned on real data in the evaluation chapter.
Common errors
- Treating the raw score as a probability and picking a threshold such as 0.8 without measuring.
- Computing logprob confidence over a long reply, where unrelated tokens dominate the average.
- Sampling at temperature 0, so every sample is identical and agreement is always 1.0.
- Calibrating on one task type and reusing the threshold on another.
Exercise
A small model answers a question five times at temperature 0.7 and returns "42", "42", "41", "42", "40". What are the top answer and its agreement confidence? Would a cascade with threshold 0.8 keep the small model's answer?
Show answer
The top answer is "42" and it appears 3 times out of 5, so the confidence is 0.6. Since 0.6 is below 0.8, the cascade escalates the request to the large model.