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 & EvaluationCausal Inference and Counterfactuals
๐Ÿ“ŠMediumEvaluation & Benchmarks

Causal Inference and Counterfactuals

Separate correlation from intervention, diagnose Simpson's reversal, estimate adjusted treatment effects, and inspect overlap before trusting observational AI evaluations.

7 min read
Learning path
Step 44 of 192 in the full curriculum
Experiment Design and A/B TestingPyTorch Training Loops

Personalize this lesson

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

An AI assistant resolves 54% of its tickets, while the old workflow resolves 76%. A release report calls the assistant harmful. Then the tickets are split by risk: the assistant is ten percentage points better inside both easy and difficult groups. Which result should drive the rollout decision?

Experiment Design and A/B Testing Foundations introduced fair comparisons. Causal inference asks whether a change caused an outcome, then makes the assignment assumptions behind that conclusion explicit.[1]Reference 1Causal Inference in Statistics: A Primerhttps://bayes.cs.ucla.edu/PRIMER/ Start with the counts, not the label on the report.

Observed assistant success is 90% versus 80% for easy tickets and 50% versus 40% for difficult tickets, but unequal case assignment reverses the naive aggregate to 54% assistant versus 76% control.
Observed assistant success is higher within both risk groups. Its aggregate looks worse because 90 of its 100 assigned tickets are difficult, while only 10 control tickets are difficult.

Watch the aggregate reverse the group results

Keep risk measured before routing. Within each group, the assistant's observed success rate is ten percentage points higher. Before looking at the totals, predict what the aggregate should say if the groups had the same mix.

Ticket riskAssistant successControl successWithin-group effect
Low9/10 = 90%72/90 = 80%+10 percentage points
High45/90 = 50%4/10 = 40%+10 percentage points
Naive aggregate54/100 = 54%76/100 = 76%-22 percentage points

The totals compare different populations. The assistant receives 90 difficult tickets; control receives 90 easy tickets. That unequal mix flips the aggregate direction.

This reversal is Simpson's paradox: group composition changes the direction of the aggregated association. The observational counts alone still don't establish a causal improvement.

The next cell computes both within-group effects and the reversed aggregate from the original counts.

inspect-confounded-ticket-outcomes.py
1groups = { 2 "low": {"assistant": (9, 10), "control": (72, 90)}, 3 "high": {"assistant": (45, 90), "control": (4, 10)}, 4} 5 6for risk, counts in groups.items(): 7 assistant_success, assistant_total = counts["assistant"] 8 control_success, control_total = counts["control"] 9 difference = assistant_success / assistant_total - control_success / control_total 10 print(f"{risk:>4} risk effect: {difference:+.0%}") 11 12assistant_rate = (9 + 45) / (10 + 90) 13control_rate = (72 + 4) / (90 + 10) 14print(f"naive aggregate effect: {assistant_rate - control_rate:+.0%}")
Output
1low risk effect: +10% 2high risk effect: +10% 3naive aggregate effect: -22%

The reversal disappears once both workflows are compared against the same risk distribution. That repairs the visible mix, but it still leaves a deeper question: for one assistant-handled ticket, what would control have done?

Separate observed outcomes from missing alternatives

Take one difficult ticket that received the assistant. We observe its treated outcome, but we don't observe what the same ticket would have done under control. Those two branches are the potential outcomes Y(1)Y(1)Y(1) and Y(0)Y(0)Y(0); their difference Y(1)โˆ’Y(0)Y(1)-Y(0)Y(1)โˆ’Y(0) is that ticket's individual treatment effect.

Only one branch is observed for each ticket. If the assistant handles it, the control outcome is a counterfactual. A logging system can't recover that missing outcome by looking at another, potentially different, ticket.

The average treatment effect averages those individual differences over a named target population:

ATEโก=E[Y(1)โˆ’Y(0)]\operatorname{ATE}=E[Y(1)-Y(0)]ATE=E[Y(1)โˆ’Y(0)]

To estimate it, name the target population, treatment, outcome window, assignment mechanism, and assumptions. "Assistant tickets resolved faster" isn't enough without those details.

Why can't the control group's 76% aggregate success rate serve as the missing outcome for every assistant ticket?

Answer

The control group contains a much larger share of easy tickets. Its aggregate outcome describes a different population, so it is not a valid counterfactual for the harder assistant-assigned cases.

Draw the assignment mechanism

The table shows an imbalanced mix, but not why routing produced it. Suppose the system sends difficult tickets to the assistant more often. Risk exists before routing and influences both assignment and resolution, which makes it a confounder.

The following directed acyclic graph (DAG) turns that routing story into an explicit causal graph.

Diagram showing Ticket risk before assignment, Assistant assignment, and Resolution outcome.
Ticket risk before assignment, Assistant assignment, and Resolution outcome.

The path assignment โ† risk โ†’ resolution is a backdoor path: risk connects assignment to resolution before the assistant acts. Backdoor adjustment for observed pre-treatment risk can block that path if risk captures the relevant common causes.[1]Reference 1Causal Inference in Statistics: A Primerhttps://bayes.cs.ucla.edu/PRIMER/

Don't adjust for a variable created after the assistant acts, such as the assistant's own generated escalation note. It can lie on the causal path or introduce a fresh selection bias, so it can't replace pre-treatment risk.

Ticket risk is recorded before routing, while an escalation note is created by the assistant after routing. Which variable can support the stated backdoor adjustment, and why can't the other replace it?

Answer

Pre-treatment risk can block a common-cause path when it captures the relevant assignment and outcome differences. The assistant-generated escalation note occurs after treatment, so conditioning on it can remove part of the effect being estimated or introduce a new selection bias.

Standardize both arms to one population

Choose a target population with 70% low-risk and 30% high-risk tickets. The low-risk contribution is 0.7ร—0.10=0.070.7 \times 0.10 = 0.070.7ร—0.10=0.07; the high-risk contribution is 0.3ร—0.10=0.030.3 \times 0.10 = 0.030.3ร—0.10=0.03. Add them to get the target-population effect:

ATEโก=0.7(0.90โˆ’0.80)+0.3(0.50โˆ’0.40)=0.10\operatorname{ATE}=0.7(0.90-0.80)+0.3(0.50-0.40)=0.10ATE=0.7(0.90โˆ’0.80)+0.3(0.50โˆ’0.40)=0.10

Both groups improve by the same ten percentage points, so this weighted result is also ten percentage points. If subgroup effects differed, the target-population weights would change the answer.

The next cell continues the earlier session and applies one shared population distribution to both arms.

standardize-ticket-treatment-effects.py
1target_weights = {"low": 0.7, "high": 0.3} 2adjusted_effect = 0.0 3 4for risk, population_weight in target_weights.items(): 5 assistant_success, assistant_total = groups[risk]["assistant"] 6 control_success, control_total = groups[risk]["control"] 7 effect = assistant_success / assistant_total - control_success / control_total 8 adjusted_effect += population_weight * effect 9 10print(f"risk-adjusted effect: {adjusted_effect:+.0%}") 11assert abs(adjusted_effect - 0.10) < 1e-12
Output
1risk-adjusted effect: +10%

The arithmetic answers a target-population comparison. It identifies a causal effect only under explicit assumptions:

Identification assumptionMeaning in the ticket example
Conditional exchangeabilityWithin measured risk groups, no unrecorded common cause still changes both routing and resolution
Positivity or overlapBoth assistant and control assignments occur for every target-population risk group
ConsistencyThe recorded outcome matches the specific treatment and outcome window being compared
No interferenceOne ticket's treatment doesn't change another ticket's outcome
Target-population relevanceThe 70% and 30% weights describe the population named in the claim

The smallest strata contain only ten tickets, so their observed rates are statistically uncertain. Standardizing both arms against a shared risk mix repairs one documented assignment imbalance; it doesn't prove that the adjusted ten-point estimate is exact or eliminate unmeasured confounding.

Both observed risk groups show a ten-point advantage, but a hidden customer-priority field affects both assistant routing and resolution. Does standardizing only by recorded risk identify the causal effect?

Answer

Not necessarily. The arithmetic still returns a risk-adjusted ten-point association, but an unmeasured common cause violates conditional exchangeability. Without measuring and appropriately adjusting for customer priority, or changing the assignment design, that association isn't justified as an identified causal effect.

Refuse effects when the alternative has no support

A propensity score estimates the probability that a ticket receives the assistant given pre-treatment features. Now test the assignment boundary: if every high-risk ticket always receives the assistant, there are no high-risk control outcomes in the log. No amount of weighting can invent that missing comparison.

ConditionWhat the evidence permits
Both actions occur in every relevant risk groupCompare observed within-group outcomes under stated assumptions
One action never occurs for a groupThe missing group's effect isn't identified from those logs alone
Risk is measured after assignmentThe adjustment can block or distort the treatment effect
Important pre-treatment causes aren't recordedMeasured adjustment can still leave confounding
Treatment is randomizedAssignment is separated from pre-treatment risk in expectation

Randomization makes treatment assignment independent of pre-treatment risk in expectation. It doesn't remove missing outcomes, attrition, interference, or measurement errors. A randomized design still needs a clear estimand and honest analysis.

Use a treatment-comparison worksheet to replay the decision. Preserve the low-risk and high-risk counts, both raw aggregate rates, and the declared 70%/30% target weights. Calculate the misleading -22 percentage-point aggregate and the +10 percentage-point standardized association.

Then inspect each risk group: record treated and control sample sizes, name the pre-treatment adjustment variables, and check overlap. Add rows for unmeasured confounding, shared outcome windows, interference, and the uncertainty from ten-ticket strata. If an identification check fails, label the result an observational association instead of a causal effect.

Complete the lesson

Mastery Check

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

1.Why can the assistant show higher observed success in both risk groups while appearing worse in the aggregate?

Correct answer: The assistant and control groups contain different proportions of difficult tickets.

Risk affects both assignment and outcome, so unequal group composition can reverse the direction of the unadjusted aggregate.

2.What does Y(0) mean for a ticket that actually received assistant treatment?

Correct answer: The unobserved outcome that ticket would have had without assistant treatment.

Y(0) is the untreated potential outcome, which is counterfactual and unobserved for a treated ticket.

3.Which property makes pre-treatment ticket risk a confounder in the worked example?

Correct answer: It influences both assistant assignment and the eventual resolution outcome.

A confounder is a pre-treatment common cause of treatment assignment and outcome.

4.Both risk groups improve by ten percentage points. What adjusted effect follows under 70% low-risk and 30% high-risk target weights?

Correct answer: Plus ten percentage points from weighting both within-group improvements.

The standardized estimate is 0.70.10+0.30.10=0.10 for the declared target population.

5.Why is an assistant-generated escalation note usually inappropriate as a confounder adjustment variable?

Correct answer: It is produced after treatment and can lie on the assistant's causal pathway.

A post-treatment variable can block part of the treatment effect or introduce selection bias instead of removing pre-treatment confounding.

6.What fails if every high-risk ticket receives the assistant and no high-risk control outcome exists?

Correct answer: The overlap condition fails, so the missing high-risk alternative isn't identified.

Without examples from both actions in a relevant stratum, observational logs cannot identify that stratum's alternative outcome without stronger assumptions.

7.What does a routing propensity score estimate?

Correct answer: The probability of assistant assignment given observed pre-treatment features.

A propensity score models treatment assignment probability conditional on observed pre-treatment covariates.

8.What does randomized assignment improve in a treatment comparison?

Correct answer: It separates assignment from pre-treatment characteristics in expectation.

Randomization improves comparability of treatment arms but does not remove all other threats to a causal estimate.

8 questions remaining.

Next Step
Continue to PyTorch Training Loops

A causal comparison makes interventions and their evidence explicit; the next lesson applies the same discipline to controlled model updates, gradients, and reproducible training behavior.

PreviousExperiment Design and A/B Testing
Share this article
XFacebookLinkedInBlueskyRedditHacker NewsEmail
References

Causal Inference in Statistics: A Primer

Pearl, J., Glymour, M., & Jewell, N. P. ยท 2016

https://bayes.cs.ucla.edu/PRIMER/

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.