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 192 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/27
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 Compilers and Kernel LanguagesGEMM From Naive CUDA to Tensor CoresLow-Precision GPU ProgrammingModel 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 & AutoscalingDistributed 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.

7 min read
Learning path
Step 38 of 192 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. That single number doesn't tell an on-call engineer whether a 50-millisecond deadline is safe. A prediction interval such as [32,48] makes the decision visible, but the range earns trust only when its coverage evidence comes from requests the model never saw during fitting.

Statistical Learning and Generalization established why untouched evidence matters. Here, conformal prediction uses a separate calibration split to turn those model errors into finite-sample prediction sets.[1]Reference 1A Gentle Introduction to Conformal Prediction and Distribution-Free Uncertainty Quantificationhttps://arxiv.org/abs/2107.07511

Nine calibration residuals increase from 2 to 12 milliseconds; corrected rank eight selects an 8 millisecond radius, producing a 32 to 48 millisecond interval around a 40 millisecond prediction.
The eighth of nine held-out errors sets the 80% conformal radius. A 40 millisecond prediction becomes a 32 to 48 millisecond interval without reusing training residuals.

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

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.

Diagram showing Fit model, Freeze, Held-out errors, and Rank 8.
Fit model, Freeze, Held-out errors, and Rank 8.

The diagram turns those held-out errors into one radius. Its guarantee needs exchangeable calibration and future examples: their joint distribution stays the same when their positions are swapped. Shuffling files doesn't repair a changed deployment distribution.

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

Nine held-out requests produce these sorted absolute errors, measured in milliseconds. The list gives us a small decision to make: 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 target coverage 1−α=0.81-\alpha=0.81−α=0.8 and calibration size n=9n=9n=9, split conformal selects a corrected 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\times0.8\rceil=8k=⌈(n+1)(1−α)⌉=⌈10×0.8⌉=8

Rank eight points to a residual of 8 milliseconds. 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]

The next cell repeats that arithmetic, checks that this calibration size can reach the requested coverage, and prints the interval. Predict its rank and bounds before running it.

calibrate-latency-prediction-interval.py
1from math import ceil 2 3residuals = sorted([2, 3, 3, 4, 5, 6, 7, 8, 12]) 4coverage = 0.80 5rank = ceil((len(residuals) + 1) * coverage) 6 7if rank > len(residuals): 8 raise ValueError("Calibration sample is too small for the requested finite interval") 9 10radius = residuals[rank - 1] 11prediction = 40 12 13print(f"corrected rank: {rank} of {len(residuals)}") 14print(f"calibration radius: {radius} ms") 15print(f"prediction interval: [{prediction - radius}, {prediction + radius}] ms")
Output
1corrected rank: 8 of 9 2calibration radius: 8 ms 3prediction interval: [32, 48] ms

Now raise the target to 95% while keeping nine calibration rows. The rank is ⌈10×0.95⌉=10\lceil10\times0.95\rceil=10⌈10×0.95⌉=10, but no tenth observed residual exists. A distribution-free finite interval at that level isn't available from this tiny sample; gather more calibration data or explicitly admit an unbounded set.

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.

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 radius 8 fixed and inspect four new request outcomes. Before running the cell, predict how many will land inside the interval.

measure-held-out-interval-coverage.py
1predictions = [40, 42, 38, 44] 2observed = [44, 48, 35, 55] 3 4covered = [abs(actual - guess) <= radius for guess, actual in zip(predictions, observed)] 5for guess, actual, is_covered in zip(predictions, observed, covered): 6 print(f"predicted={guess} actual={actual} covered={is_covered}") 7 8print(f"observed coverage: {sum(covered)}/{len(covered)}")
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

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.

The guarantee averages over repeated exchangeable draws and the calibration sample's randomness. It isn't an exact fraction in every short deployment window, and it isn't a guarantee conditional on one fixed realized calibration set.

Find the traffic the average hides

The 75% result is one population summary. Under the exchangeability condition above, standard split conformal provides marginal coverage over the overall population.[1]Reference 1A Gentle Introduction to Conformal Prediction and Distribution-Free Uncertainty Quantificationhttps://arxiv.org/abs/2107.07511[2]Reference 2Conformal Prediction Beyond Exchangeabilityhttps://arxiv.org/abs/2202.13415

That guarantee isn't conditional coverage for each subgroup or individual feature value. If short prompts receive 96% coverage while long prompts receive 54%, an aggregate passing threshold can hide unsafe long-request behavior.

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.

The failure patterns below turn those distinctions into operational diagnoses:

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 promptsRecalibrate on representative recent traffic
Tenant-specific error differsOverall coverage passes while one tenant failsMeasure per-tenant or group-conditional coverage
Noise grows with request sizeConstant intervals are too narrow for large requestsUse a better nonconformity score or group-aware method
Calibration sample is tinyDesired rank exceeds available observationsGather more data or acknowledge an unbounded set

Turn coverage into an operating check

A coverage number without interval width is incomplete. An interval spanning every plausible latency never misses, but it can't guide a 50-millisecond deadline.

Start the audit with one row per held-out request: frozen prediction, observed latency, absolute residual, sorted residual rank, and approved calibration-slice membership.

For the nine worked residuals, verify corrected rank eight, radius 8 milliseconds, and interval [32,48] for a 40-millisecond prediction. Then check overall coverage, long-request coverage, interval width, training/calibration separation, and the unsupported 95% target that would require a nonexistent tenth residual. Keep the deployment gate closed when exchangeability, subgroup safety, or a finite requested quantile isn't established.

For one final run, build a coverage scorecard from held-out rows. Verify each interval, calculate overall and long-request coverage, record interval width, and note whether exchangeability and the requested finite rank hold. Keep that scorecard with the deployment gate so a later traffic shift has evidence to trigger recalibration.

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.

Split conformal calibrates a frozen model on examples separate from the training set used to fit it.

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 milliseconds and the calibrated residual radius is 8 milliseconds. Which interval follows?

Correct answer: [32, 48], adding and subtracting the calibrated error radius.

For absolute-residual split conformal, the prediction interval is prediction minus and plus the calibrated radius.

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 residuals exist, so a finite observed threshold is unavailable at that level.

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

Calibration turns held-out errors into defensible uncertainty; the next lesson examines structure in unlabeled examples before fitting explicit probabilistic population models.

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

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.