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 & EvaluationProbabilistic Generative Models
๐Ÿ›๏ธMediumModel Architecture

Probabilistic Generative Models

Fit a Gaussian mixture from scratch, calculate soft component responsibilities, trace expectation-maximization, and diagnose collapsed or misleading latent groups.

8 min read
Learning path
Step 40 of 192 in the full curriculum
Clustering and PCACore Retrieval Algorithms

Personalize this lesson

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

A latency dashboard reports a mean of 60 milliseconds. Half its requests finish near 30 milliseconds, while the other half wait near 90. No request in that sample finishes near the mean, and a hard cluster assignment would force an in-between request into one story.

Clustering, PCA, and Representation Learning grouped examples by geometric similarity. That helps assign points, but it doesn't describe how likely each group is. A Gaussian mixture model asks how hidden populations could generate the observed values and keeps uncertain membership visible.[1]Reference 1Pattern Recognition and Machine Learning.https://www.microsoft.com/en-us/research/publication/pattern-recognition-machine-learning/[2]Reference 2Maximum Likelihood from Incomplete Data via the EM Algorithmhttps://doi.org/10.1111/j.2517-6161.1977.tb01600.x

Six observed request latencies group around 30 and 90 milliseconds; weighted component responsibilities recover two means instead of the misleading pooled mean of 60 milliseconds.
Observed requests are the only measurements. Fast and slow component labels are hidden assignments inferred from weighted likelihood, not independently observed causes.

Describe a population with hidden components

Start with six observed request latencies: [28, 30, 32, 86, 90, 94]. Their single mean is 60 milliseconds. Before naming a model, ask whether that average is a useful description of any request in the sample.

RequestLatencyPlausible hidden population
A28 msMostly fast
B30 msMostly fast
C32 msMostly fast
D86 msMostly slow
E90 msMostly slow
F94 msMostly slow

A generative model asks how an observed latency might have been produced. One possible story first chooses a component, then samples from that component's probability distribution.

That component is a latent variable: the request log records 28 or 90 milliseconds, not the hidden label that supposedly generated it. The diagram makes the two-stage story explicit:

Diagram showing Choose hidden component, Fast Gaussian near 30 ms, Slow Gaussian near 90 ms, and Observe one request latency.
Choose hidden component, Fast Gaussian near 30 ms, Slow Gaussian near 90 ms, and Observe one request latency.

The two components are useful statistical descriptions, not proof that a specific queue, GPU, or tenant caused a latency. Causal attribution requires measurements such as queue state or device traces outside this mixture.

Compute soft responsibilities

The six values suggest two groups, but the model still needs to decide how much each group explains each request. For KKK components, the mixture density is:

p(x)=โˆ‘k=1Kฯ€kโ€‰N(xโˆฃฮผk,ฯƒk2)p(x)=\sum_{k=1}^{K}\pi_k\,\mathcal N(x\mid\mu_k,\sigma_k^2)p(x)=k=1โˆ‘Kโ€‹ฯ€kโ€‹N(xโˆฃฮผkโ€‹,ฯƒk2โ€‹)

Here ฯ€k\pi_kฯ€kโ€‹ is a component weight, ฮผk\mu_kฮผkโ€‹ its mean, and ฯƒk2\sigma_k^2ฯƒk2โ€‹ its variance. The weights sum to one. Once those parameters are fixed, an observation's responsibility for component kkk is:

rik=ฯ€kN(xiโˆฃฮผk,ฯƒk2)โˆ‘jฯ€jN(xiโˆฃฮผj,ฯƒj2)r_{ik}=\frac{\pi_k\mathcal N(x_i\mid\mu_k,\sigma_k^2)}{\sum_j\pi_j\mathcal N(x_i\mid\mu_j,\sigma_j^2)}rikโ€‹=โˆ‘jโ€‹ฯ€jโ€‹N(xiโ€‹โˆฃฮผjโ€‹,ฯƒj2โ€‹)ฯ€kโ€‹N(xiโ€‹โˆฃฮผkโ€‹,ฯƒk2โ€‹)โ€‹

Responsibilities sum to one across components. A request near both component centers can receive fractional membership instead of a forced hard label.

Use equal weights, centers at 30 and 90 milliseconds, and a common standard deviation of 20. For a 50-millisecond request, which component should receive more responsibility? The next cell computes the normalized values.

calculate-mixture-responsibilities.py
1from math import exp, pi, sqrt 2 3def gaussian_density(value: float, mean: float, deviation: float) -> float: 4 exponent = -((value - mean) ** 2) / (2 * deviation**2) 5 return exp(exponent) / (sqrt(2 * pi) * deviation) 6 7latency = 50.0 8weighted_fast = 0.5 * gaussian_density(latency, mean=30.0, deviation=20.0) 9weighted_slow = 0.5 * gaussian_density(latency, mean=90.0, deviation=20.0) 10total = weighted_fast + weighted_slow 11 12fast = weighted_fast / total 13slow = weighted_slow / total 14assert abs(fast + slow - 1.0) < 1e-12 15print(f"fast responsibility: {fast:.3f}") 16print(f"slow responsibility: {slow:.3f}")
Output
1fast responsibility: 0.818 2slow responsibility: 0.182

The 50-millisecond request is closer to the fast center, so the fast component gets responsibility 0.818 and the slow component gets 0.182. Those values are conditional on the assumed weights, means, and variances.

They don't certify that a real fast queue handled the request. The model only saw latency, not queue identity.

A 50-millisecond request receives fast-component responsibility 0.818. What happens to the remaining 0.182, and does the larger number identify the physical queue that handled the request?

Answer

The remaining 0.182 is assigned to the slow component, so both responsibilities sum to one. The 0.818 value is a probability inside the assumed mixture model; no physical queue identity was observed, so it doesn't establish infrastructure ownership or causation.

Fit the mixture with expectation-maximization

Responsibilities need parameters, but the parameters are exactly what we want to learn. Expectation-maximization (EM) handles that loop by alternating two operations:[2]Reference 2Maximum Likelihood from Incomplete Data via the EM Algorithmhttps://doi.org/10.1111/j.2517-6161.1977.tb01600.x

  1. In the E-step, estimate each observation's fractional component membership using the current parameters.
  2. In the M-step, recompute component weights, means, and variances from those fractional memberships.

The M-step's weighted mean update is:

ฮผknew=โˆ‘irikxiโˆ‘irik\mu_k^{\text{new}}=\frac{\sum_i r_{ik}x_i}{\sum_i r_{ik}}ฮผknewโ€‹=โˆ‘iโ€‹rikโ€‹โˆ‘iโ€‹rikโ€‹xiโ€‹โ€‹

With exact E-steps and M-steps, each completed EM iteration doesn't decrease the observed-data log likelihood:

logโกp(x1,โ€ฆ,xn)=โˆ‘i=1nlogโก(โˆ‘k=1Kฯ€kN(xiโˆฃฮผk,ฯƒk2))\log p(x_1,\ldots,x_n)=\sum_{i=1}^{n}\log\left(\sum_{k=1}^{K}\pi_k\mathcal N(x_i\mid\mu_k,\sigma_k^2)\right)logp(x1โ€‹,โ€ฆ,xnโ€‹)=i=1โˆ‘nโ€‹log(k=1โˆ‘Kโ€‹ฯ€kโ€‹N(xiโ€‹โˆฃฮผkโ€‹,ฯƒk2โ€‹))

The outer sum runs over observed requests. The inner sum adds the possible hidden component assignments for each request. A higher value means the observed latencies fit the stated model better; it doesn't guarantee a global optimum or identify a real infrastructure cause.

The next cell starts with provisional means and runs eight one-dimensional EM iterations. It adds a variance floor, checks the observed-data log likelihood after each update, and prints the fitted means. Before running it, predict whether the two groups will settle near 30 and 90 milliseconds.

fit-two-component-mixture.py
1from math import exp, log, pi, sqrt 2 3values = [28.0, 30.0, 32.0, 86.0, 90.0, 94.0] 4means = [25.0, 95.0] 5variances = [100.0, 100.0] 6weights = [0.5, 0.5] 7 8def observed_log_likelihood() -> float: 9 total = 0.0 10 for value in values: 11 density = sum( 12 weight * exp(-((value - mean) ** 2) / (2 * variance)) 13 / sqrt(2 * pi * variance) 14 for weight, mean, variance in zip(weights, means, variances) 15 ) 16 total += log(density) 17 return total 18 19log_likelihoods = [observed_log_likelihood()] 20 21for _ in range(8): 22 responsibilities = [] 23 for value in values: 24 scores = [ 25 weight * exp(-((value - mean) ** 2) / (2 * variance)) 26 / sqrt(2 * pi * variance) 27 for weight, mean, variance in zip(weights, means, variances) 28 ] 29 responsibilities.append([score / sum(scores) for score in scores]) 30 31 for component in range(2): 32 count = sum(row[component] for row in responsibilities) 33 mean = sum(row[component] * value for row, value in zip(responsibilities, values)) / count 34 variance = sum( 35 row[component] * (value - mean) ** 2 36 for row, value in zip(responsibilities, values) 37 ) / count 38 weights[component] = count / len(values) 39 means[component] = mean 40 variances[component] = max(variance, 1.0) 41 42 log_likelihoods.append(observed_log_likelihood()) 43 44assert all( 45 current + 1e-12 >= previous 46 for previous, current in zip(log_likelihoods, log_likelihoods[1:]) 47) 48print(f"log likelihood: {log_likelihoods[0]:.3f} -> {log_likelihoods[-1]:.3f}") 49for index, (weight, mean) in enumerate(zip(weights, means), start=1): 50 print(f"component {index}: weight={weight:.3f}, mean={mean:.1f} ms")
Output
1log likelihood: -24.438 -> -17.694 2component 1: weight=0.500, mean=30.0 ms 3component 2: weight=0.500, mean=90.0 ms

The floor prevents a component from collapsing onto one observation with nearly zero variance. Because it changes the optimization problem, the code measures the constrained fit instead of assuming that an unconstrained proof transfers automatically. Larger mixtures should compute densities in log space with a log-sum-exp operation to avoid numerical underflow.

The fitted model's observed-data log likelihood rises from -24.438 to -17.694. What does that improvement establish, and which conclusions remain unsupported?

Answer

The observed latencies receive higher likelihood under the updated two-component model, and the recorded EM iterations didn't decrease that objective. The increase doesn't prove global optimality, establish that two is the correct number of components, or identify either component with a real serving-system cause.

Why is a responsibility of 0.82 different from observing that a request definitely came from the fast queue?

Answer

The responsibility is a conditional probability inside the assumed mixture model. The true queue identity wasn't observed, and the mixture components may not correspond to actual infrastructure causes.

Compare hard clusters with probabilistic models

The responsibility calculation answers a different question from a hard cluster label. Put the two views side by side:

PropertyK-meansGaussian mixture
AssignmentExactly one cluster per observationFractional responsibility across components
Cluster shapeDistance to a centerLearned mean and covariance structure
UncertaintyNot directly representedModel-conditional membership probability
Common failureSensitive to initialization and feature scaleLocal optima, collapsing covariance, unsupported component stories

Maximum likelihood compares how compatible the observations are with candidate parameters. EM can improve the observed-data likelihood, but a better likelihood alone doesn't prove that the number of components is correct or that the labels describe real causes.[1]Reference 1Pattern Recognition and Machine Learning.https://www.microsoft.com/en-us/research/publication/pattern-recognition-machine-learning/

That limitation changes how you validate a fit. Run multiple initializations, inspect held-out likelihood, check component sizes, and compare the generated distribution with actual traffic. A component containing one request with near-zero variance is a collapse warning, not a new scientific discovery.

Practice receipt: For this six-point fixture, record each component's weight, fitted mean, variance, effective responsibility total, and observed-data log likelihood after every EM iteration. The expected receipt has weights of 0.500, means near 30 and 90 milliseconds, responsibilities summing to one for every request, and likelihood increasing from -24.438 to -17.694.

Then try several starting means. Flag a collapsed variance, a tiny component, or a lower held-out likelihood instead of hiding the run that produced it. Draw samples from the fitted mixture and compare their latency shape with held-out traffic. That posterior predictive check asks whether the model can reproduce both modes, not only whether it scored the six training values well.

Finally, keep the causal boundary visible: a statistical component doesn't name a real queue until separate infrastructure evidence confirms it.

Create a mixture-fit scorecard for each initialization. Record weights, means, variances, responsibilities, held-out likelihood, and posterior-predictive checks; compare the scorecards and flag collapsed components or a poor traffic match. Keep the selected scorecard with the model handoff, including the evidence that still can't identify an infrastructure cause.

Complete the lesson

Mastery Check

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

1.What is hidden in a Gaussian mixture fitted to request latency observations?

Correct answer: The component assignment associated with each observed request.

The latency is observed, while the generating component is a latent variable inferred from the model.

2.What does a mixture responsibility of 0.82 represent?

Correct answer: The model-conditional probability assigned to one latent component.

Responsibilities are posterior component probabilities under the fitted mixture assumptions, not verified physical causes.

3.Which operation belongs to the E-step of expectation-maximization?

Correct answer: Compute fractional component assignments using the current model parameters.

The expectation step computes responsibilities for unobserved component assignments given the current mixture parameters.

4.How is a component mean updated during the Gaussian-mixture M-step?

Correct answer: Average observed values using their fractional responsibilities as weights.

The M-step sets each mean to the responsibility-weighted average of observed values.

5.Why is a minimum variance floor useful when fitting a Gaussian mixture?

Correct answer: It prevents a component from collapsing around one observation with near-zero variance.

A variance floor limits degenerate components that can otherwise make individual points appear implausibly certain.

6.How does soft mixture assignment differ from ordinary k-means assignment?

Correct answer: Mixtures distribute membership across components instead of forcing one hard label.

A Gaussian mixture expresses fractional component responsibilities, whereas ordinary k-means assigns each point to one cluster.

7.Why should a researcher run expectation-maximization from multiple initial conditions?

Correct answer: Different starts can converge to different local likelihood optima.

The mixture likelihood is nonconvex, so expectation-maximization can settle in different local solutions depending on initialization.

8.What can a higher fitted mixture likelihood establish on its own?

Correct answer: That the observations are better explained under the stated fitted model.

Likelihood compares data compatibility under model assumptions; it doesn't establish causal identity, future stability, or a uniquely correct component count.

8 questions remaining.

Next Step
Continue to Core Retrieval Algorithms

Soft assignments and likelihood expose hidden structure in unlabeled observations; retrieval now applies distance and ranking decisions to finding useful examples efficiently.

PreviousClustering and PCA
Share this article
XFacebookLinkedInBlueskyRedditHacker NewsEmail
References

Pattern Recognition and Machine Learning.

Bishop, C. M. ยท 2006

https://www.microsoft.com/en-us/research/publication/pattern-recognition-machine-learning/

Maximum Likelihood from Incomplete Data via the EM Algorithm

Dempster, A. P., Laird, N. M., & Rubin, D. B. ยท 1977 ยท Journal of the Royal Statistical Society: Series B

https://doi.org/10.1111/j.2517-6161.1977.tb01600.x

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.