All guides

Why LLM JSON confidence lies, and how to score multi-token labels with a prefix trie in Python

Adding confidence_score: float to a JSON schema produces clustered 0.85 to 0.95 guesses that wave wrong answers past your routing threshold. Switching to token-1 logprobs then breaks on leading-space BPE splits and multi-token labels that share a prefix.

  • Merge leading-space and case BPE variants (' refund' at 49.6% and 'refund' at 30.4%) with logsumexp to recover the full 80.0% label mass.
  • Keep real multi-token label names and score only branching prefix-trie nodes, cutting decode steps by 79.2% on 8 labels and 95.3% on 48 labels.
  • Fit one scalar temperature T = 1.524 on 300 validation tickets to keep 65.5% accuracy while cutting ECE from 0.212 to 0.029.
Python 3.12+ stdlib, 0 API keysRelated prerequisites:Shadow classifierPrefill vs decodeClassifier calibration
Eight-label prefix trie contrasting five branching decision nodes against six skipped single-child stepsPrefix trie: 5 decision nodesDecision nodeSkipped stepRootcardrefundwireaccount_payment_stolen_partial_full_transfer_close_declined_pending_freeze_item_order_failed_limit_request

Why JSON confidence and token-1 fail

Cook and Song (arXiv:2611.25289) show logit-based trie scoring lifts error-ranking AUROC far above verbalized JSON percentages, while A..H aliases lose 5.6 accuracy points. In our 1,000-ticket simulation, only temperature-scaled trie logprobs combine full accuracy with calibrated confidence.

MethodStepsAccAUROCECEPrimary failure or guarantee
Naive token-1 exp(logprob)135.7%0.6490.157Splits BPE space variants and collapses shared prefixes to one sibling.
Single-token IDs (A..H)160.0%0.7380.151Drops 5.5 accuracy points from stripped label words and option-ID bias.
Verbalized JSON confidence1765.5%0.5980.212Clusters guesses around 0.85 to 0.95 and misranks wrong predictions.
Decision-trie logprobs (raw)565.5%0.8000.113Ranks errors accurately, but RLHF logit sharpening inflates confidence.
Decision-trie + Temp scale565.5%0.8020.029Preserves exact argmax labels and calibrates routing probabilities.

Four steps to calibrated logprobs

Keep your real multi-token class names and score only branching nodes in a prefix trie. All four steps below run in standard-library Python without changing model weights.

1. Merge BPE splits with logsumexp

Tokenizers split ' refund' (49.6%) and 'refund' (30.4%) into separate token IDs. Group surface variants with lstrip and lower, then combine their logprobs via logsumexp to recover the full 80.0% mass.

2. Score only branching trie nodes

Build a prefix trie over real multi-token labels instead of A..H aliases. Query logprobs only where len(children) > 1, cutting 24 label tokens to 5 decision steps (and 192 to 9 across 48 banking intents).

3. Normalize over the closed set

Sum the merged logprobs along each label's branching edges to get s^D_TL(y), then apply softmax across your candidate set. Error-ranking AUROC jumps from 0.598 (17-token JSON) to 0.800.

4. Fit scalar temperature T

Minimize multiclass negative log-likelihood on 300 held-out validation tickets via golden-section search (T = 1.524). Dividing scores by T never alters argmax accuracy (65.5%) and drops ECE to 0.029.

Auto-routing gate (confidence >= 0.80)CoverageMean statedActual accError rate
Verbalized JSON confidence89.3%88.3%67.2%32.8%
Decision-trie logprobs (raw)53.7%93.9%84.7%15.3%
Decision-trie + Temp scale33.5%90.6%92.2%7.8%

Five-method benchmark on 1,000 tickets

Compare decode steps, top-1 accuracy, correctness AUROC, 10-bin ECE, and top-label Brier score on the held-out split.

Five-method evaluation grid comparing steps, accuracy, AUROC, ECE, and Brier score across 1,000 ticketsScoring methodStepsAccuracyAUROCECEBrierToken-1 logprob135.7%0.6490.1570.241Single-token A..H160.0%0.7380.1510.227Verbalized JSON1765.5%0.5980.2120.264Raw decision trie565.5%0.8000.1130.186Temp-scaled trie565.5%0.8020.0290.170

Run the prefix-trie calibrator

Save as logprobs_trie.py and run on Python 3.12 or newer. The script uses synthetic post-RLHF logits with fixed seeds, so your terminal prints the exact figures above.

logprobs_trie.pyPython 3.12+
"""Deterministic prefix-trie logprob scorer and temperature calibrator for LLM classification.

Standard library only (dataclasses, math, random, sys).
No API key, no GPU, no network. Uses synthetic billing intents only.
"""

from __future__ import annotations

from dataclasses import dataclass, field
import math
import random
import sys

LABELS: tuple[tuple[str, tuple[str, ...]], ...] = (
    ("card_payment_declined", ("card", "_payment", "_declined")),
    ("card_payment_pending", ("card", "_payment", "_pending")),
    ("card_stolen_freeze", ("card", "_stolen", "_freeze")),
    ("refund_partial_item", ("refund", "_partial", "_item")),
    ("refund_full_order", ("refund", "_full", "_order")),
    ("wire_transfer_failed", ("wire", "_transfer", "_failed")),
    ("wire_transfer_limit", ("wire", "_transfer", "_limit")),
    ("account_close_request", ("account", "_close", "_request")),
)


@dataclass
class TrieNode:
    prefix: tuple[str, ...]
    children: dict[str, TrieNode] = field(default_factory=dict)
    label: str | None = None


def build_trie(labels: tuple[tuple[str, tuple[str, ...]], ...]) -> TrieNode:
    root = TrieNode(prefix=())
    for name, tokens in labels:
        node = root
        built: list[str] = []
        for tok in tokens:
            built.append(tok)
            if tok not in node.children:
                node.children[tok] = TrieNode(prefix=tuple(built))
            node = node.children[tok]
        node.label = name
    return root


def count_trie_steps(root: TrieNode) -> tuple[int, int]:
    """Return (all_internal_nodes, decision_nodes_with_2plus_children)."""
    internal = 0
    decision = 0
    stack = [root]
    while stack:
        node = stack.pop()
        if node.children:
            internal += 1
            if len(node.children) > 1:
                decision += 1
            stack.extend(node.children.values())
    return internal, decision


def logsumexp(values: list[float]) -> float:
    peak = max(values)
    return peak + math.log(sum(math.exp(v - peak) for v in values))


def softmax_scores(scores: dict[str, float], temperature: float = 1.0) -> dict[str, float]:
    scaled = {k: v / temperature for k, v in scores.items()}
    norm = logsumexp(list(scaled.values()))
    return {k: math.exp(v - norm) for k, v in scaled.items()}


def merge_bpe_surface_logprobs(raw_top_logprobs: dict[str, float]) -> dict[str, float]:
    """Collapse leading-space and case variants (' refund', 'refund', 'Refund') in log space."""
    buckets: dict[str, list[float]] = {}
    for token_str, logp in raw_top_logprobs.items():
        canonical = token_str.lstrip(" ").lower()
        buckets.setdefault(canonical, []).append(logp)
    return {canon: logsumexp(vals) for canon, vals in buckets.items()}


def score_decision_only(
    root: TrieNode,
    labels: tuple[tuple[str, tuple[str, ...]], ...],
    step_logprobs: dict[tuple[str, ...], dict[str, float]],
) -> dict[str, float]:
    """Decision-only total log-likelihood s^D_TL(y) from Cook and Song (arXiv:2611.25289, Eq. 3)."""
    out: dict[str, float] = {}
    for name, tokens in labels:
        node = root
        decision_ll: list[float] = []
        for tok in tokens:
            if len(node.children) > 1:
                merged = merge_bpe_surface_logprobs(step_logprobs[node.prefix])
                decision_ll.append(merged[tok])
            node = node.children[tok]
        out[name] = sum(decision_ll)
    return out


def auroc_correctness(confidences: list[float], correct: list[int]) -> float:
    """Exact Mann-Whitney U AUROC with mid-ranks for ties."""
    paired = sorted(zip(confidences, correct), key=lambda item: item[0])
    n = len(paired)
    n_pos = sum(correct)
    n_neg = n - n_pos
    ranks = [0.0] * n
    i = 0
    while i < n:
        j = i
        while j + 1 < n and paired[j + 1][0] == paired[i][0]:
            j += 1
        avg_rank = 0.5 * (i + j) + 1.0
        for k in range(i, j + 1):
            ranks[k] = avg_rank
        i = j + 1
    pos_rank_sum = sum(r for r, (_, y) in zip(ranks, paired) if y == 1)
    return (pos_rank_sum - n_pos * (n_pos + 1) / 2.0) / (n_pos * n_neg)


def expected_calibration_error(
    confidences: list[float], correct: list[int], n_bins: int = 10
) -> float:
    total = len(confidences)
    ece = 0.0
    for b in range(n_bins):
        lo = b / n_bins
        hi = (b + 1) / n_bins
        idx = [
            i
            for i, c in enumerate(confidences)
            if (lo <= c <= hi if b == n_bins - 1 else lo <= c < hi)
        ]
        if not idx:
            continue
        avg_conf = sum(confidences[i] for i in idx) / len(idx)
        avg_acc = sum(correct[i] for i in idx) / len(idx)
        ece += (len(idx) / total) * abs(avg_acc - avg_conf)
    return ece


def top_label_brier(confidences: list[float], correct: list[int]) -> float:
    return sum((c - y) ** 2 for c, y in zip(confidences, correct)) / len(confidences)


def fit_temperature(
    val_scores: list[dict[str, float]], val_gold: list[str]
) -> float:
    """Golden-section search minimizing multiclass NLL on held-out validation scores."""
    def nll(temp: float) -> float:
        total = 0.0
        for scores, gold in zip(val_scores, val_gold):
            probs = softmax_scores(scores, temperature=temp)
            total -= math.log(max(probs[gold], 1e-12))
        return total / len(val_gold)

    lo, hi = 0.15, 5.0
    phi = (math.sqrt(5.0) - 1.0) / 2.0
    for _ in range(45):
        m1 = hi - phi * (hi - lo)
        m2 = lo + phi * (hi - lo)
        if nll(m1) < nll(m2):
            hi = m2
        else:
            lo = m1
    return 0.5 * (lo + hi)


def simulate_dataset(n_items: int, seed: int) -> list[dict[str, object]]:
    """Simulate a post-RLHF overconfident LLM classifier across 8 shared-prefix billing intents."""
    rng = random.Random(seed)
    root = build_trie(LABELS)
    label_names = [name for name, _ in LABELS]
    records: list[dict[str, object]] = []

    for _ in range(n_items):
        gold_idx = rng.randrange(len(LABELS))
        gold_name, gold_tokens = LABELS[gold_idx]
        # Latent semantic affinity per label: gold gets +1.85, sibling sharing token-0 gets +0.45
        latents: dict[str, float] = {}
        for idx, (name, toks) in enumerate(LABELS):
            if idx == gold_idx:
                mean = 1.85
            elif toks[0] == gold_tokens[0]:
                mean = 0.45
            else:
                mean = 0.0
            latents[name] = mean + rng.gauss(0.0, 0.95)

        # Post-RLHF output head sharpens logits ~2.8x above Bayes-optimal scale
        rlhf_sharpness = 2.85
        unnormalized = {name: math.exp(rlhf_sharpness * latents[name]) for name, _ in LABELS}
        leak_mass = math.exp(rlhf_sharpness * (-1.5))

        # Exact conditional next-token distributions at every decision node of the prefix trie
        step_logprobs: dict[tuple[str, ...], dict[str, float]] = {}
        stack = [root]
        while stack:
            node = stack.pop()
            if len(node.children) > 1:
                depth = len(node.prefix)
                child_masses: dict[str, float] = {}
                for child_tok in node.children:
                    sub_prefix = node.prefix + (child_tok,)
                    child_masses[child_tok] = sum(
                        unnormalized[nm]
                        for nm, tks in LABELS
                        if tks[: depth + 1] == sub_prefix
                    )
                denom = sum(child_masses.values()) + (leak_mass if depth == 0 else 0.0)
                vocab_lp: dict[str, float] = {}
                for child_tok, mass in child_masses.items():
                    lp = math.log(mass / denom)
                    if depth == 0:
                        # Realistic BPE split between 'refund' (38%) and ' refund' (62%)
                        vocab_lp[child_tok] = lp + math.log(0.38)
                        vocab_lp[" " + child_tok] = lp + math.log(0.62)
                    else:
                        vocab_lp[child_tok] = lp
                step_logprobs[node.prefix] = vocab_lp
            stack.extend(node.children.values())

        decision_scores = score_decision_only(root, LABELS, step_logprobs)
        raw_probs = softmax_scores(decision_scores, temperature=1.0)
        pred_trie = max(raw_probs, key=raw_probs.get)

        # Naive first-token cookbook baseline: picks single top token on step 0 without merging or branching
        first_step = step_logprobs[()]
        best_tok0 = max(first_step, key=first_step.get)
        canon0 = best_tok0.lstrip(" ").lower()
        naive_pred = next(name for name, toks in LABELS if toks[0] == canon0)
        naive_conf = math.exp(first_step[best_tok0])

        # Single-token 'A'..'H' alias baseline: 1 decode step, loses accuracy from dropped label words + ID bias
        option_bias = (0.34, 0.15, 0.05, -0.02, -0.06, -0.10, -0.15, -0.21)
        abc_logits = {
            name: rlhf_sharpness * (0.86 * latents[name] + option_bias[idx] + rng.gauss(0.0, 0.38))
            for idx, name in enumerate(label_names)
        }
        abc_probs = softmax_scores(abc_logits, temperature=1.0)
        abc_pred = max(abc_probs, key=abc_probs.get)

        # Verbalized JSON confidence baseline: greedy label plus 5%-rounded self-reported score in [0.60, 0.98]
        margin = latents[pred_trie] - max(v for k, v in latents.items() if k != pred_trie)
        verbal_base = 0.91 if margin > 0.8 else 0.84
        verbal_conf = min(0.98, max(0.60, round((verbal_base + rng.gauss(0.0, 0.07)) * 20.0) / 20.0))

        records.append(
            {
                "gold": gold_name,
                "decision_scores": decision_scores,
                "raw_pred": pred_trie,
                "raw_conf": raw_probs[pred_trie],
                "naive_pred": naive_pred,
                "naive_conf": naive_conf,
                "abc_pred": abc_pred,
                "abc_conf": abc_probs[abc_pred],
                "verbal_pred": pred_trie,
                "verbal_conf": verbal_conf,
            }
        )
    return records


def main() -> None:
    print(f"Python {sys.version.split()[0]}")

    sample_bpe = {" refund": math.log(0.80 * 0.62), "refund": math.log(0.80 * 0.38)}
    merged_refund = math.exp(merge_bpe_surface_logprobs(sample_bpe)["refund"])

    root = build_trie(LABELS)
    naive_full_tokens = sum(len(toks) for _, toks in LABELS)
    internal_nodes, decision_nodes = count_trie_steps(root)

    # Check a 48-intent hierarchical banking taxonomy (8 categories x 6 sub-intents, 4 tokens each)
    banking48 = tuple(
        (f"cat{c}_sub{s}_action_detail", (f"cat{c}", "_payment_flow", f"_sub{s}", "_issue_detail"))
        for c in range(8)
        for s in range(6)
    )
    b48_root = build_trie(banking48)
    b48_full_tokens = sum(len(toks) for _, toks in banking48)
    _, b48_decision_nodes = count_trie_steps(b48_root)

    print("\n1. BPE Surface Merge and Prefix-Trie Step Compression")
    print(
        f"BPE split check     : 'refund'={math.exp(sample_bpe['refund']) * 100:.1f}%, "
        f"' refund'={math.exp(sample_bpe[' refund']) * 100:.1f}%, "
        f"logsumexp merged={merged_refund * 100:.1f}%"
    )
    print(
        f"8-label support set : {naive_full_tokens} label tokens, {internal_nodes} trie nodes, "
        f"{decision_nodes} decision steps ({(1 - decision_nodes / naive_full_tokens) * 100:.1f}% fewer)"
    )
    print(
        f"48-label banking set: {b48_full_tokens} label tokens, "
        f"{b48_decision_nodes} decision steps ({(1 - b48_decision_nodes / b48_full_tokens) * 100:.1f}% fewer)"
    )

    val_data = simulate_dataset(n_items=300, seed=20261125)
    test_data = simulate_dataset(n_items=1000, seed=20261126)

    temp = fit_temperature(
        [row["decision_scores"] for row in val_data],  # type: ignore[misc]
        [str(row["gold"]) for row in val_data],
    )
    print(f"\nFitted temperature T on 300-ticket validation split: T = {temp:.3f}")

    methods: list[tuple[str, list[str], list[float], int]] = []
    methods.append((
        "Naive token-1 exp(logprob)",
        [str(r["naive_pred"]) for r in test_data],
        [float(r["naive_conf"]) for r in test_data],
        1,
    ))
    methods.append((
        "Single-token IDs (A..H)",
        [str(r["abc_pred"]) for r in test_data],
        [float(r["abc_conf"]) for r in test_data],
        1,
    ))
    methods.append((
        "Verbalized JSON confidence",
        [str(r["verbal_pred"]) for r in test_data],
        [float(r["verbal_conf"]) for r in test_data],
        17,
    ))
    methods.append((
        "Decision-trie logprobs (raw)",
        [str(r["raw_pred"]) for r in test_data],
        [float(r["raw_conf"]) for r in test_data],
        decision_nodes,
    ))

    cal_preds: list[str] = []
    cal_confs: list[float] = []
    for r in test_data:
        probs = softmax_scores(r["decision_scores"], temperature=temp)  # type: ignore[arg-type]
        best = max(probs, key=probs.get)
        cal_preds.append(best)
        cal_confs.append(probs[best])
    methods.append(("Decision-trie + Temp scale", cal_preds, cal_confs, decision_nodes))

    golds = [str(r["gold"]) for r in test_data]

    print("\n2. 1,000-Ticket Held-Out Evaluation")
    print(f"{'Method':<30} {'Steps':>5} {'Acc':>7} {'AUROC':>7} {'ECE':>7} {'Brier':>7}")
    for label, preds, confs, steps in methods:
        correct = [1 if p == g else 0 for p, g in zip(preds, golds)]
        acc = sum(correct) / len(correct)
        auroc = auroc_correctness(confs, correct)
        ece = expected_calibration_error(confs, correct)
        brier = top_label_brier(confs, correct)
        print(f"{label:<30} {steps:>5d} {acc * 100:>6.1f}% {auroc:>7.3f} {ece:>7.3f} {brier:>7.3f}")

    # Verify temperature scaling preserves exact argmax predictions
    assert cal_preds == [str(r["raw_pred"]) for r in test_data]

    print("\n3. Selective Routing Gate at Confidence >= 0.80")
    threshold = 0.80
    for label, preds, confs, _ in methods[2:]:
        auto_idx = [i for i, c in enumerate(confs) if c >= threshold]
        cov = len(auto_idx) / len(test_data)
        mean_stated = sum(confs[i] for i in auto_idx) / len(auto_idx)
        auto_acc = sum(1 for i in auto_idx if preds[i] == golds[i]) / len(auto_idx)
        print(
            f"{label:<30} coverage={cov * 100:>5.1f}%  stated={mean_stated * 100:>5.1f}%  "
            f"actual={auto_acc * 100:>5.1f}%  error_rate={(1 - auto_acc) * 100:>4.1f}%"
        )


if __name__ == "__main__":
    main()
Terminal
python logprobs_trie.py
Output
Python 3.12.16

1. BPE Surface Merge and Prefix-Trie Step Compression
BPE split check     : 'refund'=30.4%, ' refund'=49.6%, logsumexp merged=80.0%
8-label support set : 24 label tokens, 11 trie nodes, 5 decision steps (79.2% fewer)
48-label banking set: 192 label tokens, 9 decision steps (95.3% fewer)

Fitted temperature T on 300-ticket validation split: T = 1.524

2. 1,000-Ticket Held-Out Evaluation
Method                         Steps     Acc   AUROC     ECE   Brier
Naive token-1 exp(logprob)         1   35.7%   0.649   0.157   0.241
Single-token IDs (A..H)            1   60.0%   0.738   0.151   0.227
Verbalized JSON confidence        17   65.5%   0.598   0.212   0.264
Decision-trie logprobs (raw)       5   65.5%   0.800   0.113   0.186
Decision-trie + Temp scale         5   65.5%   0.802   0.029   0.170

3. Selective Routing Gate at Confidence >= 0.80
Verbalized JSON confidence     coverage= 89.3%  stated= 88.3%  actual= 67.2%  error_rate=32.8%
Decision-trie logprobs (raw)   coverage= 53.7%  stated= 93.9%  actual= 84.7%  error_rate=15.3%
Decision-trie + Temp scale     coverage= 33.5%  stated= 90.6%  actual= 92.2%  error_rate= 7.8%

Scope and production limits

  • The 1,000-ticket benchmark simulates post-RLHF sharpened logits (2.85x scale) and 62% / 38% BPE space splits with fixed seeds; measure accuracy and ECE on your own labeled traffic.
  • Chat APIs cap top_logprobs (for example 20 on OpenAI), so assign a small floor logprob when a rare branch token misses top-K, or score exact continuations on vLLM or SGLang.
  • Tokenize every label with the exact serving tokenizer before building the trie because subword boundaries differ across Qwen, Llama, and OpenAI vocabularies.
  • Refit scalar temperature T on 200 to 300 fresh labeled examples whenever you edit the system prompt, label set, or model checkpoint.

Pair calibrated routing with a shadow run for small-model swaps, prefill-vs-decode latency sizing, exact p-value checks on eval gaps, and pytest release gates in CI. Browse every tutorial on the guides page.

Explore this topic in the workspace

Open a structured learning roadmap on classifier calibration, cross-entropy, and log-likelihoods, then highlight any formula to ask side-by-side Horizon follow-up questions.

Or paste Probability calibration, log-likelihoods, and cross-entropy for classifiers on the home page.

Sources

Checked 26 November 2026