Chapter 9 of 10 · ~26 min read & lab+70 XP
Chapter 9 · Probability

Markov Chains, Random Walks & Monte Carlo Sampling

A wandering cat, Google PageRank, live Gambler's Ruin random walks, Reservoir Sampling, and Importance Sampling for RLHF/PPO

Step 0 · Test Your Gut Before Any Math!

You start with $50 and bet $1 per spin trying to reach $100 (or bust at $0). On a fair 50% coin, your chance is 50%. Now tilt the odds just SLIGHTLY against you to 48% win / 52% lose (like roulette!). Roughly what is your chance of reaching $100?

What You Will Master in This Chapter
  • Picture a Markov Chain as a board game with one-step memory and read its transition matrix P at a glance.
  • Find the long-run steady state πP = π via intuitive 'flow in = flow out' balance.
  • Simulate and solve Gambler's Ruin — seeing why even a tiny 2% casino edge destroys long-run win probability!
  • Understand Reservoir Sampling (streaming data), Importance Sampling (PPO/RLHF), and MCMC without fear.
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
No mysterious math notation — translate everything into English first
How to Say It Aloud
“Transition probability from state i to state j”
Plain-English Meaning
If you are standing on square i today, Pᵢⱼ is the probability you hop to square j tomorrow! Every ROW sums to 1.
Everyday Example
P(Sunny → Rainy) = 0.20; P(Sunny → Sunny) = 0.80 (row sums to 1.00!).
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Imagine your cat wanders between the Couch, the Kitchen, and the Sunny Window every hour. Where it goes next depends ONLY on where it is right now (not where it slept yesterday!). That memoryless hopping game is a Markov Chain — and it powers Google PageRank, Diffusion Models, Reinforcement Learning, and Bayesian MCMC!

1. Markov Chains & Steady State $\pi$ ('Flow In = Flow Out!')

Everyday Story First (Zero Math Yet!)

Picture a city with just two weather states: Sunny and Rainy.

  • If today is Sunny, there's an 80% chance tomorrow is Sunny and 20% chance it flips to Rainy.
  • If today is Rainy, there's a 40% chance it flips back to Sunny and 60% chance it stays Rainy.

Fast-forward 30 days: what fraction of days are Sunny in the long run? Notice Rainy flips to Sunny twice as fast (40%) as Sunny flips to Rainy (20%)! So in equilibrium, Sunny must be twice as common as Rainy: 2/3 Sunny, 1/3 Rainy! Zero matrix algebra needed!

State Transition Graph0.20 →← 0.400.800.60SunnyRainyTransition Matrix P (Rows Sum to 1)SunnyRainySunny0.800.20Σ = 1.0Rainy0.400.60Σ = 1.0Steady State πP = π ⇒ π = [2/3, 1/3]
Figure 9.1 — Markov Chain Duality: every weighted directed transition graph corresponds 1-to-1 with a row-stochastic transition matrix P (every row sums to 1).

From Friendly Graph to Transition Matrix PP

Put those hopping arrows into a table PP where every ROW sums to 1 (because from any state, you MUST land somewhere next step!):

  • After tt steps from starting state p(0)\mathbf{p}^{(0)}: p(t)=p(0)Pt\mathbf{p}^{(t)} = \mathbf{p}^{(0)} P^t.
  • Steady State π\boldsymbol{\pi}: The equilibrium where one more step changes nothing: πP=π\boldsymbol{\pi} P = \boldsymbol{\pi} (Linear Algebra connection: the left eigenvector for λ=1\lambda = 1!).
  • When does EVERY starting point converge to the same π\boldsymbol{\pi}? Whenever the chain is irreducible (no trapped islands) and aperiodic (no rigid back-and-forth cycle like A → B → A → B). That's why Google PageRank adds a 15% random teleport button so the web surfer can never get trapped!
Walk Through With Me · Interactive Worked Example

Solving Customer Retention Steady State by 'Flow In = Flow Out'

Every month, 10% of Active subscribers churn to Churned, while 30% of Churned users reactivate back to Active. What percentage of your total user base will be Active in the long run?

1Write the 'Flow Out = Flow In' balance equation!Step 1 / 3

In equilibrium, the number of users leaving Active each month MUST equal the number returning from Churned: 0.10⋅πActive=0.30⋅πChurned0.10 \cdot \pi_{\text{Active}} = 0.30 \cdot \pi_{\text{Churned}}

Teacher's Note: For any 2-state chain, 'Flow A→B = Flow B→A' solves steady state in 5 seconds!
Try It YourselfWarm-Up

A server is either Healthy (H) or Down (D). Each hour, a Healthy server crashes with prob 0.05, and a Down server gets repaired with prob 0.95. What long-run fraction of time is the server Healthy?

2. Random Walks & Gambler's Ruin (Watch Tiny Edges Compound!)

Everyday Story First (Zero Math Yet!)

Picture walking drunk along a 10-step sidewalk: Step 0 is a ditch (Ruin!), Step 10 is your front door (Jackpot!), and you start right in the middle at Step 5. Every minute you flip a coin: Heads = 1 step toward home, Tails = 1 step toward the ditch. Watch what happens live below when the coin is fair (50%) vs. slightly rigged (45%)!

1D Random Walk with Absorbing Boundaries (Start k = 5, Target N = 10, Ruin = 0)Win (N=10)Ruin (0)k=5Fair game (p = 0.5): P(Win) = k/N = 5/10 = 50% · Expected duration E[T] = k(N − k) = 25 steps
Figure 9.2 — 1D Random Walk & Absorbing Barriers: starting at k between 0 (ruin) and N (target), trajectories bounce randomly until hitting an absorbing boundary.

The Two Iconic Gambler's Ruin Formulas (Start at \k,Goal, Goal $N$)

  • Fair Coin (p=0.50p = 0.50): P(reach N)=kN,E[bets until finish]=k(N−k)P(\text{reach } N) = \frac{k}{N}, \qquad \mathbb{E}[\text{bets until finish}] = k(N - k)
  • Biased Coin (p≠0.50p \ne 0.50, let r=(1−p)/pr = (1-p)/p): P(reach N)=1−rk1−rNP(\text{reach } N) = \frac{1 - r^k}{1 - r^N}

Test both fair and biased games right now in the Live Random Walker below!

Hands-On Mini-Lab · Live Gambler's Ruin Random Walker ($5 → $10 or $0)Win Rate: — (0W / 0L)

You start with $5 and stop at $10 (Win!) or $0 (Ruin!). Try lowering win chance from 50% to just 45% and run 200 walks!

$10$0
Pause & Check · Quick Intuition Pulse

Pause & Check: In a FAIR coin-flip game (p = 0.5), you start with $3 and stop at $0 or $10. What is your win probability and expected number of flips?

3. Monte Carlo, Reservoir Sampling & Importance Sampling

Everyday Story First (Zero Math Yet!)

Want to find the area of a weird lake? Instead of solving ugly calculus integrals, throw 10,000 random pebbles into a rectangle around the lake and count what fraction splash into the water! That brilliantly lazy idea is Monte Carlo Sampling — and amazingly, its O(1/N)O(1/\sqrt{N}) accuracy works even in 10,000 dimensions where grid calculus dies completely!

Importance Sampling: Sample from Easy Proposal q(x), Reweight by w(x) = p(x)/q(x)Proposal q(x) (wide, easy to sample)Target p(x)Dot radius ∝ importance weight w(x) = p(x)/q(x) · Used in PPO & Off-Policy RL!
Figure 9.3 — Importance Sampling: when sampling directly from target p(x) is hard, sample from easy proposal q(x) and reweight every sample by w(x) = p(x)/q(x).

Three Sampling Tricks Every ML Engineer Should Own

  1. Reservoir Sampling (kk uniform samples from an infinite stream): Keep the first kk items. When item #ii arrives (i>ki > k), swap it into a random slot with probability k/ik/i. Works in O(k)O(k) RAM even if you don't know how long the stream is!
  2. Importance Sampling (Used in PPO & DeepSeek GRPO!): Can't sample from hard target p(x)p(x)? Draw from easy proposal q(x)q(x) and multiply each sample by weight wi=p(xi)/q(xi)w_i = p(x_i) / q(x_i)! Watch out for weight collapse using Effective Sample Size: ESS=(∑wi)2/∑wi2\text{ESS} = (\sum w_i)^2 / \sum w_i^2.
  3. Metropolis–Hastings (MCMC): Cleverly designs a Markov Chain whose steady state π\pi IS your nasty Bayesian posterior — so just walking the chain produces exact posterior samples!
Formula Anatomy · Click Any Colored Piece to Decode It
Importance Sampling: E_p[f(X)] ≈ (1/N) · Σ [ p(xᵢ) / q(xᵢ) ] · f(xᵢ)

How off-policy RL and LLM PPO reuse old trajectories without re-running the environment!

Sample From Easy / Old Proposal q

Generate samples from an easy distribution q(x) (or an older LLM policy π_old that already generated responses!).

In our example: Sample x from wide Gaussian q = N(3, 1)
Put it together with real numbers: Estimating 1-in-1,000 rare event P(Z > 3): shift proposal q to N(3, 1) so 50% of samples land in the tail, then reweight by p(x)/q(x)!
Try It YourselfStandard

In Importance Sampling with 4 samples, your weights come out to w = [10, 0, 0, 0]. Compute Effective Sample Size ESS = (Σw)² / Σw² and diagnose the bug!

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Think of shuffling a deck of cards (a Markov chain!). Even if you start with the deck in exact sorted order, after 7+ riffle shuffles the card probabilities smear smoothly across all permutations — the starting order gets completely washed away into the uniform steady state π\pi!

Interactive Visual Lab
Lab Challenge: Step ≥ 6 times (or press Auto-Play) from different starting states in the 3-State Markov Deep Lab to prove they all hit the exact same steady state π!
Interactive Playground · Markov Chain Convergence Lab

Watch Any Starting State Forget Its Past and Hit Steady State π

Goal: Advance ≥ 6 steps (Step t = 0)
Start 100% in:
State Distribution p^(t) at t = 0Steady π ≈ [0.46, 0.29, 0.25]
Sunny100.0%
Cloudy0.0%
Rainy0.0%
Transition Matrix P (row → col)
SunCldRain
Sunny0.70.20.1
Cloudy0.30.40.3
Rainy0.20.30.5

Try starting 100% in Rainy vs. 100% in Sunny — after ~8 steps, both converge to the exact same stationary vector π!

Intuition Takeaway: Row-stochastic Markov chains evolve via p^(t) = p^(0)P^t and converge to πP = π (flow in = flow out); tiny biases crush Gambler's Ruin odds; and Importance Sampling / MCMC power modern RLHF and Bayesian AI.
Where This Powers Real ML, Deep Learning & GenAI

Google PageRank & Graph Random Walks

PageRank adds 15% random teleportation so the web Markov chain is irreducible & aperiodic, guaranteeing one unique ranking π!

PPO & GRPO in LLM Post-Training (Importance Sampling)

RLHF algorithms reuse rollouts from π_old by multiplying rewards by the importance ratio π_θ / π_old.

Diffusion Models (DDPM Forward & Reverse Chains)

Image/video diffusion runs a forward Markov chain adding Gaussian noise, then learns a neural reverse Markov chain to generate art from static!

Streaming Data Pipelines (Reservoir Sampling)

Uniformly samples k evaluation logs from infinite Kafka/PubSub streams in O(k) memory.

Production NumPy & PyTorch Code Patterns
import numpy as np

# 1. Exact steady state πP = π via linear least squares
P = np.array([
    [0.7, 0.2, 0.1],
    [0.3, 0.4, 0.3],
    [0.2, 0.3, 0.5],
])
A = np.vstack([P.T - np.eye(3), np.ones(3)])
b = np.array([0.0, 0.0, 0.0, 1.0])
pi, *_ = np.linalg.lstsq(A, b, rcond=None)
print("Exact steady state π:", np.round(pi, 4))
print("After 30 steps P^30: ", np.round(np.linalg.matrix_power(P, 30)[0], 4))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Multiplying P on the wrong side (Pπ = π instead of πP = π) when rows sum to 1.
Best Practice: Always check first: if ROWS sum to 1, use row-vector πP = π (left eigenvector)!
Trap #2: Picking an Importance Sampling proposal q(x) with narrower/lighter tails than target p(x).
Best Practice: Always choose q(x) with HEAVIER tails than p(x) so p(x)/q(x) never explodes to infinity!
Trap #3: Assuming every Markov chain converges to a unique stationary vector.
Best Practice: Always verify irreducibility (strongly connected) and aperiodicity!
Chapter Mastery Check (+70 XP)
Score: 0 / 5
11. For a row-stochastic transition matrix P, the stationary row vector π satisfies:
22. Why does P = [[0, 1], [1, 0]] fail to converge from p^(0) = [1, 0]?
33. Fair Gambler's Ruin (p = 0.5) starting at $4 with goal $20: P(reach $20)?
44. Reservoir Sampling (k = 1): when item #100 arrives, probability of replacing the stored item?
55. Key requirement for Importance Sampling proposal q(x) to avoid exploding weights?

Apply What You Learned — Solve Matching Coding Problems