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
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?
- 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.
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!')
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!
From Friendly Graph to Transition Matrix
Put those hopping arrows into a table where every ROW sums to 1 (because from any state, you MUST land somewhere next step!):
- After steps from starting state : .
- Steady State : The equilibrium where one more step changes nothing: (Linear Algebra connection: the left eigenvector for !).
- When does EVERY starting point converge to the same ? 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!
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?
In equilibrium, the number of users leaving Active each month MUST equal the number returning from Churned:
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!)
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%)!
The Two Iconic Gambler's Ruin Formulas (Start at \k$N$)
- Fair Coin ():
- Biased Coin (, let ):
Test both fair and biased games right now in the Live Random Walker below!
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!
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
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 accuracy works even in 10,000 dimensions where grid calculus dies completely!
Three Sampling Tricks Every ML Engineer Should Own
- Reservoir Sampling ( uniform samples from an infinite stream): Keep the first items. When item # arrives (), swap it into a random slot with probability . Works in RAM even if you don't know how long the stream is!
- Importance Sampling (Used in PPO & DeepSeek GRPO!): Can't sample from hard target ? Draw from easy proposal and multiply each sample by weight ! Watch out for weight collapse using Effective Sample Size: .
- Metropolis–Hastings (MCMC): Cleverly designs a Markov Chain whose steady state IS your nasty Bayesian posterior — so just walking the chain produces exact posterior samples!
How off-policy RL and LLM PPO reuse old trajectories without re-running the environment!
Generate samples from an easy distribution q(x) (or an older LLM policy π_old that already generated responses!).
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!
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 !
Watch Any Starting State Forget Its Past and Hit Steady State π
| Sun | Cld | Rain | |
|---|---|---|---|
| Sunny | 0.7 | 0.2 | 0.1 |
| Cloudy | 0.3 | 0.4 | 0.3 |
| Rainy | 0.2 | 0.3 | 0.5 |
Try starting 100% in Rainy vs. 100% in Sunny — after ~8 steps, both converge to the exact same stationary vector π!
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.
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))