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
LearnMath & StatisticsBayesian Inference from Evidence
๐Ÿ“ŠEasyEvaluation & Benchmarks

Bayesian Inference from Evidence

Update a coding agent's unknown success rate with beta-binomial evidence, compare priors, measure uncertainty, and expose sampling failures.

8 min read
Learning path
Step 15 of 192 in the full curriculum
Probability for Machine LearningStatistics and Uncertainty

Personalize this lesson

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

A coding agent passes eight of its first ten held-out tasks. Should its next deployment receive more traffic? The observed rate is 0.800, but ten tasks can still mislead, and yesterday's agents may provide useful evidence you shouldn't quietly discard.

Probability for Machine Learning introduced base rates and conditioning. Now ask a narrower question: before those ten tasks, which pass rates were plausible? Bayesian inference makes that starting belief explicit, updates it with outcomes, and carries uncertainty into the next deployment decision.[1]Reference 1Machine Learning: A Probabilistic Perspective.https://probml.github.io/pml-book/book0.html[2]Reference 2Gittins Index for Bayesian Bandits: Beta-Binomial Conjugacyhttps://www.stat.berkeley.edu/~bartlett/courses/2014fall-cs294stat260/lectures/gittins-notes.pdf

We'll keep one running ledger: Beta(2, 2) before the run, then eight passes and two failures. The count flow makes those two sources of information visible before we name the equations.

A Beta(2,2) prior combines with eight observed passes and two failures to form Beta(10,4), changing the predicted next-task pass probability from the observed 0.800 to the posterior mean 0.714.
Prior parameter weights and ten actual observed outcomes flow into one posterior. The updated success probability is 10 divided by 14, not the raw eight divided by ten.

Name the uncertainty before seeing the new run

Let ppp mean the probability that this agent passes a future task drawn from the same task population. The last ten outcomes don't reveal ppp exactly. They provide evidence about plausible values.

QuantityQuestion it answersWorked value
PriorWhich rates were plausible before this eval?Beta(2, 2)
ObservationsWhat actually happened?8 passes, 2 failures
LikelihoodHow compatible are those outcomes with each rate?proportional to p8(1โˆ’p)2p^8(1-p)^2p8(1โˆ’p)2
PosteriorWhich rates remain plausible after the update?Beta(10, 4)

Read the table as a sequence. The prior proposes candidate rates, the likelihood scores how well each rate explains the eight passes and two failures, and the posterior combines both sources and normalizes them. The likelihood by itself isn't yet a probability distribution over ppp.

The prior Beta(2, 2) is a probability distribution over possible success rates, symmetric around 0.5. For intuition, its two parameters carry success-shaped and failure-shaped weight into the update. They're modeling assumptions, not four real benchmark rows. Relative to a uniform Beta(1, 1) starting point, Beta(2, 2) could instead arise from one observed success and one observed failure, so disclose the baseline before treating parameters as historical evidence.

Diagram showing Prior Beta(2,2), Add 8 passes and 2 failures, Ten held-out tasks, and Posterior Beta(10,4).
Prior Beta(2,2), Add 8 passes and 2 failures, Ten held-out tasks, and Posterior Beta(10,4).

The update transfers only when the old and new tasks share a success-rate meaning. If historical agents performed differently, came from a different benchmark, or used another tool policy, treating their records as evidence about this agent will distort the update.

Work through the update by hand

Start with the ledger rather than the symbol: two prior success weights plus eight observed passes gives 10, and two prior failure weights plus two failures gives 4. For a binary outcome, this neat addition is the beta-binomial update. A beta prior and Bernoulli observations (independent pass-or-fail draws under the assumed model) stay in the same beta family, which is why beta is a conjugate prior:[2]Reference 2Gittins Index for Bayesian Bandits: Beta-Binomial Conjugacyhttps://www.stat.berkeley.edu/~bartlett/courses/2014fall-cs294stat260/lectures/gittins-notes.pdf

pโˆฃDโˆผBetaโก(ฮฑ+s,โ€…โ€Šฮฒ+f)p \mid D \sim \operatorname{Beta}(\alpha+s,\;\beta+f)pโˆฃDโˆผBeta(ฮฑ+s,ฮฒ+f)

Here ฮฑ\alphaฮฑ and ฮฒ\betaฮฒ are the prior parameters, sss counts observed passes, and fff counts observed failures. Substitute the actual numbers:

Betaโก(2+8,โ€…โ€Š2+2)=Betaโก(10,4)\operatorname{Beta}(2+8,\;2+2)=\operatorname{Beta}(10,4)Beta(2+8,2+2)=Beta(10,4)

The posterior mean is:

E[pโˆฃD]=ฮฑ+sฮฑ+ฮฒ+s+f=1014โ‰ˆ0.714E[p\mid D]=\frac{\alpha+s}{\alpha+\beta+s+f}=\frac{10}{14}\approx0.714E[pโˆฃD]=ฮฑ+ฮฒ+s+fฮฑ+sโ€‹=1410โ€‹โ‰ˆ0.714

The sample-only rate is 8/10=0.88/10=0.88/10=0.8. The prior-only mean is 2/4=0.52/4=0.52/4=0.5. The updated mean lies between them because the prior supplies modeling weight while the observations supply new evidence under the assumed model.

The next cell repeats that arithmetic and checks the parameter totals before printing the updated rate.

update-agent-success-posterior.py
1prior_success = 2 2prior_failure = 2 3observed_pass = 8 4observed_fail = 2 5 6posterior_success = prior_success + observed_pass 7posterior_failure = prior_failure + observed_fail 8posterior_mean = posterior_success / (posterior_success + posterior_failure) 9 10assert (posterior_success, posterior_failure) == (10, 4) 11print(f"observed rate: {observed_pass / (observed_pass + observed_fail):.3f}") 12print(f"posterior: Beta({posterior_success}, {posterior_failure})") 13print(f"next-task pass probability: {posterior_mean:.3f}")
Output
1observed rate: 0.800 2posterior: Beta(10, 4) 3next-task pass probability: 0.714

Predict one future task from the posterior

If the next task is comparable, the posterior predictive probability gives us a forecast before that task runs. Under this beta-binomial model, one new task passes with probability equal to the posterior mean: 10/14, or about 0.714. That's a model-based prediction, not a guarantee that the next task passes.

Why does the posterior mean equal 10/14 instead of the observed pass rate 8/10?

Answer

The Beta(2,2) prior contributes two success-shaped and two failure-shaped counts. Combining them with eight passes and two failures yields Beta(10,4), whose mean is 10 divided by 14.

Check whether the prior dominates the evidence

Two engineers can see the same ten outcomes and reach different posterior means because they chose different priors. Hold the observations fixed and vary only the historical assumption.

The next cell reuses the pass and failure counts and compares a weak Beta(1, 1) prior, a moderate Beta(2, 2) prior, and a strong Beta(20, 20) prior. Predict what should happen before reading the numbers: the strong prior should stay closer to 0.5.

compare-agent-prior-strengths.py
1for success_count, failure_count in [(1, 1), (2, 2), (20, 20)]: 2 updated_success = success_count + observed_pass 3 updated_total = success_count + failure_count + observed_pass + observed_fail 4 print( 5 f"Beta({success_count:>2}, {failure_count:>2}) -> " 6 f"posterior mean {updated_success / updated_total:.3f}" 7 )
Output
1Beta( 1, 1) -> posterior mean 0.750 2Beta( 2, 2) -> posterior mean 0.714 3Beta(20, 20) -> posterior mean 0.560

Beta(20, 20) gives its starting mean a weight of 40 in this update, so the ten new outcomes barely move it. That can be reasonable when the prior came from substantial, comparable historical evidence.

Relative to a uniform Beta(1, 1) baseline, reaching Beta(20, 20) would require 19 historical passes and 19 historical failures, not 40 observed tasks. The parameter weight is bookkeeping; it isn't a provenance record. Keep those two facts separate.

PriorPrior parameter weightPosterior meanInterpretation
Beta(1, 1)20.750Weak symmetric starting assumption
Beta(2, 2)40.714Mild pull toward 0.5
Beta(20, 20)400.560Strong historical assumption dominates ten tasks

Report several defensible priors when the sample is small. If the deployment decision flips between them, collect more representative evidence instead of quietly choosing the prior that makes the preferred outcome win.

An engineer claims Beta(20,20) proves that 40 comparable historical tasks were observed. What information is missing?

Answer

The prior has total parameter weight 40, but that weight isn't automatically 40 observed tasks. Relative to a uniform Beta(1,1) baseline, the same prior could result from 19 historical passes and 19 historical failures. The earlier baseline and the historical evidence's provenance must both be disclosed.

Keep posterior uncertainty separate from the average

A mean of 0.714 doesn't say every plausible success rate is 0.714. Beta(10, 4) still spreads probability across a range of rates. For Beta(a,ba,ba,b), the posterior variance is:

Varโก(pโˆฃD)=ab(a+b)2(a+b+1)\operatorname{Var}(p\mid D)=\frac{ab}{(a+b)^2(a+b+1)}Var(pโˆฃD)=(a+b)2(a+b+1)abโ€‹

At Beta(10, 4), this is 40/(196โ‹…15)โ‰ˆ0.013640/(196\cdot15)\approx0.013640/(196โ‹…15)โ‰ˆ0.0136, giving a posterior standard deviation near 0.117. A credible interval would summarize posterior quantiles; its interpretation still depends on the prior and the sampling model.[1]Reference 1Machine Learning: A Probabilistic Perspective.https://probml.github.io/pml-book/book0.html

Does a posterior mean of 0.714 establish that the agent's unknown success probability is exactly 0.714?

Answer

No. The mean summarizes the Beta(10,4) posterior, while its standard deviation near 0.117 shows that other success probabilities remain plausible under the assumed prior, likelihood, and sample.

Test how more evidence changes uncertainty

Hold the Beta(2, 2) prior fixed and increase the evidence: compare the ten-task run with eighty passes and twenty failures. The larger run yields Beta(82, 22), whose mean is about 0.788 and whose posterior standard deviation is about 0.040. More representative data narrows uncertainty and reduces the prior's influence.

The next independent cell computes both summaries from the closed-form beta variance.

compare-posterior-uncertainty.py
1from math import sqrt 2 3for successes, failures in [(10, 4), (82, 22)]: 4 total = successes + failures 5 mean = successes / total 6 variance = successes * failures / (total**2 * (total + 1)) 7 print(f"Beta({successes}, {failures}): mean={mean:.3f}, sd={sqrt(variance):.3f}")
Output
1Beta(10, 4): mean=0.714, sd=0.117 2Beta(82, 22): mean=0.788, sd=0.040

Check calibration on new tasks

Posterior spread and calibration answer different questions. The posterior describes uncertainty about a success rate under a chosen model. Calibration asks whether forecasts line up with later outcomes: among many comparable tasks assigned a pass probability near 0.7, do about 70% pass?

The 0.714 forecast can't establish calibration from the same ten tasks that produced it. To test transfer, update on an initial batch, freeze predictions for later tasks, group similar forecasts into bins, and compare each bin's average prediction with its observed pass fraction. A mismatch points you back to task shift, duplicated retries, policy changes, or a misspecified likelihood. More data can narrow a wrong model's interval without making its forecasts honest.[1]Reference 1Machine Learning: A Probabilistic Perspective.https://probml.github.io/pml-book/book0.html[3]Reference 3On Calibration of Modern Neural Networkshttps://arxiv.org/abs/1706.04599

Break the assumptions before trusting the result

The arithmetic can be correct while the inference is wrong.

FailureVisible symptomRepair
Repeated retries of one taskTen rows claim to represent ten independent tasksGroup retries by underlying task and sample distinct tasks
Easy benchmark slicePosterior looks strong while hard production tasks failStratify by task family and compare deployment traffic
Historical prior from another agentStrong prior hides a real regressionRecord prior provenance and run sensitivity checks
Hidden prompt changesOutcomes combine incompatible policiesPin model, prompt, tools, and task definitions
Selective release reportingOnly a favorable stopping point or chosen agent is disclosedRecord every evaluated agent, stopping rule, and release decision

Bayesian updating handles evidence under a model. Under a correctly specified likelihood and an ignorable stopping rule, stopping early doesn't automatically invalidate a posterior. Selectively reporting the most favorable model or repeatedly changing the release decision still distorts the evidence available to readers. Updating can't turn duplicated, biased, or contaminated rows into representative observations.

A model passes eight out of ten tasks, but all ten rows are retries of the same prompt. Why is Beta(10,4) misleading?

Answer

The update treats the rows as distinct exchangeable task outcomes. Retries of one prompt mainly describe that prompt, so they exaggerate evidence about performance across the deployment population.

Build a release-decision worksheet

Write a compact evaluation worksheet with four columns: observed passes and failures, declared prior and its provenance, posterior parameters, and the resulting next-task probability. Start with the ten reviewed tasks and compare Beta(1,1), Beta(2,2), and Beta(20,20). The expected output is a posterior-mean sequence of 0.750, 0.714, and 0.560, with the historical prior's source stated separately from the number of benchmark rows.

Add a second row group for 80 passes and 20 failures. Verify that Beta(2,2) becomes Beta(82,22), then compare its posterior standard deviation of about 0.040 with 0.117 for the ten-task update. Before releasing, state which policy you apply: posterior mean, a lower credible bound, or the posterior probability that ppp exceeds a launch threshold. Mark the release undecided if defensible priors disagree, retries inflate the sample, or the benchmark population doesn't match deployment traffic. Keep the worksheet as a reviewable artifact rather than publishing a bare pass-rate headline.

What should a release reviewer conclude when one justified prior passes the deployment threshold but another equally defensible prior fails it?

Answer

The available sample doesn't support a prior-robust decision. Record both priors and posterior results, keep the release undecided, and collect additional representative tasks before claiming the threshold is met.

Complete the lesson

Mastery Check

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

1.A Beta(2,2) prior observes eight passes and two failures. Which posterior follows from beta-binomial updating?

Correct answer: Beta(10,4), adding passes and failures to their matching prior counts.

The beta-binomial update adds successes to alpha and failures to beta, so Beta(2+8,2+2) becomes Beta(10,4).

2.What is the posterior predictive probability that the next comparable task passes under Beta(10,4)?

Correct answer: 0.714, because the predictive probability equals 10 divided by 14.

For a Bernoulli outcome with a beta posterior, the next-trial predictive probability is the posterior mean a/(a+b).

3.Why can a Beta(20,20) prior produce a much smaller posterior mean than Beta(1,1) for the same ten observations?

Correct answer: The stronger prior contributes more pseudo-count weight before the new evidence.

Beta(20,20) carries forty prior pseudo-counts, so ten new outcomes move its initial 0.5 mean less than a weak prior.

4.Which statement correctly describes a 90% Bayesian credible interval?

Correct answer: The stated posterior assigns 90% probability to parameter values in the interval.

A credible interval is a statement about posterior probability under the chosen prior, likelihood, and observed evidence.

5.An agent's ten evaluation rows are retries of one prompt. What assumption becomes doubtful?

Correct answer: The rows behave like distinct representative task outcomes for the intended population.

Repeated attempts at one prompt provide correlated prompt-specific evidence, not ten independent draws from the target task population.

6.Which action most directly checks whether a release decision depends on an unjustified prior?

Correct answer: Recompute the decision under several defensible priors and record the changes.

Prior sensitivity analysis reveals whether limited observations support the same decision under reasonable historical assumptions.

7.What changes when the same Beta(2,2) prior receives eighty passes and twenty failures instead of eight passes and two failures?

Correct answer: The larger sample reduces prior influence and narrows posterior uncertainty.

More representative observations dominate fixed prior pseudo-counts and reduce posterior variance, though model and sampling assumptions remain.

8.Why isn't likelihood alone a posterior probability distribution over candidate success rates?

Correct answer: A posterior also requires an explicit prior and normalization by the evidence.

Likelihood scores fixed observations under candidate parameters. Bayes' rule multiplies that likelihood by a prior and normalizes the product.

8 questions remaining.

Next Step
Continue to Statistics and Uncertainty

A posterior turns limited observations into a distribution; the next lesson compares sample estimates, variation, and uncertainty before those numbers drive model decisions.

PreviousProbability for Machine Learning
Share this article
XFacebookLinkedInBlueskyRedditHacker NewsEmail
References

Machine Learning: A Probabilistic Perspective.

Murphy, K. P. ยท 2012

https://probml.github.io/pml-book/book0.html

Gittins Index for Bayesian Bandits: Beta-Binomial Conjugacy

Bartlett, P. ยท 2014 ยท University of California, Berkeley

https://www.stat.berkeley.edu/~bartlett/courses/2014fall-cs294stat260/lectures/gittins-notes.pdf

On Calibration of Modern Neural Networks

Guo, C., Pleiss, G., Sun, Y., & Weinberger, K. Q. ยท 2017

https://arxiv.org/abs/1706.04599

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.