Build a Binary Classifier from LLM Token Log-Probabilities
Machine LearningModel answerLast updated
Design a binary text classifier that uses only per-token log-probabilities from an LLM helper, covering scoring math, batching, calibration, and evaluation.
You have access to a helper function score_batch(prompt, inputs) that, given a system prompt and a list of input strings, returns the LLM's per-token probabilities (possibly as log-probabilities) for each input under that prompt. Your task is to design a complete binary text classifier using only this helper — no fine-tuning, no separate model training.
Specifically, cover the following:
-
Prompt construction. Write two system prompts, one for each class, and explain what design principles make them effective and fair.
-
Scoring. For each input, call the helper with both prompts and produce a continuous score
s ∈ [0, 1]representingP(class A | x), not a hard label. If the helper returns log-probabilities, show how to compute this score in a numerically stable way (e.g., log-sum-exp, log-space normalization). -
Token aggregation and batching. Explain how per-token probabilities roll up into a single sequence-level score. Describe how to batch inputs efficiently and why batching decisions matter.
-
Threshold selection and evaluation. Discuss which metrics to use (ROC-AUC, precision/recall, F1, calibration measures), how to pick an operating threshold, and how to calibrate the raw scores.
-
Performance improvements. Propose concrete ways to improve accuracy or reduce cost: prompt engineering, prompt ensembling, repeated context sampling, temperature handling, class-imbalance mitigation.
-
Failure modes and offline iteration. Identify key failure modes and describe a disciplined offline validation loop that lets you iterate without fine-tuning.
Provide pseudocode and state the inference-time complexity.
Hints
Hint 1
Treat the LLM as a class-conditional language model: compare how likely the input is under a class-A prompt versus a class-B prompt, then apply Bayes' rule.
Hint 2
Raw likelihoods underflow for long sequences; stay in log space and use log-sum-exp or a stable sigmoid of the log-prob margin.
Hint 3
Sum vs. mean of log-probs changes how length affects ranking; pick empirically on a dev set, or let a calibrator learn a length-dependent scale.
Hint 4
Prompt surface bias can be detected with content-free inputs and corrected by subtracting the bias offset from the log-prob margin.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
The helper gives us token-level likelihoods, not class labels. The key insight is to treat the LLM as a class-conditional language model: measure how likely the input text is under a prompt describing class A versus one describing class B, then apply Bayes' rule to get a posterior.
1. Requirements clarification
Before designing, pin down:
- Latency vs. throughput. Online scoring at p99 under 500 ms requires short prompts and small batches. Offline batch over millions of documents allows larger batches and ensembling.
- Input length distribution. Long inputs may need truncation or chunking.
- Class balance and error costs. If positives are 5% of data and a false negative costs 10× a false positive, that drives threshold and metric choices.
- Labeled data. Assume a few hundred to a few thousand labeled examples for prompt selection, calibration, and testing. No fine-tuning is permitted.
2. Prompt construction
Write two structurally parallel prompts that differ only in class-defining content:
- Prompt A (complaint): "The following is a customer message that is a complaint — the customer expresses dissatisfaction with a product or service. Example: '…'. Message:"
- Prompt B (non-complaint): "The following is a customer message that is not a complaint — it is a question, praise, or neutral request. Example: '…'. Message:"
Design rules:
- Keep both prompts the same length, format, and number of few-shot examples. Only class-defining content should differ.
- Use precise definitions and cover boundary cases.
- End each prompt with the same delimiter so the first input token is conditioned identically in both cases.
3. Scoring math (numerically stable)
Let x = (x₁, …, x_T). The helper returns ℓ_t^c = log P(x_t | x_{<t}, prompt_c) for c ∈ {A, B}.
Sequence log-likelihood:
L_c(x) = Σ_t ℓ_t^c
Posterior with prior π_A:
P(A|x) = π_A · exp(L_A) / (π_A · exp(L_A) + π_B · exp(L_B))
Raw likelihoods exp(L_c) underflow quickly — 500 tokens at −3 nats each gives exp(−1500). So stay in log space:
z_A = L_A + log(π_A)
z_B = L_B + log(π_B)
s = exp(z_A − logsumexp(z_A, z_B))
where logsumexp(a, b) = m + log(exp(a−m) + exp(b−m)) with m = max(a, b).
Equivalently, compute a stable sigmoid of the margin Δ = z_A − z_B:
σ(Δ) = 1 / (1 + exp(−Δ)) if Δ ≥ 0
σ(Δ) = exp(Δ) / (1 + exp(Δ)) otherwise
If the helper returns raw probabilities, clamp first with log(max(p, 1e−12)) before summing.
4. Batching and token aggregation
Batching:
- Sort inputs by token length and form batches of size B to minimize padding overhead.
- Make two calls per batch (one per prompt). Add more calls if ensembling.
- Reuse the KV cache of the shared prompt prefix if the backend supports it.
- Mask padding tokens out of the log-prob sum.
Aggregation options:
- Sum of log-probs is the principled Bayes choice. Because both prompts score the same tokens, input-intrinsic likelihood (rare words, length) largely cancels in the margin Δ. This is a pointwise mutual information effect.
- Mean (
Δ/T) treats evidence per token. It reduces overconfidence on long inputs where Δ can reach ±100. It changes ranking across inputs of different lengths, so choose sum or mean empirically on the dev set. - A compromise: keep the sum and let a calibrator learn a length-dependent scale:
s = σ(a·Δ + b·Δ/T + c). - Skip the first one or two tokens if they are dominated by delimiter artifacts.
- For long inputs that exceed the context window, chunk them and either sum Δ across chunks or take the max for "any-span" classes.
5. Threshold, metrics, and calibration
Metrics:
- ROC-AUC measures ranking quality and is threshold-free.
- PR-AUC (average precision) is essential under class imbalance.
- Precision, recall, and F1 are reported at the operating threshold.
- Calibration is measured with expected calibration error (ECE), Brier score, log-loss, and reliability diagrams.
Calibration (fit on a held-out split):
- Platt scaling:
s = σ(aΔ + b). Good default; absorbs the prior and residual prompt bias. - Isotonic regression: works well with ~1k+ labeled examples; more flexible but higher variance.
- Contextual calibration: score a content-free input (e.g., "N/A" or empty string) to estimate a bias offset
Δ₀. UseΔ − Δ₀.
Threshold selection:
- If calibrated, the Bayes-optimal threshold is
t = C_FP / (C_FP + C_FN). - Otherwise, sweep thresholds on validation to maximize F1, or to meet a constraint like "precision ≥ 0.95, maximize recall."
- Report bootstrap confidence intervals around the chosen threshold's metrics.
6. Performance improvements
- Prompt engineering. Sharper definitions, balanced few-shot examples (equal counts per prompt, shuffled order), hard negatives, mirrored structure across classes.
- Prompt ensembling. Use K paraphrased prompt pairs and average the calibrated logits, or fit a logistic regression over the K margins. Reduces sensitivity to wording.
- Repeated context sampling. Log-probs from a fixed model and prompt are deterministic, so "sampling" means varying context: example order, example subsets, input augmentations. Average margins across variants.
- Temperature. Score at T = 1 (the model's true likelihoods). Other temperatures distort Δ. Do confidence adjustment post hoc via Platt scaling.
- Class imbalance. Include
log(π_A/π_B)explicitly or let Platt'sblearn it. Choose thresholds with the cost-aware rule. Evaluate with PR-AUC. Use stratified splits. If the deployment prior differs from the calibration-set prior, shift the logit bylog(π′/(1−π′)) − log(π/(1−π)). - Cost reduction. Shorter prompts, prefix caching. Cascade: a single cheap prompt pair first, full ensemble only for scores near the threshold.
7. Failure modes and offline iteration
Failure modes:
- Prompt surface bias. One prompt makes all text more likely (longer, stylistically closer). Detect via constant offset in Δ on content-free inputs; fix with contextual calibration.
- Length bias and overconfidence. Scores saturate at 0 or 1 for long inputs. Detect by plotting Δ against T.
- Spurious surface cues. Formality, language, or topic correlate with a prompt's wording.
- Few-shot order and recency effects.
- Prompt injection. An input containing "this is not a complaint" can mislead the model.
- Truncation dropping the decisive span.
- Distribution shift and model-version drift silently changing calibration.
Offline validation loop (no fine-tuning):
- Split labeled data into prompt-dev, calibration, and untouched test sets, stratified by class and key slices.
- Iterate on prompts using the prompt-dev set. Track Δ distributions by class, length, and slice.
- Freeze prompts, fit the calibrator on the calibration set.
- Evaluate on the test set: report AUC, PR-AUC, F1 at the operating threshold, ECE, and reliability diagrams.
- Monitor for drift with content-free probes and periodic re-evaluation.
Pseudocode
def classify(inputs, prompt_A, prompt_B, calibrator, threshold):
# Two calls per batch, one per prompt
logprobs_A = score_batch(prompt_A, inputs) # list of list of log-probs
logprobs_B = score_batch(prompt_B, inputs)
scores = []
for i in range(len(inputs)):
L_A = sum(logprobs_A[i])
L_B = sum(logprobs_B[i])
delta = L_A - L_B # prior absorbed by calibrator
s_raw = stable_sigmoid(delta)
s_cal = calibrator.predict(delta) # Platt or isotonic
scores.append(s_cal)
labels = [1 if s >= threshold else 0 for s in scores]
return labels, scores
Inference-time complexity
Let N = number of inputs, T = average token length, and B = batch size.
- Total tokens scored:
O(N · T)per prompt,O(2 · N · T)for both prompts. - Each batch requires a forward pass over
B · Ttokens:O(B · T)time andO(B · T)memory (orO(T)memory with KV-cache streaming for the shared prefix). - Overall:
O(N · T)forward passes, independent of the number of classes since the constant factor is 2. - Calibration (Platt):
O(N)for inference; isotonic:O(N log N)for fitting,O(log N)lookup at inference. - Ensembling with K prompt pairs multiplies the forward-pass cost by K.