LeetLLM
My PlanLearnGlossaryTracksPracticeBlog
LeetLLM

Your go-to resource for mastering AI & LLM systems.

Product

  • Learn
  • Glossary
  • Tracks
  • Practice
  • Blog
  • RSS

Legal

  • Terms of Service
  • Privacy Policy

© 2026 LeetLLM. All rights reserved.

All Topics
Your Progress
0%

0 of 196 articles completed

🛠️Computing Foundations0/9
Git, Shell, Linux for AIDocker for Reproducible AIPython for AI EngineeringNumPy and Tensor ShapesCUDA for ML TrainingMPS & Metal for ML on MacData Structures for AISQL and Data ModelingAlgorithms for ML Engineers
📊Math & Statistics0/9
Gradients and BackpropVectors, Matrices & TensorsLinear Algebra for MLAdam, Momentum, SchedulersProbability for Machine LearningBayesian Inference from EvidenceStatistics and UncertaintyDistributions and SamplingHypothesis Tests, Intervals, and pass@k
📚Preparation & Prerequisites0/13
Neural Networks from ScratchCNNs from ScratchTraining & BackpropagationSoftmax, Cross-Entropy & OptimizationRNNs, LSTMs, GRUs, and Sequence ModelingAutoencoders and VAEsThe Transformer Architecture End-to-EndLanguage Modeling & Next TokensFrom GPT to Modern LLMsPrompt Engineering FundamentalsCalling LLM APIs in ProductionFirst AI App End-to-EndThe LLM Lifecycle
🧮ML Algorithms & Evaluation0/15
Linear Regression from ScratchLogistic Regression and MetricsDecision Trees, Forests, and BoostingReinforcement Learning BasicsValidation and LeakageStatistical Learning and GeneralizationConformal Prediction and UncertaintyClustering and PCAProbabilistic Generative ModelsCore Retrieval AlgorithmsDecoding AlgorithmsExperiment Design and A/B TestingCausal Inference and CounterfactualsPyTorch Training LoopsDataset Pipelines and Data Quality
📦Production ML Systems0/6
Feature Engineering for Production MLBatch and Streaming Feature PipelinesGradient Boosted Trees in ProductionRanking and Recommendation SystemsForecasting and Anomaly DetectionMonitoring Predictive Models
🧪Core LLM Foundations0/8
The Bitter Lesson & ComputeBPE, WordPiece, and SentencePieceStatic to Contextual EmbeddingsPerplexity & Model EvaluationFile Ingestion for AIChunking StrategiesLLM Benchmarks & LimitationsInstruction Tuning & Chat Templates
🧰Applied LLM Engineering0/25
Dimensionality Reduction for EmbeddingsCoT, ToT & Self-Consistency PromptingFunction Calling & Tool UseMCP & Tool Protocol StandardsContext EngineeringPrompt Injection DefenseResponsible AI GovernancePrivacy-Preserving Machine LearningData Labeling and Human FeedbackEvaluating AI AgentsProduction RAG PipelinesHybrid Search: Dense + SparseReranking and Cross-Encoders for RAGRAG Evaluation for Reliable AnswersLLM-as-a-Judge EvaluationBias & Fairness in LLMsHallucination Detection & MitigationLLM Observability & MonitoringExperiment Tracking with MLflow and W&BPrompt Optimization with DSPyModel Versioning & DeploymentSemantic Caching & Cost OptimizationLLM Cost Engineering & Token EconomicsModel Gateways, Routing, and FallbacksDesign an Automated Support Agent
🎓Portfolio Capstones0/9
Capstone: Delivery ETA PredictionCapstone: Product RankingCapstone: Demand ForecastingCapstone: Image Damage ClassifierCapstone: Production ML PipelineCapstone: Document QACapstone: Eval DashboardCapstone: Fine-Tuned ClassifierCapstone: Reproducible ML Study
🧠Transformer Deep Dives0/8
Sentence Embeddings & Contrastive LossEmbedding Similarity & QuantizationScaled Dot-Product AttentionVision Transformers and Image EncodersPositional Encoding: RoPE & ALiBiLayer Normalization: Pre-LN vs Post-LNMechanistic InterpretabilityDecoding Strategies: Greedy to Nucleus
🧬Advanced Training & Adaptation0/17
Scaling Laws & Compute-Optimal TrainingPre-training Data at ScaleBuild GPT from Scratch LabJAX for PyTorch ResearchersContinued Pretraining for Domain ShiftSynthetic Data PipelinesSupervised Fine-Tuning PipelineMixed Precision TrainingDistributed Training: FSDP & ZeROLoRA & Parameter-Efficient TuningTraining Run OperationsReward Modeling from Preference DataRLHF & DPO AlignmentConstitutional AI & Red TeamingRLVR & Verifiable RewardsKnowledge Distillation for LLMsModel Merging and Weight Interpolation
🤖Advanced Agents & Retrieval0/16
Vector DB Internals: HNSW & IVFAdvanced RAG: HyDE & Self-RAGGraphRAG & Knowledge GraphsRAG Security & Access ControlStructured Output GenerationReAct & Plan-and-ExecuteGuardrails & Safety FiltersCode Generation & SandboxingComputer-Use / GUI / Browser AgentsHuman-in-the-Loop Agent ArchitectureAI Coding Workflow with AgentsAgent Memory & PersistenceAgent Failure & RecoveryRecursive Language Models (RLM)Multi-Agent OrchestrationCapstone: Production Agent
⚡Inference & Production Scale0/31
Inference: TTFT, TPS & KV CacheMulti-Query & Grouped-Query AttentionKV Cache & PagedAttentionPrefix Caching and Prompt CachingFlashAttention & Memory EfficiencyContinuous Batching & SchedulingScaling LLM InferenceModel Parallelism for LLM InferenceAccelerator Architecture Field GuideCorrect GPU Profiling and BenchmarkingGPU Kernel Performance Engineering LabGPU Parallel Primitives LabGPU Compilers and Kernel LanguagesGEMM From Naive CUDA to Tensor CoresLow-Precision GPU ProgrammingGPU Runtime Execution LabAI-Generated Kernel EngineeringModel Quantization: GPTQ, AWQ & GGUFLocal LLM DeploymentSLM Specialization & Edge DeploymentSpeculative DecodingLong Context Window ManagementMixture of Experts ArchitectureMamba & State Space ModelsReasoning & Test-Time ComputeAdvanced MLOps & DevOps for AIGPU Serving & AutoscalingGPU Failure OperationsDistributed Inference Data PlaneServing Benchmark EngineeringA/B Testing for LLMs
🏗️System Design Capstones0/9
Content Moderation SystemCode Completion SystemMulti-Tenant LLM PlatformLLM-Powered Search EngineVision-Language Models & CLIPMultimodal LLM ArchitectureDiffusion Models: Images & TextReal-Time Voice AI AgentReasoning Agent System Design
🎤AI Lab Interviewing0/4
AI Lab Coding Interview: Python SystemsAI Lab System Design InterviewAI Lab Behavioral InterviewAI Lab Technical Presentation
🔬Project Deep Dives0/17
Deep Dive - vLLMDeep Dive - SkyRLDeep Dive - FlashAttentionDeep Dive - FlashInferDeep Dive - DeepGEMMDeep Dive - NCCLDeep Dive - MegatronDeep Dive - DeepSpeedDeep Dive - RayDeep Dive - MLflowDeep Dive - PyTorchDeep Dive - TransformersDeep Dive - SGLangDeep Dive - slimeDeep Dive - DeepEPDeep Dive - TinkerDeep Dive - Light-PEFT
Back to Topics
LearnML Algorithms & EvaluationConformal Prediction and Uncertainty
📊MediumEvaluation & Benchmarks

Conformal Prediction and Uncertainty

Build finite-sample conformal prediction intervals, compute corrected calibration quantiles, and diagnose subgroup and distribution-shift failures.

15 min read
Learning path
Step 38 of 196 in the full curriculum
Statistical Learning and GeneralizationClustering and PCA

Personalize this lesson

Adapt explanations and teaching visuals to your background and preferred voice.

A latency model predicts that the next request will finish in 40 milliseconds. Should a caller rely on a 50-millisecond deadline? A prediction interval such as [32, 48] adds information the point prediction lacks, but even that range isn't a promise about this particular request.

Statistical Learning and Generalization established why untouched evidence matters. Traditional confidence intervals often assume normally distributed errors or asymptotic large-sample limits. When production traffic experiences heavy tails or bursty queues, those parametric assumptions break down. Split conformal prediction circumvents this issue by using a separate calibration split to wrap any frozen model's point predictions with statistically rigorous prediction intervals or prediction sets C(X)C(X)C(X).[1]Reference 1A Gentle Introduction to Conformal Prediction and Distribution-Free Uncertainty Quantificationhttps://arxiv.org/abs/2107.07511

Under an exchangeability condition on the data, split conformal prediction guarantees that future outcomes fall inside the prediction set with at least a chosen probability:

Pr⁡ ⁣(Yn+1∈C(Xn+1))≥1−α\Pr\!\left(Y_{n+1} \in C(X_{n+1})\right) \geq 1 - \alphaPr(Yn+1​∈C(Xn+1​))≥1−α

Here α∈(0,1)\alpha \in (0, 1)α∈(0,1) represents the allowed miscoverage rate (for example, α=0.20\alpha = 0.20α=0.20 for an 80% coverage target). This guarantee holds for any sample size nnn, without requiring Gaussian errors, linear relationships, or parametric families.

All latency values below are synthetic teaching data. We start with predictions already made by a frozen model; this lesson calibrates their uncertainty rather than fitting another predictor.

Freeze the model before measuring its errors

Before calculating a radius, decide which rows are allowed to influence it. Three slices play different roles:

SplitRoleProhibited shortcut
TrainingFit the latency modelReport training residuals as independent calibration
CalibrationMeasure errors from the already-frozen modelTune the model repeatedly against calibration outcomes
Test or deploymentCheck interval coverage on new requestsInclude those outcomes in the original coverage claim

Choose features, preprocessing, model settings, and the score rule before using calibration outcomes. Any model selection needs its own validation data within the training workflow. Once calibration starts, freeze that whole prediction procedure, not just its final layer.

For a 40-millisecond prediction, an observed 44 milliseconds gives an error of 4; an observed 53 gives an error of 13. A simple regression nonconformity score records that miss as the absolute residual si=∣yi−y^i∣s_i = |y_i - \widehat{y}_i|si​=∣yi​−y​i​∣. Larger scores mean the point prediction missed by more.

The finite-sample guarantee relies on exchangeable calibration and future examples, conditional on the fitted procedure: their joint distribution is unchanged by permuting their positions. Formally, for nnn calibration points and one future test point:

P(Z1,…,Zn,Zn+1)=P(Zπ(1),…,Zπ(n),Zπ(n+1))P(Z_1, \dots, Z_n, Z_{n+1}) = P(Z_{\pi(1)}, \dots, Z_{\pi(n)}, Z_{\pi(n+1)})P(Z1​,…,Zn​,Zn+1​)=P(Zπ(1)​,…,Zπ(n)​,Zπ(n+1)​)

for every permutation π∈Sn+1\pi \in S_{n+1}π∈Sn+1​, where Zi=(Xi,Yi)Z_i = (X_i, Y_i)Zi​=(Xi​,Yi​). Independent draws from the same distribution satisfy this condition. A queueing time series, diurnal traffic swings, or an altered prompt distribution may not. Shuffling an already shifted log doesn't restore exchangeability.[2]Reference 2Conformal Prediction Beyond Exchangeabilityhttps://arxiv.org/abs/2202.13415

A model was repeatedly tuned using the same nine examples later labeled as its calibration split. Why can't their residuals support the ordinary split-conformal guarantee?

Answer

Those outcomes influenced the model before calibration, so their residuals are no longer held-out measurements of a frozen predictor. Their apparent errors can be optimistically small, and the ordinary exchangeability argument for fresh request outcomes no longer follows.

Let nine errors choose the radius

Our nine held-out requests produce these sorted absolute errors, measured in milliseconds. Which position should set the radius for the next request?

[2,3,3,4,5,6,7,8,12][2, 3, 3, 4, 5, 6, 7, 8, 12][2,3,3,4,5,6,7,8,12]

For 80% target coverage, allow a miscoverage rate of α=0.20\alpha = 0.20α=0.20. With nine calibration errors plus one future error, there are ten possible rank positions. Covering the first eight positions gives 8/10 = 80%. The correction counts the future request as well as the calibration requests.

In general, with calibration size nnn, select the following residual quantile. Its order statistic, the value at a numbered position in the sorted sample, has rank:[1]Reference 1A Gentle Introduction to Conformal Prediction and Distribution-Free Uncertainty Quantificationhttps://arxiv.org/abs/2107.07511

k=⌈(n+1)(1−α)⌉=⌈10×0.8⌉=8k = \left\lceil(n+1)(1-\alpha)\right\rceil = \lceil10 \times 0.8\rceil = 8k=⌈(n+1)(1−α)⌉=⌈10×0.8⌉=8

The ceiling brackets mean round upward. For example, an 85% target would require ⌈10×0.85⌉=9\lceil10 \times 0.85\rceil = 9⌈10×0.85⌉=9, not eight. At our 80% target, rank eight selects an 8 ms error. Call this selected radius qqq. A new prediction of 40 milliseconds therefore gets:

[y^−q,y^+q]=[40−8,40+8]=[32,48][\widehat y - q, \widehat y + q] = [40 - 8, 40 + 8] = [32, 48][y​−q,y​+q]=[40−8,40+8]=[32,48]
Nine sorted calibration residuals plotted by rank: 2, 3, 3, 4, 5, 6, 7, 8, 12 milliseconds. Rank eight selects the 8 millisecond radius for 80% target coverage under the finite-sample correction ceil((n+1)(1-alpha)). A side panel breaks down sample size, rank formula, tail error, and marginal validity.
Rank chooses a position, not an error magnitude. Here both happen to be 8: the eighth error is 8 ms. If that error changed to 9 ms, the rank would stay eight but the interval would widen.

The next cell constructs the absolute errors from frozen predictions and outcomes. Its helper selects an observed order statistic directly, avoiding interpolation between two residuals. Python index rank - 1 converts the one-based rank to a zero-based list position.

calibrate-latency-prediction-interval.py
1from math import ceil, inf, isfinite 2 3def conformal_radius(scores, coverage): 4 if not 0 < coverage < 1: 5 raise ValueError("coverage must be strictly between 0 and 1") 6 ordered = sorted(scores) 7 if not ordered or any(not isfinite(s) or s < 0 for s in ordered): 8 raise ValueError("provide nonempty, finite, nonnegative scores") 9 rank = ceil((len(ordered) + 1) * coverage) 10 radius = ordered[rank - 1] if rank <= len(ordered) else inf 11 return rank, radius 12 13cal_predictions = [30, 35, 40, 45, 50, 55, 60, 65, 70] 14cal_observed = [32, 32, 43, 41, 55, 49, 67, 57, 82] 15residuals = sorted(abs(actual - guess) 16 for guess, actual in zip(cal_predictions, cal_observed, strict=True)) 17rank, radius = conformal_radius(residuals, coverage=0.80) 18prediction = 40 19 20print("sorted absolute errors:", residuals) 21print(f"corrected rank: {rank} of {len(residuals)}") 22print(f"calibration radius: {radius} ms") 23print(f"prediction interval: [{prediction - radius}, {prediction + radius}] ms")
Output
1sorted absolute errors: [2, 3, 3, 4, 5, 6, 7, 8, 12] 2corrected rank: 8 of 9 3calibration radius: 8 ms 4prediction interval: [32, 48] ms

The helper returns inf when the requested rank exceeds the available scores. That's deliberate, not a numerical failure. At 90% coverage the ninth error gives radius 12; at 95% the required rank is ten. The standard rule then uses q=+∞q=+\inftyq=+∞, giving the entire real line rather than inventing a tenth error.[1]Reference 1A Gentle Introduction to Conformal Prediction and Distribution-Free Uncertainty Quantificationhttps://arxiv.org/abs/2107.07511

Check the boundary in code. Raising the target can only preserve or widen the interval:

handle-an-unavailable-finite-quantile.py
1for coverage in (0.80, 0.90, 0.95): 2 rank, q = conformal_radius(residuals, coverage) 3 print(f"target={coverage:.0%} rank={rank} radius={q} width={2*q}")
Output
1target=80% rank=8 radius=8 width=16 2target=90% rank=9 radius=12 width=24 3target=95% rank=10 radius=inf width=inf

Don't clip rank ten to nine: a largest-of-nine threshold supports a 90% lower bound in the no-ties case, not 95%. With 19 calibration errors, 95% first becomes possible with a finite observed threshold: ⌈20×0.95⌉=19\lceil20 \times 0.95\rceil = 19⌈20×0.95⌉=19. That's a mathematical minimum, not a recommendation for a stable calibration sample. Known bounds on the outcome could support other finite sets; the unavailable threshold here is specific to this residual-quantile construction.

Why does the example choose the eighth residual instead of simply multiplying nine by 0.8 and rounding down?

Answer

The finite-sample conformal rank is ceil((n+1)(1-alpha)). For nine calibration rows and 80% coverage, that is ceil(10 times 0.8), which selects the eighth order statistic.

Why the extra rank gives coverage

Temporarily imagine ten distinct scores, one from the future request and nine from calibration. Exchangeability makes the future request equally likely to occupy any of the ten sorted positions. Its score is no larger than the eighth calibration score exactly when it lands in positions one through eight.

You can inspect every possible test position without a random simulation. The following scores are a separate rank-only example, not additional latency measurements. Each pass holds out one score and calibrates on the remaining nine:

enumerate-the-ten-possible-test-ranks.py
1scores = list(range(1, 11)) 2covered_positions = [] 3 4for index, test_score in enumerate(scores): 5 calibration = scores[:index] + scores[index + 1:] 6 _, q = conformal_radius(calibration, coverage=0.80) 7 if test_score <= q: 8 covered_positions.append(index + 1) 9 10print("covered test ranks:", covered_positions) 11print(f"covered positions: {len(covered_positions)}/{len(scores)}")
Output
1covered test ranks: [1, 2, 3, 4, 5, 6, 7, 8] 2covered positions: 8/10

Our latency fixture has tied errors at 3 ms. Ties don't invalidate the lower coverage bound when the set includes the boundary (score <= q); they can make coverage conservative. Don't discard tied rows or promise exact 80% coverage. When scores are almost surely distinct (continuous nonconformity scores), conformal prediction also provides a tight upper bound on coverage:

1−α≤Pr⁡ ⁣(Ynew∈C(Xnew))≤1−α+1n+11 - \alpha \leq \Pr\!\left(Y_{\mathrm{new}} \in C(X_{\mathrm{new}})\right) \leq 1 - \alpha + \frac{1}{n+1}1−α≤Pr(Ynew​∈C(Xnew​))≤1−α+n+11​

The upper bound demonstrates that split conformal prediction isn't overly conservative. With n=9n = 9n=9 and 1−α=0.801 - \alpha = 0.801−α=0.80, coverage is sandwiched between 80% and 80%+1/10=90%80\% + 1/10 = 90\%80%+1/10=90%. The rank argument doesn't require the predictor to be correct; a poor predictor will usually pay through less useful intervals.[3]Reference 3Distribution-Free Predictive Inference for Regressionhttps://www.stat.cmu.edu/~ryantibs/papers/conformal.pdf

Watch coverage appear in new requests

The interval [32, 48] covers an actual 44-millisecond outcome and misses 53 milliseconds. That single request tells us what the rule does, not whether the rule is reliable. Coverage is measured across a stream of new comparable examples.

Keep the 80% radius 8 fixed and inspect four new synthetic request outcomes. Each request has its own interval centered at its prediction. Before running the cell, predict which outcome falls outside.

Side-by-side comparison of fixed-radius versus locally adaptive conformal prediction intervals on four held-out requests with predictions 40, 42, 38, and 44 milliseconds and observed outcomes 44, 48, 35, and 55 milliseconds. On the left, fixed intervals of width 16 milliseconds miss request D because outcome 55 lies beyond upper endpoint 52. On the right, locally adaptive intervals scale with conditional standard deviation, producing a tight 8-millisecond interval for easy request C and a wider 24-millisecond interval for high-variance request D, covering all four requests.
Fixed-width intervals center around point predictions but maintain a constant radius. Under heteroscedastic noise, fixed intervals miss on high-variance requests like D while staying unnecessarily loose on low-variance requests like C.
measure-held-out-interval-coverage.py
1predictions = [40, 42, 38, 44] 2observed = [44, 48, 35, 55] 3 4covered = [abs(actual - guess) <= radius 5 for guess, actual in zip(predictions, observed, strict=True)] 6for guess, actual, is_covered in zip(predictions, observed, covered): 7 print(f"predicted={guess} actual={actual} covered={is_covered}") 8 9print(f"observed coverage: {sum(covered)}/{len(covered)}") 10print(f"interval width: {2 * radius} ms")
Output
1predicted=40 actual=44 covered=True 2predicted=42 actual=48 covered=True 3predicted=38 actual=35 covered=True 4predicted=44 actual=55 covered=False 5observed coverage: 3/4 6interval width: 16 ms

A four-row observed coverage of 75% doesn't contradict an 80% marginal coverage guarantee. Four requests are a noisy sample, so the observed fraction can move around the target.

Two sources of variation exist: this calibration sample selected one particular radius, and the four test outcomes are another small sample. Even a very long test run with that fixed radius needn't achieve the nominal coverage. Standard split conformal isn't a guarantee conditional on one realized calibration set.[1]Reference 1A Gentle Introduction to Conformal Prediction and Distribution-Free Uncertainty Quantificationhttps://arxiv.org/abs/2107.07511

Classification nonconformity scores and adaptive prediction sets

Conformal prediction isn't limited to regression intervals. In multiclass classification, the output C(X)⊆YC(X) \subseteq \mathcal{Y}C(X)⊆Y is a set of candidate classes guaranteed to contain the true label with probability at least 1−α1 - \alpha1−α.

Different nonconformity scores produce different set behaviors:

  1. Naive softmax score: Let f^(x)y\widehat{f}(x)_yf​(x)y​ denote the model's estimated probability for class yyy. The score is s(x,y)=1−f^(x)ys(x, y) = 1 - \widehat{f}(x)_ys(x,y)=1−f​(x)y​. After computing threshold q^\widehat{q}q​ on calibration data, the prediction set includes all classes whose predicted probability is at least 1−q^1 - \widehat{q}1−q​:
C(X)={y∈Y:f^(X)y≥1−q^}C(X) = \left\{y \in \mathcal{Y} : \widehat{f}(X)_y \geq 1 - \widehat{q}\right\}C(X)={y∈Y:f​(X)y​≥1−q​}

When a query is ambiguous and the model distributes probability thinly across many classes (for example, four classes near 0.25), no single class may exceed 1−q^1 - \widehat{q}1−q​. That produces an empty prediction set C(X)=∅C(X) = \emptysetC(X)=∅.

  1. Adaptive Prediction Sets (APS): To avoid empty sets and adapt set sizes to instance difficulty, sort the predicted class probabilities in descending order π(1)(x)≥π(2)(x)≥⋯≥π(K)(x)\pi_{(1)}(x) \geq \pi_{(2)}(x) \geq \dots \geq \pi_{(K)}(x)π(1)​(x)≥π(2)​(x)≥⋯≥π(K)​(x). Accumulate probabilities until reaching the true class label yyy:[1]Reference 1A Gentle Introduction to Conformal Prediction and Distribution-Free Uncertainty Quantificationhttps://arxiv.org/abs/2107.07511
s(x,y)=∑j=1kπ(j)(x)where π(k)(x)=ys(x, y) = \sum_{j=1}^{k} \pi_{(j)}(x) \quad \text{where } \pi_{(k)}(x) = ys(x,y)=j=1∑k​π(j)​(x)where π(k)​(x)=y

At test time, the prediction set accumulates sorted classes until their cumulative probability mass reaches or exceeds the calibrated threshold q^\widehat{q}q​:

C(X)={π(1)(x),…,π(m)(x)}where m=min⁡{j:∑i=1jπ(i)(x)≥q^}C(X) = \left\{\pi_{(1)}(x), \dots, \pi_{(m)}(x)\right\} \quad \text{where } m = \min\left\{j : \sum_{i=1}^j \pi_{(i)}(x) \geq \widehat{q}\right\}C(X)={π(1)​(x),…,π(m)​(x)}where m=min{j:i=1∑j​π(i)​(x)≥q​}

On easy examples with high confidence (say, top class probability 0.98), C(X)C(X)C(X) contains a single label. On difficult, ambiguous queries, C(X)C(X)C(X) automatically expands to contain multiple classes, preserving marginal coverage while signaling uncertainty through set size.

Why does Adaptive Prediction Sets (APS) prefer accumulating sorted probabilities over thresholding individual softmax outputs?

Answer

Thresholding individual softmax probabilities can produce empty sets on difficult, ambiguous inputs where probability mass is dispersed. APS accumulates sorted probabilities until reaching the calibrated threshold, ensuring non-empty prediction sets whose size dynamically reflects input ambiguity.

Find the traffic the average hides

The four-row result measures overall empirical coverage. Breaking that count down by request type asks a different question: who receives the misses?

That guarantee isn't conditional coverage for every subgroup or individual feature value. Consider a constructed evaluation report with 750 short and 250 long requests. Short requests have 96% coverage; long requests have only 54%. The weighted average still exceeds 80%:

750(0.96)+250(0.54)1000=0.855\frac{750(0.96) + 250(0.54)}{1000} = 0.8551000750(0.96)+250(0.54)​=0.855

These are hypothetical counts, not results from the four-request test above. They expose what an aggregate metric can hide. If the mix shifted to half short and half long while those subgroup rates stayed the same, overall coverage would fall to 0.5 * 0.96 + 0.5 * 0.54 = 75%. The old population guarantee wouldn't transfer automatically to that new mix.[2]Reference 2Conformal Prediction Beyond Exchangeabilityhttps://arxiv.org/abs/2202.13415

An 80% conformal target passes across all traffic, but long requests are covered only 54% of the time. Does the population-wide guarantee refute the long-request measurement?

Answer

No. Standard split conformal guarantees marginal coverage across the exchangeable population, not equal conditional coverage for every prompt-length subgroup. A common well-covered group can keep the aggregate above target while a smaller long-request group remains unsafe.

Different failures call for different repairs:

FailureSymptomAppropriate response
Model trained on calibration rowsResiduals look too smallRefit with a genuinely separate calibration split
Prompt lengths shift after launchRecent interval misses cluster on long promptsInvestigate the shift; fresh calibration helps only if its assumptions fit subsequent traffic
Tenant-specific error differsOverall coverage passes while one tenant failsMeasure subgroup coverage; consider separately calibrated, predefined groups
Noise grows with request sizeConstant intervals are too narrow for large requestsUse normalized nonconformity scores or group-aware methods
Calibration sample is tinyDesired rank exceeds available observationsGather more data or acknowledge an unbounded set

Constant width isn't the only option. Suppose a second trained model predicts error scales of 3 ms for a short request and 6 ms for a long one. If calibration of normalized errors yields a threshold of 2, their interval radii become 2 * 3 = 6 ms and 2 * 6 = 12 ms. That threshold needs its own calibration; it isn't the 8 ms threshold from the raw-error example.

In symbols, learn a positive error scale a(x)a(x)a(x) using training data, then calibrate scores ∣y−f^(x)∣/a(x)|y - \widehat f(x)| / a(x)∣y−f​(x)∣/a(x). The interval becomes f^(x)±q a(x)\widehat f(x) \pm q\,a(x)f​(x)±qa(x). Both models must be frozen before calibration; this changes how width adapts, not the marginal guarantee into exact conditional coverage.[3]Reference 3Distribution-Free Predictive Inference for Regressionhttps://www.stat.cmu.edu/~ryantibs/papers/conformal.pdf

Conformal risk control for language model triage routing

Modern language model systems often require bounds on general losses rather than simple interval coverage. In conformal risk control, the objective expands from set containment to bounding the expected value of any bounded loss function ℓ(C(X),Y)∈[0,1]\ell(C(X), Y) \in [0, 1]ℓ(C(X),Y)∈[0,1]:[1]Reference 1A Gentle Introduction to Conformal Prediction and Distribution-Free Uncertainty Quantificationhttps://arxiv.org/abs/2107.07511

E[ℓ(Cλ(X),Y)]≤α\mathbb{E}\left[\ell\left(C_\lambda(X), Y\right)\right] \leq \alphaE[ℓ(Cλ​(X),Y)]≤α

Here λ\lambdaλ represents a tunable parameter (such as an uncertainty cutoff or threshold). In production language model pipelines, two triage workflows build on this mechanism:

  1. Hallucination filtering and human escalation: An evaluator or verifier scores each generated answer with an uncertainty metric u(x)u(x)u(x) (such as token entropy, consistency variance across sampled rollouts, or an external critic score). By calibrating threshold λ\lambdaλ, the pipeline routes requests with u(x)>λu(x) > \lambdau(x)>λ to human review or a fallback search pipeline, guaranteeing that accepted answers maintain an error rate below α\alphaα.
  2. Selective intent routing: For tool-calling or API agents, classification prediction sets determine autonomy. If the prediction set contains exactly one intent (∣C(X)∣=1|C(X)| = 1∣C(X)∣=1), the system executes the tool call automatically. If ∣C(X)∣>1|C(X)| > 1∣C(X)∣>1, the query triggers a clarification prompt or routes to human support.

How does conformal triage routing turn set size into an operational decision for an autonomous agent?

Answer

When the calibrated prediction set contains a single candidate action, the agent executes autonomously. When uncertainty expands the set to multiple candidates or an empty set, the agent halts and routes the request to human review or asks the user for clarification.

Check the decision, not just the percentage

A coverage number without interval width is incomplete. An interval spanning the entire outcome space never misses, but it can't guide a 50-millisecond deadline.

Return to the deadline question. [32, 48] sits below 50 ms, but the 80% marginal guarantee doesn't mean this request has an 80% conditional chance of meeting its deadline. Selecting only requests with upper endpoints below 50 also creates a subgroup; ordinary marginal validity alone doesn't certify that selected group's failure rate.

For monitoring, retain the model and calibration versions, each interval, actual outcome, request group, and width. Inspect counts as well as percentages. A scorecard with two long requests can't establish a reliable long-request rate, and no finite log proves that future traffic will stay exchangeable.

Try these changes to the cells before checking the expected result:

ExperimentExpected result and interpretation
Change the eighth sorted calibration error from 8 to 9Rank stays eight; radius becomes 9 and the 40 ms interval becomes [31, 49]. Rank and value are different quantities.
Change the fourth test outcome from 55 to 52All four outcomes are covered because endpoints are included. This is still a four-row observation, not proof of 100% future coverage.
Clip the 95% rank to nineThe code would return radius 12, hiding that the ordinary finite-sample rule required infinity. A finite output isn't evidence of a valid 95% guarantee.
Compare the short/long report under a 75/25 versus 50/50 mixAggregate coverage changes from 85.5% to 75% even with identical subgroup rates.
Complete the lesson

Mastery Check

Answer every question, then check your score. Score 75% or higher to mark this lesson complete.

1.What must the calibration examples represent in ordinary split conformal prediction?

Correct answer: Held-out outcomes scored after the prediction model has been frozen.

The calibration outcomes must stay out of fitting and model selection. Scoring them with a frozen procedure preserves the rank argument when calibration and future examples are exchangeable. A held-out split alone doesn't establish exchangeability under changed traffic.

2.Nine calibration residuals are available and target coverage is 80%. Which order-statistic rank is used?

Correct answer: Rank eight, computed as the ceiling of ten multiplied by 0.8.

The finite-sample rank is ceil((n+1)(1-alpha)), giving ceil(10*0.8)=8.

3.A prediction is 40 ms, the calibrated radius is 8 ms, and the observed outcome is exactly 48 ms. What does the split-conformal rule report?

Correct answer: Coverage, because the closed interval [32, 48] includes its endpoints.

The set contains candidates with score <= q. Here abs(48-40)=8, so the outcome is covered. Keeping the boundary also preserves the lower coverage guarantee with tied scores; ties may make coverage conservative.

4.What does an 80% marginal conformal coverage guarantee claim under its assumptions?

Correct answer: Across exchangeable calibration and future draws, true outcomes are covered at least 80% of the time.

Standard split conformal provides a marginal repeated-draw coverage statement, not exact subgroup or individual-interval guarantees.

5.Why can a traffic shift invalidate the ordinary conformal coverage argument?

Correct answer: Calibration and new requests may no longer be exchangeable under the same data-generating regime.

The standard rank argument depends on calibration and future examples being exchangeable; changed traffic can break that condition.

6.Nine calibration rows are used for a requested 95% finite-sample coverage level. What happens?

Correct answer: Rank ten is required, so this sample cannot supply the requested finite observed quantile.

ceil((9+1)*0.95)=10, but only nine calibration scores exist. The ordinary rule uses an infinite threshold, not a clipped rank of nine. Nineteen calibration scores first allow a finite observed 95% threshold, though that remains a very small sample.

7.Why should deployment monitoring report interval width as well as observed coverage?

Correct answer: An interval can achieve high coverage while being too wide to support a useful decision.

Coverage alone can be maximized by making intervals extremely wide, so their practical usefulness also depends on width and decision thresholds.

8.Overall coverage passes, but long-prompt requests miss frequently. Which conclusion is justified?

Correct answer: Aggregate coverage can hide subgroup failure, so slice-specific coverage needs inspection.

A marginal coverage guarantee does not ensure equal conditional coverage for every subgroup, so segment-level monitoring matters.

8 questions remaining.

Next Step
Continue to Clustering and PCA

Here, observed outcomes let you calibrate prediction errors. Next, set the outcomes aside and look for structure in the input features themselves.

PreviousStatistical Learning and Generalization
Share this article
XFacebookLinkedInBlueskyRedditHacker NewsEmail
References

A Gentle Introduction to Conformal Prediction and Distribution-Free Uncertainty Quantification

Angelopoulos, A. N. & Bates, S. · 2021

https://arxiv.org/abs/2107.07511

Conformal Prediction Beyond Exchangeability

Barber, R. F., Candès, E. J., Ramdas, A., & Tibshirani, R. J. · 2022

https://arxiv.org/abs/2202.13415

Distribution-Free Predictive Inference for Regression

Jing Lei, Max G'Sell, Alessandro Rinaldo, Ryan J. Tibshirani, Larry Wasserman · 2018

https://www.stat.cmu.edu/~ryantibs/papers/conformal.pdf

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.