LLM Evaluation and Observability Questions
Measuring, monitoring and releasing generative and LLM-powered systems. Covers evaluation of open-ended outputs (human review, calibrated model-graded judges, reference-based and embedding scores, perplexity), hallucination, toxicity, privacy-leak and red-team checks, offline benchmarks versus online monitoring, and production observability (logs, traces, metrics, cost and token attribution, privacy-safe telemetry, drift and quality alerts). Also release decisions: A/B tests, canary rollouts, SLOs and go or no-go gates. Building the grounding architecture itself, calibration of predictive models and general software testing are covered elsewhere.
How would you automatically detect hallucinations in long-form LLM answers when there are no gold labels for each response? Describe the checks, how you would combine them into one score, and where the approach breaks down.
Sample Answer
Direct answer
With no gold label per response, break the answer into atomic claims and test each claim with several independent checks: is it supported by the evidence the system had, do repeated samples of the model agree on it, and do its numbers and names appear in the evidence. Turn each check into a risk number, combine them into a claim risk and then a response score, and use the score to triage and rank, not as a probability of being wrong until it is calibrated on a small human-labelled sample. The approach breaks where the checks share a blind spot: a hallucination the model repeats every time, evidence that is itself wrong, and true statements the evidence never mentions.
The checks
- Claim extraction. Split the long answer into atomic claims (one checkable fact each). A model usually does this; in the example below the split is written by hand.
- Evidence support. For each claim, find the best-matching evidence passage and score whether it entails (logically supports) the claim. A natural-language-inference model (one that reads a passage and a claim and says whether the passage implies it, contradicts it or says nothing about it) or a judge model fills this role. The program uses a stand-in: the highest TF-IDF cosine similarity against the evidence sentences. TF-IDF weights each word by how rare it is across the texts, and cosine similarity compares two such word-weight lists on a scale from 0 (no shared weighted words) to 1 (the same words), so it measures vocabulary overlap, not entailment.
- Self-consistency. Sample the model several times on the same question and measure how many samples repeat the claim's key facts (its numbers, number words and names; the program finds them with a crude rule, digits, words like "eight", and capitalised words after the first word, where a real system would use a named-entity model). Facts the model invents tend to vary between samples. In the program the five samples are hand-written stand-ins for model samples.
- Hard checks. Every number, date and proper name in the claim must appear in the evidence. The program tests the same key facts as check 3, matching whole tokens so that a claim saying 50 metres does not pass because the evidence contains 503. A claim with none of them has nothing to test and passes this check without proof, which is why the other checks must carry the weight there.
- Model confidence (when token probabilities are available): low probability on the tokens that carry the fact is a further signal.
Combining into one score
For claim c with support sc (check 2), consistency kc (check 3) and hard-check result nc (check 4; 1 if passed, else 0). Check 1 produces the claims, and check 5 is left out of the formula because the stand-in has no token probabilities:
riskc=1−(w1sc+w2kc+w3nc)where the weights w1,w2,w3 are non-negative and sum to 1. The response score is the mean claim risk for a quality trend, and the maximum claim risk for gating, because one false claim can sink a long answer. Fit the weights if you can: have people label 200 or more claims as wrong (1) or fine (0), then run a logistic regression, a model that learns a weight for each of the three check values (plus an offset) so that its output between 0 and 1 matches those labels. Its output replaces the hand-set weighted sum and is a probability that the claim is wrong; the learned weights are not constrained to sum to 1, and with all three checks on the same 0 to 1 scale, a check with a larger weight separates wrong claims from fine ones more. The program uses 0.5, 0.3, 0.2 chosen by hand for illustration, so its risk is a ranking score, not yet a calibrated probability (calibrated means that claims scored 0.3 turn out wrong about 30% of the time).
Computed example
import os
os.environ["OMP_NUM_THREADS"] = "1"
import re
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
evidence = [
"The bridge opened in 1932 and spans 503 metres across the harbour.",
"Its architect, Ralph Freeman, also advised on the design of a similar bridge in Newcastle.",
"The bridge carries eight road lanes and two rail tracks.",
]
# Long-form answer split into atomic claims by hand (a real system uses a model to extract claims)
claims = [
"The bridge opened in 1932.",
"The bridge spans 503 metres.",
"The architect was Ralph Freeman.",
"The bridge carries eight road lanes.",
"The bridge was painted green in 1950.",
"The architect was Ralph Jones.",
]
# Five extra sampled answers to the same question (hand-written stand-ins for model samples)
samples = [
"Opened in 1932, spans 503 metres, designed by Ralph Freeman, eight lanes, painted green in 1950.",
"It opened 1932 and is 503 metres long. Ralph Freeman was the architect. It was painted grey.",
"Opened 1932; 503 metres; eight lanes; painted green in 1950.",
"The bridge opened in 1932, designed by Ralph Freeman. It was painted green in 1950.",
"Ralph Freeman designed it; 503 metres; opened in 1932; green paint added in 1950.",
]
NUMBER_WORDS = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}
def key_facts(c):
# Checkable facts in a claim: digit strings, number words, and capitalised words after the first word
# (a crude proper-name detector; a real system would use a named-entity model).
words = re.findall(r"[A-Za-z0-9]+", c)
return [w for i, w in enumerate(words)
if w.isdigit() or w.lower() in NUMBER_WORDS or (i > 0 and w[0].isupper())]
def words_of(text):
# Whole tokens, so that "50" is not found inside "503"
return set(re.findall(r"[a-z0-9]+", text.lower()))
vec = TfidfVectorizer().fit(evidence + claims)
E = vec.transform(evidence)
rows = []
for c in claims:
# Check 2, evidence support (stand-in for an entailment model): best TF-IDF cosine against any evidence sentence
support = float((vec.transform([c]) @ E.T).toarray().max())
# Check 3, self-consistency: share of other samples that repeat every key fact of the claim
kf = key_facts(c)
consist = float(np.mean([all(f.lower() in words_of(s) for f in kf) for s in samples]))
# Check 4, hard check: every number, number word and name in the claim must appear in the evidence
facts_ok = all(f.lower() in words_of(" ".join(evidence)) for f in kf)
rows.append((c, support, consist, facts_ok))
w = np.array([0.5, 0.3, 0.2]) # weights chosen by hand for illustration; in practice fit on a small labelled set
print(f"{'claim':42s} support consist facts risk")
risks = []
for c, s, k, n in rows:
risk = 1 - float(w @ np.array([s, k, float(n)]))
risks.append(risk)
print(f"{c:42s} {s:.2f} {k:.2f} {str(n):7s} {risk:.2f}")
print("response score (mean claim risk):", round(float(np.mean(risks)), 3),
" worst claim risk:", round(float(max(risks)), 3))
It prints:
claim support consist facts risk
The bridge opened in 1932. 0.58 1.00 True 0.21
The bridge spans 503 metres. 0.61 0.80 True 0.25
The architect was Ralph Freeman. 0.38 0.80 True 0.37
The bridge carries eight road lanes. 0.68 0.40 True 0.34
The bridge was painted green in 1950. 0.16 0.80 False 0.68
The architect was Ralph Jones. 0.23 0.00 False 0.89
response score (mean claim risk): 0.457 worst claim risk: 0.887
Reading it:
- The invented claim "painted green in 1950" has risk 0.68: support is only 0.16 and the hard check fails (1950 is not in the evidence). The invented name "Ralph Jones" is riskier still, 0.89: support 0.23, consistency 0.00 because no sample says Jones, and the hard check fails because Jones is not in the evidence. A digits-only check has nothing to test in that claim and would pass it, which is why the program also checks names and number words.
- Its consistency is still 0.80, because four of the five samples repeat it. A consistency check alone would have trusted it. This is the case where the model hallucinates the same thing every time.
- The true claim "carries eight road lanes" has consistency 0.40, since most samples omit the detail. Low agreement can mean omission, not falsehood, so consistency should add risk, never decide alone.
- The mean claim risk is 0.457 and the worst claim risk is 0.887. A gate on the worst claim sends this response to review; the mean sits mid-range and hides that two of the six claims are invented.
- What the scales mean here: support is a 0 to 1 overlap score, and even true claims land between 0.38 and 0.68 because the claim's wording differs from the evidence sentence, while the invented ones land at 0.16 and 0.23. Risk is also 0 to 1, but 0.34 for a true claim and 0.37 for another true one show that a fixed gate such as 0.5 is a guess. Pick the gate on the 100 to 300 labelled responses described below, as the value that catches most of the wrong responses at a review load you can afford.
Where it breaks down
- Consistent hallucination: repeated by every sample, so the consistency check passes. Only the evidence and hard checks catch it.
- Wrong or stale evidence: support to a wrong document looks like faithfulness. Check document versions and sources separately.
- True but unsupported claims: general knowledge the evidence does not contain is flagged as risk. Decide per product whether outside knowledge is allowed.
- Checker error: the claim extractor drops or merges claims, and a lexical or NLI checker is fooled by negation and paraphrase (the TF-IDF stand-in gives "Ralph Freeman" only 0.38 although the evidence supports it).
- Cost: consistency needs several extra samples per response; sample on a fraction of traffic.
Validate the final score on 100 to 300 human-labelled responses: check that high-risk responses contain far more labelled errors, and pick the gate threshold from the precision and recall that you see there.
Running the code
The program needs numpy and scikit-learn. Copy it into a file and run it with python; it takes a few seconds.
How would you surface and quantify hallucinations in a code-generation model, such as calls to APIs that do not exist? What would you verify against, and how do you turn that into a per-response factuality score?
Sample Answer
Direct answer
Hallucinated APIs are a good case for verification against ground truth (an independent, trusted record of what is actually true, which here is the library itself), because code has an external source of truth that prose does not. Extract every call, import and symbol the model produced, resolve each against the real library (to resolve a symbol means to look the name up and see whether it exists; use the version you target, or its documentation index), run the code's tests where they exist, and score each response by the fraction of checked references that resolve and the fraction of tests that pass. Report the rates across a benchmark of prompts, with the library version stated, and separate "never existed" from "existed in an older version".
What to verify against
- Static symbol resolution. Parse the generated code into a syntax tree (the nested structure of imports, calls and attributes that Python builds from the text, which a program can walk without running the code), map import aliases (the short names set by lines like
import numpy as np, wherenpstands fornumpy), and check that eachmodule.attribute.callexists in the version you target. This is cheap and runs without executing untrusted code. - Signature checks. Compare the call's argument names and count with the real signature (introspection, which means asking a live object about itself, such as the parameter names of a function, or a documentation index): a function can exist while the keyword argument is invented.
- Execution against tests, in an isolated sandbox with no network, resource limits and a timeout. Tests catch wrong behaviour that valid names do not.
- Documentation retrieval check for libraries you cannot import: look the symbol up in an indexed copy of the official docs.
- Pin versions. An API that was removed in a later release is a different failure ("outdated") from one that never existed ("fabricated"). Record the version for both.
A computed example
The program below parses six short hand-written snippets that imitate typical generated code (they are illustrations, not output observed from any model, so the rates it prints show the arithmetic and say nothing about how often a real model hallucinates), maps imports, and resolves each referenced call against the real library (it imports only an allow-list, a short fixed list of modules it is willing to import, to resolve names; it never runs the generated code). It is a minimal illustration: it handles plain import and from ... import calls on attribute chains, does not check signatures, does not follow variables or methods on objects, and treats modules outside the allow-list as unverifiable. A production verifier must also handle those cases, version matrices and sandboxed execution.
import ast, importlib, numpy, sys
ALLOWED = {"math", "os", "json", "numpy", "re"} # modules we are willing to import for resolution (illustration)
def resolve(mod_name, attrs):
if mod_name not in ALLOWED: return "unverifiable"
obj = importlib.import_module(mod_name)
for a in attrs:
if not hasattr(obj, a): return "missing"
obj = getattr(obj, a)
return "ok"
def check(code):
tree = ast.parse(code)
alias = {}
for n in ast.walk(tree):
if isinstance(n, ast.Import):
for a in n.names: alias[a.asname or a.name] = a.name
elif isinstance(n, ast.ImportFrom) and n.module in ALLOWED:
for a in n.names:
alias[a.asname or a.name] = None
if not hasattr(importlib.import_module(n.module), a.name): alias[a.asname or a.name] = "BAD:" + n.module + "." + a.name
results = []
for n in ast.walk(tree):
if isinstance(n, ast.Call):
chain = []; f = n.func
while isinstance(f, ast.Attribute): chain.append(f.attr); f = f.value
if isinstance(f, ast.Name) and f.id in alias and alias[f.id] and not alias[f.id].startswith("BAD:") and chain:
results.append((alias[f.id] + "." + ".".join(reversed(chain)), resolve(alias[f.id], list(reversed(chain)))))
elif isinstance(f, ast.Name) and f.id in alias and alias[f.id] and alias[f.id].startswith("BAD:"):
results.append((alias[f.id][4:], "missing"))
return results
snippets = {
"g1": "import math\nx = math.sqrt(2) + math.hypot(3, 4)\n",
"g2": "import math\nx = math.sqroot(2)\n",
"g3": "import numpy as np\na = np.zeros(3)\nb = np.linalg.solve(np.eye(3), a)\n",
"g4": "import numpy as np\nx = np.float_(1.0)\ny = np.linalg.fast_inverse(np.eye(2))\n",
"g5": "import os\np = os.path.join('a', 'b')\nos.makedirs_safe(p)\n",
"g6": "import json\nfrom math import cube_root\ns = json.dumps({})\nx = cube_root(27)\n",
}
print("numpy", numpy.__version__, "python", sys.version.split()[0])
total_ok = total = 0
for k, code in snippets.items():
res = check(code)
ok = sum(1 for _, s in res if s == "ok"); bad = [c for c, s in res if s == "missing"]
total_ok += ok; total += len(res)
print(f"{k}: calls checked {len(res)}, resolve {ok}, score {ok/len(res):.2f}, missing {bad}")
assert check(snippets["g2"]) == [("math.sqroot", "missing")] and check(snippets["g1"])[0][1] == "ok"
print(f"corpus: {total_ok}/{total} = {total_ok/total:.3f}")
Output:
numpy 2.1.3 python 3.12.15
g1: calls checked 2, resolve 2, score 1.00, missing []
g2: calls checked 1, resolve 0, score 0.00, missing ['math.sqroot']
g3: calls checked 3, resolve 3, score 1.00, missing []
g4: calls checked 3, resolve 1, score 0.33, missing ['numpy.float_', 'numpy.linalg.fast_inverse']
g5: calls checked 2, resolve 1, score 0.50, missing ['os.makedirs_safe']
g6: calls checked 2, resolve 1, score 0.50, missing ['math.cube_root']
corpus: 8/13 = 0.615
How check works, on one snippet: for each snippet it first walks the tree for import lines and fills alias, a dictionary from the name used in the code to the real module name (np to numpy). For from math import cube_root it instead tests whether math really has that name; if it does not, the dictionary stores a marker string starting with BAD: so the later call to cube_root(...) is reported as missing. (A name that imports successfully with from ... import is not counted as a checked call by this minimal program.) It then walks the tree again for every call. A call like np.linalg.fast_inverse(...) is a chain of attribute lookups: the code peels them off from the outside, collecting fast_inverse, then linalg, until it reaches the plain name np; it reverses the list to get linalg, fast_inverse, looks np up in alias to get numpy, and calls resolve, which asks hasattr at each step. The snippet g4 is traced below with exactly that logic:
import ast, numpy
code = "import numpy as np\nx = np.float_(1.0)\ny = np.linalg.fast_inverse(np.eye(2))\n"
tree = ast.parse(code)
alias = {}
for n in ast.walk(tree):
if isinstance(n, ast.Import):
for a in n.names:
alias[a.asname or a.name] = a.name
print("alias map:", alias)
for n in ast.walk(tree):
if isinstance(n, ast.Call):
chain, f = [], n.func
while isinstance(f, ast.Attribute): # peel one attribute at a time, outermost first
chain.append(f.attr)
f = f.value
names = list(reversed(chain))
obj, status = numpy, "ok"
for a in names:
if not hasattr(obj, a):
status = "missing at '" + a + "'"
break
obj = getattr(obj, a)
print(f"{ast.unparse(n.func):22} root '{f.id}' -> {alias[f.id]}, attributes {names}, result: {status}")
Output:
alias map: {'np': 'numpy'}
np.float_ root 'np' -> numpy, attributes ['float_'], result: missing at 'float_'
np.linalg.fast_inverse root 'np' -> numpy, attributes ['linalg', 'fast_inverse'], result: missing at 'fast_inverse'
np.eye root 'np' -> numpy, attributes ['eye'], result: ok
Three calls are found: np.float_ is missing, np.linalg.fast_inverse is missing because numpy.linalg has no such name, and np.eye resolves. That is 1 of 3 resolving, the 0.33 score printed for g4 above.
Reading the output:
- Snippets g1 and g3 resolve fully (score 1.00). g2 calls
math.sqroot, which does not exist (score 0.00). g4 has one resolving call (np.eye) and two missing ones:np.linalg.fast_inverse(invented) andnp.float_, which does not exist in NumPy 2.1.3 (it was a valid alias in older releases, so this is an outdated-API case rather than a fabricated one; a verifier targeting an older version would score it differently). g5 inventsos.makedirs_safe; g6 imports a namemath.cube_rootthat does not exist. - The per-response factuality score is resolved references divided by checked references: 0.50 for g5 and g6, 0.33 for g4. The corpus-level figure is 8 of 13 checked references, 0.615. Report the share of responses with at least one unresolved reference (here 4 of 6), because a single fabricated call breaks a program, so the average score understates harm.
- The assert (it would fail if resolution wrongly accepted
math.sqroot) passed.
Turning it into a metric you can trust
- Define the unit: per reference, per response, or per task (does the program run and pass its tests?). The task-level pass rate is the headline; reference-level scores diagnose.
- Sample size: a hallucination rate is a proportion (a count out of a total), so report an interval around it, so two model versions are not ranked on a difference smaller than the interval. Two standard choices: the Wilson interval, a closed-form formula that stays sensible with small samples and rates near 0 or 1, and the exact interval, which is computed directly from the binomial distribution and is a little more cautious (wider), as the output below shows. For example, with 13 of 60 checked responses containing an invented symbol:
from scipy.stats import binomtest
k, n = 13, 60 # 13 of 60 checked responses contained an invented symbol
r = binomtest(k, n)
print("observed rate:", round(k / n, 3))
for method in ("wilson", "exact"):
ci = r.proportion_ci(confidence_level=0.95, method=method)
print(f"{method:7} 95% interval: {ci.low:.3f} to {ci.high:.3f}")
Output:
observed rate: 0.217
wilson 95% interval: 0.131 to 0.336
exact 95% interval: 0.121 to 0.342
The rate is 0.217, but the data are consistent with a true rate anywhere from roughly 0.13 to 0.34, which is why 60 responses cannot separate two models whose rates differ by a few points (scipy 1.14.1).
- Stratify (split the results into groups and report each group separately) by library popularity, API age and prompt type; hallucination tends to concentrate on rare or fast-changing libraries, and a benchmark of only popular functions hides that.
- Mitigation loop: retrieval of current documentation into the prompt, a verifier that rejects and regenerates when a symbol fails to resolve, and tests run before the answer is shown.
Limits and mistakes
Resolution proves a name exists, not that it is used correctly; a call can resolve and still be semantically wrong, so keep tests in the score. Do not execute unreviewed code outside a sandbox (an isolated environment with no access to your files or network). Do not average over versions without recording which version each result used. Dynamic features (attributes created at runtime, plugins) cause false "missing" results, so review a sample of flagged items by hand to estimate the verifier's own error rate.
Why are n-gram overlap scores a weak measure of quality for generated text such as translations and summaries, and when do embedding-based similarity scores track human judgment better? How would you combine automatic scores with human evaluation?
Sample Answer
Direct answer
N-gram overlap scores (BLEU, ROUGE, METEOR) count how many word sequences a generated text shares with a reference. That is a proxy for meaning that fails in both directions: a correct paraphrase shares few words with the reference and scores low, while a text that copies the reference wording but flips one fact scores high. Embedding-based scores compare meaning-vectors instead, so they track human judgment better when the quality difference is about wording, and still miss negation and factual errors. Combine automatic scores as a cheap filter and regression alarm, and let a sampled, calibrated human comparison make the decision.
The metrics, defined
- N-gram: a run of n consecutive words; a unigram is one word, a bigram is two.
- BLEU: the geometric mean of n-gram precisions (share of the generated n-grams that appear in the reference, for n from 1 to 4) multiplied by a brevity penalty so short outputs cannot win. Built for machine translation (MT).
- ROUGE: overlap with a reference summary, originally recall-oriented (share of the reference n-grams that the output recovered). ROUGE-1 uses unigrams, ROUGE-2 bigrams. The program below reports the F1 version (harmonic mean of precision and recall).
- METEOR: aligns words between output and reference in stages (exact match, then stem match, then synonym match) and combines precision and recall with recall weighted more, plus a penalty for scrambled order. Because of the stem and synonym stages it gives credit for "increased" versus "raised" where BLEU gives none.
- Embedding-based scores: each text becomes a vector (a list of numbers) from an embedding model (a neural network trained so that texts with similar meaning get nearby vectors), and the score is the cosine similarity (the angle between vectors) between output and reference. Variants compare token-level embeddings and match them greedily.
Why overlap misleads: a computed example
Reference: "the company raised its prices last year". Three candidates: a correct paraphrase, a negated (wrong) sentence that reuses the wording, and a sentence that copies the wording but changes one word to an unrelated claim.
Two stand-ins are used and named here: the embedding scores come from a small hand-built table of word vectors (a stand-in for a trained embedding model), and the "METEOR-like" score is a simplified exact-plus-synonym alignment with a tiny synonym table and no order penalty, not the full METEOR. BLEU is nltk 3.9.1's sentence BLEU with smoothing method 1. The perplexity lines use hand-set per-token log-probabilities, not model output. The last block is a sign test on a hand-written win/loss/tie tally for a summarization release decision. In the code, toks is a deliberately simple tokenizer (it lowercases and splits on spaces; real systems split text into words or word pieces called tokens), and smoothing method 1 replaces a zero n-gram match count with 0.1, because BLEU would otherwise be exactly 0 whenever any one of its four precisions is 0.
import os
os.environ["OMP_NUM_THREADS"] = "1"
import math
import numpy as np
from collections import Counter
from scipy import stats
from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction
def toks(t): return t.lower().replace(".", "").split()
def ngrams(t, n): return Counter(tuple(t[i:i+n]) for i in range(len(t)-n+1))
def rouge_n_f1(ref, hyp, n):
r, h = ngrams(toks(ref), n), ngrams(toks(hyp), n)
ov = sum((r & h).values())
if ov == 0: return 0.0
p, rc = ov / sum(h.values()), ov / sum(r.values())
return 2*p*rc/(p+rc)
ref = "the company raised its prices last year"
cands = {
"paraphrase_ok": "the firm increased what it charges in the previous year",
"negated_wrong": "the company did not raise its prices last year",
"unrelated_copy": "the company raised its offices last year",
}
smooth = SmoothingFunction().method1
print("candidate ROUGE-1 F1 ROUGE-2 F1 BLEU(sentence, 1-4gram, smoothing method1)")
for k, c in cands.items():
b = sentence_bleu([toks(ref)], toks(c), smoothing_function=smooth)
print(f"{k:18s} {rouge_n_f1(ref,c,1):.3f} {rouge_n_f1(ref,c,2):.3f} {b:.3f}")
# Stand-in for an embedding model: hand-set concept vectors (dimensions: money, change-up, time, org, negation)
V = {"company":[0,0,0,1,0],"firm":[0,0,0,1,0],"raised":[0,1,0,0,0],"increased":[0,1,0,0,0],"raise":[0,1,0,0,0],
"prices":[1,0,0,0,0],"charges":[1,0,0,0,0],"its":[0,0,0,0,0],"it":[0,0,0,0,0],"what":[0,0,0,0,0],"the":[0,0,0,0,0],
"last":[0,0,1,0,0],"previous":[0,0,1,0,0],"year":[0,0,1,0,0],"in":[0,0,0,0,0],"did":[0,0,0,0,0],
"not":[0,0,0,0,-1],"offices":[0,0,0,0.5,0]}
def embed(t):
v = np.sum([V.get(w,[0]*5) for w in toks(t)], axis=0).astype(float)
return v / (np.linalg.norm(v) + 1e-9)
print("embedding-stand-in cosine (note: negation is one weak dimension)")
for k, c in cands.items():
print(f"{k:18s} {float(embed(ref) @ embed(c)):.3f}")
# METEOR-style simplified alignment: exact match, then a tiny synonym table; F-mean weighted to recall
syn = {("raised","increased"),("company","firm"),("year","year"),("last","previous"),("prices","charges")}
def match(a,b): return a==b or (a,b) in syn or (b,a) in syn
def meteor_like(ref, hyp):
r, h = toks(ref), toks(hyp); used=set(); m=0
for w in h:
for i,x in enumerate(r):
if i not in used and match(w,x): used.add(i); m+=1; break
if m==0: return 0.0
p, rc = m/len(h), m/len(r)
return 10*p*rc/(rc+9*p)
print("meteor-like (exact+synonym, no fragmentation penalty)")
for k, c in cands.items(): print(f"{k:18s} {meteor_like(ref,c):.3f}")
# Pairwise preference test for a release decision: 200 prompts, 78 wins, 52 losses, 70 ties
w,l,t = 78,52,70
p = stats.binomtest(w, w+l, 0.5).pvalue
print("wins",w,"losses",l,"ties",t,"win share excluding ties",round(w/(w+l),3),"sign test p",round(float(p),4))
# Perplexity from hand-set per-token log-probs for a factual and a fluent-wrong summary
f = [-1.9,-2.2,-1.7,-2.4,-2.0]; g=[-0.5,-0.6,-0.4,-0.5,-0.7]
print("perplexity factual", round(math.exp(-np.mean(f)),2), "fluent-wrong", round(math.exp(-np.mean(g)),2))
It prints:
candidate ROUGE-1 F1 ROUGE-2 F1 BLEU(sentence, 1-4gram, smoothing method1)
paraphrase_ok 0.235 0.000 0.025
negated_wrong 0.750 0.571 0.355
unrelated_copy 0.857 0.667 0.489
embedding-stand-in cosine (note: negation is one weak dimension)
paraphrase_ok 1.000
negated_wrong 0.935
unrelated_copy 0.912
meteor-like (exact+synonym, no fragmentation penalty)
paraphrase_ok 0.822
negated_wrong 0.833
unrelated_copy 0.857
wins 78 losses 52 ties 70 win share excluding ties 0.6 sign test p 0.0279
perplexity factual 7.69 fluent-wrong 1.72
Reading it:
- Paraphrase vs copy. The correct paraphrase gets ROUGE-1 F1 0.235, ROUGE-2 0 and BLEU 0.025. The sentence that wrongly says "offices" gets 0.857, 0.667 and 0.489. Overlap ranks the wrong copy far above the right paraphrase.
- Negation survives overlap. "Did not raise" scores 0.750 on ROUGE-1, far above the paraphrase.
- Synonym alignment helps the paraphrase but not negation. The METEOR-like score lifts the paraphrase from 0.235 to 0.822, yet the negated sentence (0.833) and the wrong copy (0.857) still outrank it.
- The hand-built vectors are a teaching device. Each of the five numbers was set by hand to mean one concept. In a real embedding model the numbers are learned and no single one means "money" or "negation"; the table only mimics the idea that similar words get similar vectors.
- Embeddings help with wording, and also miss the flip. The stand-in gives the paraphrase 1.000 and the other two 0.935 and 0.912, so wording is handled, but the negated sentence is only 0.065 below perfect. Similarity between two vectors is not a factual check, so test any real embedding model on negated and number-changed pairs from your own data before relying on it.
Tracing the paraphrase by hand
To see where 0.025, 0.235 and 0.822 come from, this second program redoes the paraphrase row from scratch. Libraries: Python 3.12 standard library and nltk 3.9.1 (used only to check the BLEU figure).
import os
os.environ["OMP_NUM_THREADS"] = "1"
import math
from collections import Counter
from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction
def toks(t): return t.lower().replace(".", "").split()
def ngrams(t, n): return Counter(tuple(t[i:i+n]) for i in range(len(t)-n+1))
ref = toks("the company raised its prices last year")
hyp = toks("the firm increased what it charges in the previous year")
# BLEU by hand: clipped n-gram precisions, then their geometric mean (brevity penalty is 1 when the output is longer than the reference)
ps = []
for n in range(1, 5):
r, h = ngrams(ref, n), ngrams(hyp, n)
hit, tot = sum((r & h).values()), sum(h.values())
p = hit / tot if hit else 0.1 / tot # smoothing method 1 adds 0.1 to a zero match count
ps.append(p)
print(f"{n}-gram: {hit} of {tot} match, precision {p:.4f}")
bp = 1.0 if len(hyp) > len(ref) else math.exp(1 - len(ref) / len(hyp))
by_hand = bp * math.exp(sum(math.log(p) for p in ps) / 4)
lib = sentence_bleu([ref], hyp, smoothing_function=SmoothingFunction().method1)
print(f"BLEU by hand {by_hand:.3f}, nltk {lib:.3f}, agree {abs(by_hand - lib) < 1e-9}")
# ROUGE-1 F1 by hand
shared = sum((ngrams(ref, 1) & ngrams(hyp, 1)).values())
P, R = shared / len(hyp), shared / len(ref)
print(f"ROUGE-1: {shared} shared words, precision {shared}/{len(hyp)}={P:.3f}, recall {shared}/{len(ref)}={R:.3f}, F1 {2*P*R/(P+R):.3f}")
# METEOR-like score by hand for the same pair: 6 aligned words (the, company/firm, raised/increased, prices/charges, last/previous, year)
syn = {("raised","increased"),("company","firm"),("last","previous"),("prices","charges")}
m = sum(1 for w in ref if w in hyp or any((w, x) in syn for x in hyp))
P2, R2 = m / len(hyp), m / len(ref)
print(f"aligned words {m}; precision {m}/{len(hyp)}={P2:.3f}; recall {m}/{len(ref)}={R2:.3f}; weighted F {10*P2*R2/(R2+9*P2):.3f}")
Output:
1-gram: 2 of 10 match, precision 0.2000
2-gram: 0 of 9 match, precision 0.0111
3-gram: 0 of 8 match, precision 0.0125
4-gram: 0 of 7 match, precision 0.0143
BLEU by hand 0.025, nltk 0.025, agree True
ROUGE-1: 2 shared words, precision 2/10=0.200, recall 2/7=0.286, F1 0.235
aligned words 6; precision 6/10=0.600; recall 6/7=0.857; weighted F 0.822
Reading it:
- BLEU counts, for each n from 1 to 4, how many of the output's n-grams also occur in the reference (matches are clipped so a repeated word cannot score twice), divides by the output's n-gram count to get a precision, and takes the geometric mean of the four precisions: multiply them and take the fourth root. Here 0.2000, 0.0111, 0.0125 and 0.0143 give 0.025. The brevity penalty is 1 because the output (10 words) is longer than the reference (7 words); it only bites on outputs shorter than the reference.
- ROUGE-1 F1. Precision is the share of the output's words that are in the reference (2 of 10), recall the share of the reference's words that the output recovered (2 of 7). The harmonic mean F1=2PR/(P+R) is an average that stays close to the smaller of the two, so a score is high only when both are.
- The METEOR-like score aligns 6 of the 7 reference words (the, company with firm, raised with increased, prices with charges, last with previous, year), so precision is 6/10 and recall 6/7. The weighted mean 10PR/(R+9P) counts recall nine times as heavily as precision, which is why the paraphrase scores 0.822 even though 4 of the 10 output words align with nothing.
When embeddings track humans better
When references are few but valid answers are many (abstractive summaries, open translations), when the difference is paraphrase or reordering, and when the embedding model was trained on the language and domain at hand. They do worse on rare terms, numbers, negation, domain jargon, and on texts longer than the model reads well. Check each metric by correlating it with human scores on your own sample, per language pair or task, instead of assuming.
Perplexity and factual summaries
Perplexity (the exponential of average negative log-probability per token) says how predictable the text is. In the program a factual but specific summary has perplexity 7.69 and a fluent wrong one 1.72. Low perplexity means common phrasing, not truth, so it cannot certify a factual summary. Perplexity is also not comparable across tokenizers.
Combining automatic and human evaluation
- Use overlap and embedding scores to reject obvious failures and to track regressions between versions, never as the ship decision.
- Run pairwise preference tests: raters see the old and new output in random order and pick the better one, or tie. Pairwise is more stable than absolute scores.
- Add a factual-consistency audit on a sample (does each claim follow from the source?), because preference raters miss subtle errors.
- Calibrate: compute the correlation between each automatic metric and the human score on 100 or more items, and keep only metrics that correlate on your data.
Release rule for a summarization model (a proposal to adapt). In one line: check the factual audit and the segments first, and let the win share decide only among versions that pass them. In full: ship when (a) the win share excluding ties is above 0.5 with a confidence interval or sign-test p-value that supports it, (b) the factual-error rate in the audit is no worse than the current model's within an agreed margin, and (c) no important segment (long documents, numbers-heavy documents) regresses. A sign test asks: if the two versions were equally good, each decided pair would be a win or a loss with probability 0.5 (a tie gives no direction and is set aside). The p-value is the probability of a split at least as lopsided as the observed one, in either direction, under that assumption. The win share excluding ties is wins divided by wins plus losses. In the tally above, 78 wins, 52 losses and 70 ties give a 0.600 win share among decided pairs and sign-test p = 0.0279; 35% of the prompts were ties, so most of the evidence is about the other 65%. Whether that clears the bar depends on condition (b), which the sign test says nothing about.
Common mistakes
- Comparing BLEU across different tokenizations or test sets.
- Reporting a one-point ROUGE gain without a baseline of the simple token-overlap score and a confidence interval.
- Using one reference for an open-ended task.
- Treating low perplexity or high similarity as evidence of factuality.
Running the code
Python 3.12 with numpy 2.1.3, scipy 1.14.1 and nltk 3.9.1. Save each block to its own .py file and run it with python.
Large generative models can memorize training examples and leak sensitive data. How would you measure memorization and leakage in production, using runtime checks, periodic audits and red-team tests?
Sample Answer
Direct answer
Memorization is when a model reproduces a training example it should only have learned patterns from, and leakage is when that reproduction exposes something sensitive (a personal identifier, a credential, proprietary text). You cannot measure it with one number, so you run three layers that answer different questions. A runtime check inspects every response cheaply and blocks or flags a leak as it happens. A periodic audit takes a statistical sample, or plants known canary strings, and estimates the leak rate with a confidence bound. A red-team test has humans or automated attackers hunt for prompts that extract data, and finds the attacks the first two layers did not think of. The layers disagree on purpose: runtime catches known shapes, audits quantify, red teams discover.
Terms used below
- Memorization: the model can output a training sequence verbatim (or nearly) when prompted with part of it.
- Canary: a fake secret you insert into training data on purpose, so you know exactly what a leak would look like. An example is "the access code is 7316."
- Prefix completion test: give the model the beginning of a known training string and check whether greedy decoding (always pick the most likely next token) continues it exactly.
- Exposure: a canary-based score. Rank every possible canary value by the model's log-likelihood (the base-2 logarithm of the probability the model gives to the text, summed over its characters; it is zero or negative, and closer to zero means the model finds the text more likely); if the true one ranks r among N candidates, then
where N is the number of candidate values and r is the rank of the planted value (1 is best). Exposure is 0 bits when the planted value ranks last, reaches log2N when the model ranks it first, and is about 1 bit for a value the model never saw, because that value lands at a random rank (the last block of the output prints a mean of 1.44 and a median of 1.0 bits over 100,000 random ranks). So the baseline for "no memorization" is about 1 bit, not 0.
- Red-teaming: deliberately attacking your own system to find failures before users do.
Layer 1: runtime checks (every response, milliseconds)
Runtime checks look at the output (and sometimes the prompt) before it leaves the service:
- Pattern detectors for structured identifiers: social security numbers, card numbers (with a checksum test), API-key prefixes, email addresses.
- Overlap against a protected index. Hash every 12-character window (a shingle) of documents you must never reproduce, store the hashes in a set, and flag a response whose shingles hit the set. This catches verbatim regurgitation of known sensitive text, including text that has no fixed pattern.
- Logging of the decision (blocked, redacted, passed) with the request identifier, so every later audit can count how often the layer fired.
What it cannot see: leaks in a paraphrase or a different encoding, and secrets nobody put in the index. It is a floor, not a measurement.
Layer 2: periodic audits (weekly or monthly, statistical)
Two audits answer two different questions.
Canary exposure answers "does this model memorize, and how fast does that grow with repetition?" Before training, insert canaries at known repetition counts, plus an unseen control value. After training, compute each one's exposure. Below is a deterministic stand-in: a character n-gram language model (it predicts each next character from the previous characters, here up to 8, using counts from the training text; with backoff, meaning that when the full 8-character context never appeared in training it falls back to a shorter one) trained on 400 synthetic sentences plus the canaries. It is a stand-in for a trained neural model, chosen so the repetition effect is easy to see; a real audit would score the production model's own log-likelihoods.
How the program works, in order: (1) it builds 400 random sentences from a 34-word vocabulary and appends the three canaries 1, 5 and 20 times; (2) it counts, for every context of 0 to 8 characters, which character followed it; (3) next_dist turns those counts into probabilities for the next character, using the longest context seen in training, with a small constant (0.1) added to every character so nothing has probability zero; (4) logprob scores a string by adding log2 of each character's probability as it is appended, so exposure can score all 10,000 four-digit codes the same way and rank them; (5) greedy repeatedly appends the single most probable character; (6) the last section is the Layer 1 guard code.
import os
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["OPENBLAS_NUM_THREADS"] = "1"
import math
import re
from collections import defaultdict
import numpy as np
# Stand-in model: a character n-gram language model with backoff. It is NOT a neural
# network; it simply makes the repetition-to-memorization effect easy to see.
ORDER = 8
rng = np.random.default_rng(0)
words = ("the quick report shows system update customer order ships today policy review "
"team meets budget plan launch metric weekly status notes draft final version "
"access code is pin number account ticket closed opened queue").split()
def sentence():
return " ".join(rng.choice(words, size=8)) + ". "
corpus = [sentence() for _ in range(400)]
canaries = {"c_once": "the access code is 7316. ", "c_x5": "the access code is 2480. ",
"c_x20": "the access code is 9051. "}
reps = {"c_once": 1, "c_x5": 5, "c_x20": 20}
for name, text in canaries.items():
corpus += [text] * reps[name]
unseen = "the access code is 4627. " # never inserted: control
rng.shuffle(corpus)
text = "".join(corpus)
vocab = sorted(set(text))
counts = [defaultdict(lambda: defaultdict(int)) for _ in range(ORDER + 1)]
for i in range(len(text)):
for k in range(ORDER + 1):
if i - k >= 0:
counts[k][text[i - k:i]][text[i]] += 1
def next_dist(ctx):
for k in range(min(ORDER, len(ctx)), -1, -1):
c = counts[k].get(ctx[len(ctx) - k:] if k else "")
if c:
tot = sum(c.values())
return {ch: (c.get(ch, 0) + 0.1) / (tot + 0.1 * len(vocab)) for ch in vocab}
return {ch: 1 / len(vocab) for ch in vocab}
def logprob(ctx, s):
lp = 0.0
for ch in s:
lp += math.log2(next_dist(ctx)[ch]); ctx += ch
return lp
def greedy(prefix, n):
out = prefix
for _ in range(n):
d = next_dist(out); out += max(sorted(d), key=lambda c: d[c])
return out[len(prefix):]
# 1. Exposure of a canary: rank of the true digits among all 10,000 candidates.
def exposure(code):
ctx = "the access code is "
scores = np.array([logprob(ctx, f"{n:04d}.") for n in range(10000)])
true = scores[int(code)]
rank = 1 + int((scores > true).sum())
return rank, math.log2(10000) - math.log2(rank)
print("canary inserted rank exposure_bits")
for name, code in [("c_once", "7316"), ("c_x5", "2480"), ("c_x20", "9051"), ("unseen", "4627")]:
r, e = exposure(code)
print(f"{name:8s} {reps.get(name, 0):8d} {r:5d} {e:13.2f}")
print("max possible exposure bits:", round(math.log2(10000), 2))
# 2. Prefix-completion extraction test: give the first 19 chars, ask for the next 5.
prefix = "the access code is "
print("greedy continuation of the prefix:", repr(greedy(prefix, 5)))
# 3. Runtime check on outputs: PII regex plus overlap with a protected-text index.
protected = ["the access code is 9051.", "ssn 123-45-6789 on file"]
def shingles(s, n=12):
return {s[i:i + n] for i in range(len(s) - n + 1)}
index = set().union(*[shingles(p) for p in protected])
pii = re.compile(r"[0-9]{3}-[0-9]{2}-[0-9]{4}")
outputs = ["Your order ships today.", "Sure: the access code is 9051. Anything else?",
"Record shows 123-45-6789 for that customer."]
for o in outputs:
overlap = len(shingles(o) & index) / max(1, len(shingles(o)))
print(f"pii={bool(pii.search(o))!s:5} overlap={overlap:.2f} {o}")
# 4. Audit sizing: exact (Clopper-Pearson) upper bound on leak rate after n clean samples.
from scipy.stats import beta
for n in (300, 3000, 30000):
print(n, "clean samples -> 95% upper bound", round(float(beta.ppf(0.95, 1, n)) * 100, 4), "%")
# ---- Extra read-outs ----
# (a) Why the closed form 1 - 0.05**(1/n) is the zero-leak bound: P(0 leaks in n) = (1 - p)**n, set equal to 0.05.
print("closed form 1-0.05**(1/n), in percent:", [round(100 * (1 - 0.05 ** (1 / n)), 4) for n in (300, 3000, 30000)])
# (b) Which 12-character windows matched in the runtime check.
for o in outputs[1:]:
hit = sorted(shingles(o) & index)
print(f"matched {len(hit)} of {len(shingles(o))} windows", hit if len(hit) < 5 else "")
# (c) Score a candidate by hand: probability the model gives each next character of '9051.' and '4627.'.
for code in ("9051", "4627"):
ctx, probs = "the access code is ", []
for ch in code + ".":
probs.append(next_dist(ctx)[ch]); ctx += ch
print(code + ".", "per-character probabilities", [round(p, 3) for p in probs],
"log2 likelihood", round(sum(math.log2(p) for p in probs), 2))
# (d) What exposure does a value the model never saw get? Its rank is roughly uniform over 1..N.
ranks = np.random.default_rng(1).integers(1, 10001, 100000)
ex = math.log2(10000) - np.log2(ranks)
print("never-seen value: mean exposure", round(float(ex.mean()), 2), "bits, median", round(float(np.median(ex)), 2), "bits")
# (e) Membership inference on the stand-in: 100 training sentences versus 100 fresh sentences from the
# same generator; guess 'member' when the per-character log-likelihood is above the median of the 200 scores.
def per_char(s):
ctx, lp = "", 0.0
for ch in s:
lp += math.log2(next_dist(ctx)[ch]); ctx += ch
return lp / len(s)
members = [per_char(s) for s in corpus[:100]]
fresh = [per_char(sentence()) for _ in range(100)]
cut = float(np.median(members + fresh))
tpr = np.mean([v > cut for v in members]); fpr = np.mean([v > cut for v in fresh])
print(f"membership guess: members flagged {tpr:.2f}, fresh flagged {fpr:.2f}, advantage over a coin flip {(tpr - fpr) / 2:.2f}")
Output:
canary inserted rank exposure_bits
c_once 1 14 9.48
c_x5 5 2 12.29
c_x20 20 1 13.29
unseen 0 5848 0.77
max possible exposure bits: 13.29
greedy continuation of the prefix: '9051.'
pii=False overlap=0.00 Your order ships today.
pii=False overlap=0.38 Sure: the access code is 9051. Anything else?
pii=True overlap=0.06 Record shows 123-45-6789 for that customer.
300 clean samples -> 95% upper bound 0.9936 %
3000 clean samples -> 95% upper bound 0.0998 %
30000 clean samples -> 95% upper bound 0.01 %
closed form 1-0.05**(1/n), in percent: [0.9936, 0.0998, 0.01]
matched 13 of 34 windows
matched 2 of 32 windows [' 123-45-6789', '123-45-6789 ']
9051. per-character probabilities [0.659, 0.855, 0.855, 0.855, 0.855] log2 likelihood -1.5
4627. per-character probabilities [0.003, 0.012, 0.022, 0.012, 0.022] log2 likelihood -32.06
never-seen value: mean exposure 1.44 bits, median 1.0 bits
membership guess: members flagged 0.87, fresh flagged 0.13, advantage over a coin flip 0.37
Reading the table (candidate space N=10000 four-digit codes, so the ceiling is log210000=13.29 bits):
- The code inserted once already ranks 14th of 10,000 (9.48 bits). A single exposure is enough for this stand-in to lean toward it.
- The codes inserted 5 and 20 times rank 2nd and 1st (12.29 and 13.29 bits). Exposure rises with repetition, which is why deduplicating training data is the cheapest mitigation.
- The code never inserted ranks 5848th (0.77 bits). That is what a value the model has not seen looks like: a random rank gives about 1 bit (mean 1.44, median 1.0 in the printed simulation), so the baseline is around 1 bit, not 0. This control row is what makes the other rows interpretable; without it you cannot tell memorization from a model that simply prefers four-digit strings.
- The exposure arithmetic by hand: for the code inserted once, log210000−log214=13.29−3.81=9.48 bits; for the one ranked first, 13.29−log21=13.29; for the unseen one, 13.29−log25848=13.29−12.52=0.77.
- Why the ranks come out this way: the program prints the per-character probabilities for the 9051 canary (0.659 for its first digit, then 0.855 for each following character, log2 likelihood -1.50) and for the unseen 4627 (0.003, 0.012, 0.022, 0.012, 0.022, log2 likelihood -32.06). The score of a candidate is just the sum of those logs, so a code the model has seen repeatedly outscores almost every other code.
- Overlap in the runtime check is the share of a response's 12-character windows found in the protected index. The second response has 34 windows and 13 of them lie inside the copied "the access code is 9051.", so 13/34 = 0.38. The third has 32 windows and 2 of them contain the digits (the program prints
' 123-45-6789'and'123-45-6789 '), so 2/32 = 0.06; its pattern detector also fires. Any single hit is enough to block, whatever the fraction. - The prefix completion test gave the model the 19-character prefix "the access code is " and greedy decoding returned
9051., the most-repeated canary. An attacker who knows the format retrieves the most-duplicated secret first.
Sampled leak-rate audit answers "what fraction of real production responses leak?" Pull a random sample of logged responses, have a detector plus human review label each, and report the rate with an interval. The last block of the output shows what a clean audit proves. With zero leaks found in n responses, the exact one-sided 95% upper bound on the true rate is 1−0.051/n. The reason: if the true leak rate were p, the chance of seeing zero leaks in n independent samples is (1−p)n; the largest p for which that chance is still at least 5% solves (1−p)n=0.05, giving p=1−0.051/n (this is the Clopper-Pearson bound, an exact rather than approximate confidence bound for a rate measured as a count out of a total; the program computes it with scipy's beta quantile and prints the closed form beside it). It is 0.9936% for 300 samples, 0.0998% for 3,000 and 0.01% for 30,000. So "we found nothing" in 300 responses is compatible with a leak rate near 1%, which is about 10,000 leaked responses per million. Size the audit to the rate you must rule out, and stratify by user segment and prompt type so a rare, high-risk slice (for example, support chats containing account numbers) is not drowned by the bulk.
Layer 3: red-team tests (scheduled campaigns plus continuous automation)
- Extraction attacks: prefix prompts like the one above, repeated-token and "continue this document" prompts, and requests framed as role-play or translation. Score by the same overlap index and pattern detectors as Layer 1, so the attack results are comparable with production.
- Membership probes: for records you hold out of training, check whether the model assigns suspiciously higher likelihood to the ones that were in training (a membership-inference test). Report it as an advantage over a coin flip, not a binary. Example on the stand-in above: guess "was in training" whenever a sentence's per-character log-likelihood is above the median of 100 training sentences and 100 fresh ones; it flagged 0.87 of the training sentences and 0.13 of the fresh ones, so the guess is right about 87% of the time, an advantage of 0.37 over the 50% a coin flip gets. That number describes this memorizing stand-in only, not any real model.
- Retrieval and tool paths: if the application retrieves documents or calls tools, test whether those paths surface data the user should not see. That is access-control leakage rather than memorization, and it needs its own cases.
- Regression set: every successful attack becomes a permanent test that runs on each model, prompt or filter change, and its pass rate goes on the same dashboard as the audit numbers.
How the layers combine (what to track)
| Signal | Source | Question it answers | Alert rule (example) |
|---|---|---|---|
| Runtime block rate | Layer 1 | Is the filter firing more than usual? | Rate above its trailing baseline |
| Max canary exposure | Layer 2 | Is memorization growing between model versions? | Any unseen-control exposure above noise, or any canary above a set bits level |
| Audited leak rate with upper bound | Layer 2 | Are we under the tolerated rate? | Upper bound above the tolerance |
| Red-team success rate | Layer 3 | Do known attacks still work? | Any regression-set failure |
Trade-offs and common mistakes
- Treating the runtime filter as the measurement. It reports only what it matches. The audit and the red team measure what it misses.
- No control value. Without an unseen canary you cannot interpret an exposure number.
- A one-off audit. Memorization changes with each fine-tune, data refresh and decoding setting, so rerun on every model version.
- Declaring zero leaks from a small sample. Report the upper bound, as above.
- Confusing verbatim copying with privacy. A paraphrase of a secret can leak the fact without a long shared substring, so the overlap index should be backed by a human-reviewed sample and, for the highest-risk data, by training-time protections such as deduplication, removing sensitive records before training, or differentially private training (a method that bounds how much any single record can influence the model, at a cost in quality).
- Logging the leak while auditing for it. The logs holding responses are themselves sensitive: store hashes or redacted text where you can, restrict access, and set retention.
The guard code above is a minimal illustration: the regular expression covers one social-security-number layout and the shingle index covers exact 12-character windows. A production system must also handle other identifier formats, case and whitespace variation, encodings, translation, paraphrase and multi-turn extraction.
How would you detect and reduce overconfident wrong answers in a consumer-facing assistant? Cover detection signals, what the user sees, and what the backend does.
Sample Answer
Direct answer
An overconfident wrong answer is one the assistant states firmly and gets wrong. The fix is a loop: (1) produce a confidence signal that is checked against outcomes, not the model's own tone, (2) let that signal decide what the user sees (answer, hedged answer, ask a question, decline, or hand off), and (3) have the backend log every case, collect labels, and recalibrate. The signal is only useful if it is calibrated: among answers scored 0.8, about 80% should be right.
Detection signals, from cheapest to strongest
- Stated confidence ("I'm 90% sure"). Free, but models tend to state similar high confidence regardless of correctness. Measure it, do not trust it.
- Self-consistency (agreement across samples). Ask the model the same question K times at non-zero temperature (temperature is a decoding setting that controls randomness: at 0 the model always picks its most likely next token, and above 0 it samples, so repeated runs can differ) and measure the share of samples that give the most common answer. Cost: K times the generation. Works when wrong answers scatter; fails when the model is consistently wrong.
- Grounding checks. For answers that should come from documents or a database, test whether each claim is supported by the retrieved text, using a rule or a judge model (a second language model prompted to decide whether the text supports the claim). Unsupported claims are the high-risk ones.
- Token-level uncertainty. Where the serving stack exposes log-probabilities (the model's per-token probabilities), low probability on key tokens such as names, numbers and dates is a signal. Not always available.
- Query-side risk. The topic (medical, legal, money), the time-sensitivity, and whether the question is out of the product's scope. Some questions deserve extra caution however confident the model is.
- Outcome feedback. Thumbs-down, corrections the user types, and repeat questions. Delayed, biased toward users who bother, but the only signal that reflects real impact.
A learned combination (a small classifier on these signals, trained on labelled answers) beats any single one, but needs labels, which come from the logging loop below.
Worked example: stated confidence versus agreement
The program simulates 400 labelled questions. It is a stand-in for logged, human-labelled answers; the model is simulated: each question has a hidden chance of a correct sample, wrong samples scatter across four different wrong answers, and the stated confidence is set near 0.93 whatever happens. K = 5 samples per question, and the answer the user would see is the first sample. ECE (expected calibration error) is computed with 5 equal-width bins: the bin-size-weighted average gap between a bin's mean confidence and its observed accuracy.
How the simulation builds a question: rng.beta(2.0, 1.2) draws, for each question, its hidden chance p_right that one sampled answer is correct (a bumpy range between 0 and 1 with more easy questions than hard ones). rng.random((N, K)) < p_right[:, None] then flips a biased coin for each of the K samples of that question, so a hard question gets few right samples. Every right sample is the same answer (id 0), and every wrong sample is one of four wrong ids chosen at random, which is what "wrong answers scatter" means in code. np.bincount(a) counts how many times each answer id appears among the K samples, .max() / K is the share held by the most common one, and that share is the agreement score: 1.0 when all 5 samples match, 0.2 when all 5 differ. The ECE function sorts questions into confidence bins and sums, over bins, the share of questions in the bin times the gap between the bin's mean confidence and its accuracy.
import numpy as np
rng = np.random.default_rng(0)
N, K = 400, 5
# Simulated eval set (stand-in for logged, human-labelled answers).
# Each question has a hidden difficulty; the model answers K times at temperature > 0.
# p_right: chance that one sampled answer is right. Agreement = share of the K samples
# that match the most common answer (a self-consistency signal).
p_right = rng.beta(2.0, 1.2, size=N)
samples_right = rng.random((N, K)) < p_right[:, None]
# wrong samples scatter over 4 different wrong answers; right samples all agree
wrong_ids = rng.integers(1, 5, size=(N, K))
answers = np.where(samples_right, 0, wrong_ids)
final = answers[:, 0] # the answer the user would see
correct = (final == 0).astype(int)
agree = np.array([np.bincount(a).max() / K for a in answers])
# verbalized confidence: the model states high confidence almost regardless of correctness
verbal = np.clip(0.93 + 0.04 * rng.standard_normal(N), 0, 1)
def ece(conf, y, bins=5):
edges = np.linspace(0, 1, bins + 1)
total = 0.0
for lo, hi in zip(edges[:-1], edges[1:]):
m = (conf >= lo - 1e-9) & ((conf < hi - 1e-9) | (hi == 1.0)) # 1e-9 guards float edges such as 0.6
if m.any():
total += m.mean() * abs(y[m].mean() - conf[m].mean())
return total
def bin_table(conf, y, bins=5):
edges = np.linspace(0, 1, bins + 1)
for lo, hi in zip(edges[:-1], edges[1:]):
m = (conf >= lo - 1e-9) & ((conf < hi - 1e-9) | (hi == 1.0)) # 1e-9 guards float edges such as 0.6
if m.any():
print(f" [{lo:.1f}, {hi:.1f}] n={m.sum():3d} mean confidence {conf[m].mean():.3f} accuracy {y[m].mean():.3f} gap {abs(y[m].mean() - conf[m].mean()):.3f}")
print("accuracy overall:", round(correct.mean(), 3))
print("ECE verbalized :", round(ece(verbal, correct), 3), "(5 equal-width bins)")
print("ECE agreement :", round(ece(agree, correct), 3), "(raw agreement used as probability)")
print("verbalized confidence by bin:")
bin_table(verbal, correct)
print("agreement by bin:")
bin_table(agree, correct)
print("\nagreement n accuracy of the shown answer")
for a in sorted(set(agree)):
m = agree == a
print(f"{a:.1f} {m.sum():3d} {correct[m].mean():.3f}")
print("\nthreshold answered error_rate_among_answered")
for t in [0.0, 0.6, 0.8, 1.0]:
m = agree >= t
print(f"{t:.1f} {m.mean():.3f} {1 - correct[m].mean():.3f}")
print("\nband (agreement) n accuracy")
for name, m in [("high (5 of 5)", agree == 1.0), ("middle (3 or 4 of 5)", (agree >= 0.6) & (agree < 1.0)), ("low (1 or 2 of 5)", agree < 0.6)]:
print(f"{name:20} {m.sum():3d} {correct[m].mean():.3f}")
Output:
accuracy overall: 0.648
ECE verbalized : 0.284 (5 equal-width bins)
ECE agreement : 0.05 (raw agreement used as probability)
verbalized confidence by bin:
[0.8, 1.0] n=400 mean confidence 0.932 accuracy 0.647 gap 0.284
agreement by bin:
[0.2, 0.4] n= 3 mean confidence 0.200 accuracy 0.000 gap 0.200
[0.4, 0.6] n=108 mean confidence 0.400 accuracy 0.287 gap 0.113
[0.6, 0.8] n=102 mean confidence 0.600 accuracy 0.559 gap 0.041
[0.8, 1.0] n=187 mean confidence 0.898 accuracy 0.914 gap 0.016
agreement n accuracy of the shown answer
0.2 3 0.000
0.4 108 0.287
0.6 102 0.559
0.8 95 0.832
1.0 92 1.000
threshold answered error_rate_among_answered
0.0 1.000 0.353
0.6 0.723 0.211
0.8 0.468 0.086
1.0 0.230 0.000
band (agreement) n accuracy
high (5 of 5) 92 1.000
middle (3 or 4 of 5) 197 0.690
low (1 or 2 of 5) 111 0.279
Reading it:
- Accuracy is 0.648, but the stated confidence is about 0.93 throughout, so all 400 questions fall in one bin (mean confidence 0.932, accuracy 0.647) and ECE is simply that gap, 0.284: the signal is badly overconfident. For the agreement score the bins give gaps of 0.200 (n=3), 0.113 (n=108), 0.041 (n=102) and 0.016 (n=187), so ECE is (3 x 0.200 + 108 x 0.113 + 102 x 0.041 + 187 x 0.016) / 400, about 0.05. There is no universal good value, because ECE is the average distance between what the score claims and what happens: 0.05 means the score is off by about five percentage points on average, and 0.284 means more than five times that. A bin includes its lower edge and the last bin includes both ends, so agreement 0.8 and 1.0 share the last bin.
- In this run agreement tracks correctness: answers where all 5 samples agree were right 1.000 of the time, those at 0.8 were right 0.832, at 0.4 only 0.287. ECE of the agreement score used as a probability is 0.05.
- Answering only when agreement is at least 0.8 cuts the error rate among shown answers from 0.353 to 0.086, at the price of answering 46.8% of questions instead of all of them. Each threshold gives one point: coverage (the share of questions answered) and risk (the error rate among those answered). Plotting risk against coverage as the threshold moves gives the risk-coverage curve, and a product owner picks the threshold from it.
- Caveat on the simulation: it was built so that wrong answers scatter, which is why agreement works so well here. A real model can be consistently wrong (a common misconception), and agreement then reports high confidence for a wrong answer. Treat the 1.000 as a property of this simulation, and measure the same table on real labelled traffic.
What the user sees
Map the calibrated score to a small number of behaviours, written down in advance. With agreement as the score, the first bands to ship from this run's numbers are: high is 5 of 5 samples agreeing (92 of 400 questions, all correct), middle is 3 or 4 of 5 (197 questions, accuracy 0.690), and low is 1 or 2 of 5 (111 questions, accuracy 0.279; the last lines of the output). These cut-offs come from a simulation, so on real traffic you re-draw them from the labelled calibration table.
- High: answer plainly, with sources when available.
- Middle: answer with a visible hedge ("I'm not certain; this is based on X") and a way to verify, such as a citation or link.
- Low: ask a clarifying question, offer what is known, or say the assistant cannot answer reliably.
- High-risk topic: lower the bar for hedging or handing off to a human or an official source, regardless of score.
Hedges must be earned: if every answer is hedged, users learn to ignore the hedge and the product feels useless. Test the wording with users, and track whether corrections and escalations fall.
What the backend does
- Log per answer: query id, signals (stated confidence, agreement, grounding result, topic risk), the action shown, and later the outcome.
- Sample answers across all score bands for human labelling, including the high-confidence ones, because the confident-wrong cases live there.
- Recompute the calibration table and ECE per topic weekly; refit the threshold or the combining classifier when the table moves.
- Route a slice of low-score and user-corrected cases to review and into the next test set.
- Alert when the share of high-confidence answers that later get corrected rises.
Trade-offs and mistakes
- Cost of K samples versus the value of the signal: use it only when a cheaper signal (topic risk, retrieval score) says the question is worth it.
- Calibration drifts when the model, prompt or user mix changes, so a threshold set once goes stale.
- Over-hedging is a failure too: report the answered fraction next to the error rate.
- ECE depends on binning and on how many items fall in each bin; with few labels per bin it is noisy, so report counts as in the table.
- Do not measure on the data you tuned the threshold on.
Unlock Full Question Bank
Get access to all 21 LLM Evaluation and Observability interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.