Reinforcement Learning
Reinforcement learning is the problem of acting to maximize long-run reward when four difficulties hit at once: you optimize a utility, consequences are delayed (credit assignment), you must explore to discover what’s good, and you must generalize across states you’ve never seen. Everything in the subject hangs off one object — the value function , the expected discounted return from under policy — and one recursion, the Bellman equation, which says today’s value is the immediate reward plus the discounted value of where you land. From there the field forks along two axes. Known vs unknown model: with the model you plan (dynamic programming — iterate a Bellman operator to its fixed point); without it you learn from samples (Monte Carlo vs temporal difference). Value-based vs policy-based: value methods estimate then act greedily; policy methods ascend the policy’s value directly. Convergence is earned, not assumed, and a small set of proof strategies recur — contraction + fixed point, monotone improvement, telescoping advantages, Jensen, Robbins–Monro, the score-function trick, mean-zero baselines, concentration + union bound, importance reweighting. Naming the strategy at each proof is the point: it turns a wall of derivations into a handful of reusable moves. Prerequisites cashed in: expectation, variance, conditional expectation, Markov chains (track 1); MLE and bias/variance (tracks 3, 6); contraction/fixed-point and norms (track 2); SGD, function approximation, the score function (tracks 11a, 11b); concentration and Jensen (track 1); conjugate priors (track 7); importance sampling intuition (track 9).
1. The problem: MDPs, returns, and value functions
- The agent–environment loop. At each step the agent takes action , the world transitions and emits observation and reward . The agent picks actions from a policy to maximize expected cumulative reward. We seek states of high value (long-run reward), not high immediate reward — that’s the whole delayed-consequence problem.
- The Markov assumption. — the state is a sufficient statistic of history; given the present, the future is independent of the past. (You can always make the state the full history, but that’s unwieldy; we assume , full observability.)
- The MDP is the tuple : states, actions, transition dynamics , reward , discount . A policy is a distribution over actions. (MDP + fixed policy collapses to a Markov reward process with averaged dynamics — useful: prediction problems reduce to MRPs.)
- Return and value. The return is the discounted reward sum ( toward 1 weights the future more; keeps infinite-horizon returns finite). The state-value and action-value functions are
measures how good a state is; how good an action is from a state. They link by and .
- Two tasks: prediction (evaluate a given ) vs control (find the best ). Model-based (you have/estimate ) vs model-free (you only sample).
Core competency set
- State the Markov assumption, the MDP tuple, return, and with their linking equations.
- Distinguish prediction vs control and model-based vs model-free.
2. The Bellman equations — the recursion everything rests on
- Where it comes from — split the return after one step, , and take expectations:
The expected next-step return is itself a value, :
Reading the expectation out over and gives the Bellman expectation equation
Today’s value = immediate reward + discounted value of the next state. A one-step lookahead, in other words.
- Matrix form (finite states): , solved directly by — exact but and needs the inverse to exist (it does for ).
- Bellman optimality for the best policy maxes over actions instead of averaging:
- The Bellman operators turn these equations into maps on value functions — the objects whose fixed points are the value functions:
is the fixed point of ; the fixed point of . The next section’s algorithms are just iterating these operators.
- Picture (draw it): the backup diagram — state at the root branches down to action nodes (the agent’s choice), each action branches to next-state nodes (the environment’s chance), one step deep. The Bellman expectation equation averages values back up this tree; optimality takes a max at the action layer instead of an average. Every value-based algorithm is some version of backing values up this diagram.
Core competency set
- Derive the Bellman expectation equation from ; write the optimality equation and the matrix solve.
- Define and and state that are their fixed points.
3. Planning by dynamic programming (known model)
- Policy evaluation = compute by iterating from any until convergence (a “Bellman backup,” a full sweep of states each iteration). It converges because is a contraction (proved below alongside ).
- Policy iteration = alternate evaluate () and greedily improve () until the policy stops changing. Two guarantees make it work:
- Policy improvement theorem — strategy: telescoping the one-step improvement inequality. Let be greedy w.r.t. , so . Then unroll:
Each step replaces a $V^\pi$ by the at-least-as-large $Q^\pi(\cdot,\pi')$ and expands one more reward; in the limit, $V^{\pi'} \ge V^\pi$.
- Termination — strategy: monotone improvement over a finite set. Each iteration strictly improves a deterministic policy, and there are only of them, so no policy repeats → it halts. At the halt, greedy gives no change, so — the Bellman optimality equation — hence is optimal.
- Value iteration = iterate the optimality operator directly (no separate evaluation phase), reading off at the end via one greedy step. Intuition: is the optimal value with steps left; grow the horizon. (Unlike policy iteration, the iterates don’t increase monotonically — they converge from wherever they start.)
- The convergence proof (the centerpiece) — strategy: contraction mapping + Banach fixed-point theorem. Claim: is a -contraction in the sup-norm, . For any state ,
(using ), and each term is
(probabilities sum to 1). Take the max over : . Since , Banach gives a unique fixed point and geometric convergence . The identical argument for proves policy evaluation converges to the unique .
- Finite horizon: just iterate value iteration exactly times (); now the optimal policy is non-stationary — with 1 step left vs 10, the best action differs.
| Problem | Bellman equation | Algorithm |
|---|---|---|
| Prediction | expectation | iterative policy evaluation |
| Control | expectation + greedy improvement | policy iteration |
| Control | optimality | value iteration |
Core competency set
- Run policy evaluation/iteration/value iteration as operator iterations; state which Bellman equation each uses.
- Prove the policy improvement theorem (telescoping) and policy-iteration termination (monotone + finite).
- Prove (and ) is a -contraction and invoke Banach for unique fixed point + geometric convergence.
4. Model-free prediction — learning from samples
The move to learning: we no longer know , only sampled experience. Two estimators of , trading off bias and variance.
- Monte Carlo (MC). Replace the expectation with an empirical mean of complete-episode returns. Maintain a count and update incrementally (the running-mean identity ):
First-visit MC (count only the first visit per episode) is unbiased; every-visit is biased (within-episode dependence) but consistent. Properties: no Markov assumption, but episodic only (you must wait for the episode to end), and high variance (a full return accumulates all the randomness of a trajectory).
- Temporal difference (TD(0)). Don’t wait for the episode — bootstrap: replace the unknown rest-of-return with the current estimate of the next state’s value. With the TD target and TD error ,
This is the Bellman equation with the expectation over replaced by a single sample. Properties: online (updates every step), works in continuing settings, uses the Markov property, lower variance (only one step’s randomness) but biased (the bootstrap target uses an estimate).
- DP with certainty equivalence: estimate the MLE model from data (count transitions, average rewards), then plan on it. Data-efficient and consistent, but expensive (re-solve the MDP each update).
- The comparison. MC is unbiased, high-variance, assumption-light, insensitive to initialization; TD is biased, low-variance, more data-efficient, Markov-exploiting, but converges only guaranteed under tabular representations. The classic AB example: MC converges to the minimum-MSE fit on the observed returns; TD converges to the value of the maximum-likelihood Markov model — so TD effectively builds and exploits a model of the world.
- Numeric anchor (Mars rover, , observed trajectory terminal with rewards ). Returns per visit: , first , second , . First-visit MC counts only the first : . Every-visit MC averages both visits: . TD(0) on the first tuple with and all values init 0: target , so stays 0 — TD propagates the terminal reward back one step per sweep, where MC moved it in a single episode (variance-for-immediacy, made concrete).
Core competency set
- Write MC (incremental mean) and TD(0) (TD error/target) updates; identify TD as “Bellman with a sampled next state.”
- Lay out the MC-vs-TD tradeoff (bias/variance, episodic/online, Markov) and the AB / min-MSE-vs-max-likelihood distinction.
5. Model-free control — learning to act
- Generalized policy iteration (GPI) without a model. Greedy improvement on needs the model (), so switch to : needs no model. But pure greed never explores untried actions — hence the explore/exploit tradeoff. Picture (draw it): GPI as two interacting processes pulling on — evaluation drags toward , improvement drags toward greedy; each step partly undoes the other, and they come to rest only at , the one point consistent with both (the Bellman optimality equation). Almost every control algorithm here is GPI with a different evaluation step (MC/TD/-step) and a softened greedy (-greedy).
- -greedy balances them: with prob take the greedy action, else a uniform random one.
- Monotone -greedy improvement — strategy: the policy improvement theorem again, checking the one-step inequality survives. For the -greedy w.r.t. ,
because shifting weight onto the max action (relative to $\pi$) can only raise the average. The improvement theorem then gives $V^{\pi'}\ge V^\pi$.
- GLIE (Greedy in the Limit with Infinite Exploration): every visited infinitely often and the policy converges to greedy (e.g. ). GLIE Monte-Carlo control converges to .
- SARSA — on-policy TD control on , updating from the tuple where is drawn from the current (-greedy) policy:
Convergence to requires (1) a GLIE policy sequence and (2) Robbins–Monro step sizes — strategy: stochastic approximation (steps big enough to reach anywhere, shrinking enough to settle).
- Q-learning — off-policy control: bootstrap off the best next action rather than the one taken, so it learns while behaving with an exploratory policy:
Needs only . Converges to with all visited infinitely often and R–M step sizes — not requiring GLIE (that’s only needed to make the behavior policy optimal).
- Maximization bias — strategy: Jensen’s inequality (max is convex). Even with unbiased per-action estimates , the greedy value over-estimates:
The fix — double Q-learning — splits the data into two independent estimates, using to select and to evaluate , decoupling selection from evaluation so the estimate is unbiased.
Core competency set
- Explain why control needs (model-free greedy) and -greedy; prove monotone -greedy improvement.
- Write SARSA (on-policy) vs Q-learning (off-policy, the max) and their convergence conditions (GLIE + R–M; R–M alone for ).
- Derive maximization bias via Jensen and explain double-Q’s selection/evaluation split.
6. Value-function approximation and deep RL
- Why. Tabular can’t handle large or continuous state spaces. Parameterize , (tabular is the special case where features are state indicators). Fit by SGD on the mean-squared value error , the state-visitation distribution.
- The oracle/supervised view. If an oracle gave , this is regression on pairs: . No oracle exists, so plug in a target:
- MC-VFA: target = return (unbiased). ; converges to the min-MSVE weights (the best linear approximation, which may not be ).
- TD-VFA: target = bootstrapped (a semi-gradient — we don’t differentiate through the target); biased, but lower variance, and converges to a different fixed point.
- The deadly triad. Combining bootstrapping + function approximation + off-policy learning can diverge. (Each pair is fine; all three together is the danger — the central caution of deep RL.)
- DQN makes Q-learning + neural nets stable with two tricks that attack the triad’s instabilities: experience replay (sample past transitions in random minibatches — breaks the temporal correlation that violates i.i.d.) and a target network (a periodically-frozen copy supplies the bootstrap target — stops the target from chasing the parameters). Extensions: double DQN (maximization-bias fix, online net selects / target net evaluates), prioritized replay (sample high-TD-error transitions more often), dueling DQN (split the head into + advantage ).
Core competency set
- Set up MSVE and the SGD update; contrast MC-VFA (unbiased target) vs TD-VFA (semi-gradient, biased) and their fixed points.
- State the deadly triad and how DQN’s replay + target network address it; name double/prioritized/dueling.
7. Policy gradient methods — optimize the policy directly
- Why policy-based. Parameterize the policy and ascend its value. Advantages: smoother convergence (no value-function discontinuities flipping the greedy action), works in continuous/high-dimensional action spaces (no global ), and can represent stochastic optimal policies (needed under partial observability / state aliasing — e.g. rock-paper-scissors). Disadvantage: typically local optima, high variance.
- The objective over trajectories .
- The score-function / likelihood-ratio trick — strategy: to turn a gradient of a probability into an expectation. Differentiate the objective:
Multiply and divide by (the log-derivative identity):
Recognize the weighted sum as an expectation:
Now expand the trajectory log-prob into its factors:
Drop every term free of — and the dynamics vanish, the key payoff: the model cancels:
Estimate by sampling trajectories: .
- Policy gradient theorem (general, beyond episodic): for any of the standard objectives,
The intuition: push up the log-probability of actions in proportion to how good they are. (Softmax policy score: — feature of the action taken minus its average.)
- REINFORCE: use the sampled return as an unbiased estimate of : . Correct but high variance (it’s Monte-Carlo).
- Baselines and the advantage — strategy: subtract a mean-zero term to cut variance without touching the mean. Claim: for any that depends only on the state, . Pull out and write the inner sum over actions:
Undo the log-derivative ():
Swap the sum and gradient; the action probabilities sum to 1, so its gradient is 0:
So subtracting leaves the gradient unbiased but can shrink its variance. The near-optimal choice is , giving the advantage (“how much better than average is this action”):
- Actor–critic. Maintain an actor (policy ) and a critic (value estimate ). The critic supplies the advantage. The clean trick: the TD error is an unbiased sample of the advantage —
The first term is exactly (Bellman), so the difference is the advantage:
so , using the approximate in practice. Variance reduction also comes from reward-to-go (only future rewards multiply each ) and -step / blended targets.
- Monotonic improvement → TRPO. Stepping too far in RL is unrecoverable (a bad policy collects bad data). The performance-difference lemma — strategy: express one policy’s value via the other’s advantages —
Why (telescoping): along a -trajectory, expand the advantage , so
(the discounted terms telescope) ; take to get . Exact, but it needs the new policy’s state distribution . Local approximation swaps in the old to get a surrogate that matches and its gradient at . Conservative policy iteration bounds the gap by a term in the policy difference; generalizing to a KL-divergence penalty gives a guaranteed-improvement lower bound. TRPO maximizes the surrogate subject to a trust-region KL constraint (the principled, larger step size), using importance sampling and a linear-objective/quadratic-constraint solve.
Core competency set
- Derive via the score-function trick and show the dynamics cancel; state the policy gradient theorem.
- Prove the baseline leaves the gradient unbiased () and define the advantage; show is an unbiased advantage sample.
- Explain REINFORCE → actor-critic (variance reduction) and the performance-difference-lemma → TRPO trust-region story.
8. Exploration and bandits
- Multi-armed bandit (MAB) = a single-state MDP: actions (“arms”) with unknown reward distributions; maximize cumulative reward. The pure-greedy estimator can lock onto a suboptimal arm forever.
- Regret is the currency: . Decompose it by gaps and counts — strategy: rewrite the sum over time as a sum over arms — with gap :
A good algorithm keeps small counts on large-gap arms. Greedy and fixed--greedy have linear regret (a constant fraction of pulls are suboptimal); the goal is sub-linear, and the lower bound is logarithmic, .
- Optimism under uncertainty → UCB — strategy: a concentration inequality + invert for a bonus + union bound over time. Hoeffding: . Set the RHS to a target and solve for the bonus:
so with probability . Choosing (so it holds across all steps, via a union bound) gives UCB1:
Less-tried arms (small ) get a bigger bonus → exploration. Regret bound — strategy: a pulled suboptimal arm had a high UCB, so the gap is bounded by the bonus. When UCB pulls suboptimal , its index beats the optimal’s, which (under the concentration event) exceeds ; chaining gives , hence , and — logarithmic, matching the lower bound’s rate. Picture: draw each arm’s value as a distribution; optimism compares the upper ends, so a wide (uncertain) arm can outrank a higher-mean narrow one — and its band shrinks as you sample it, which is the explore→exploit transition made visible.
- PAC (an alternative criterion): act -optimally with probability on all but a polynomial number of steps. Optimistic initialization (init high) is a simpler route to sub-linear regret if tuned right — but optimism may not survive function approximation.
- Bayesian bandits & Thompson sampling. Keep a posterior over each arm’s reward parameter (e.g. Beta–Bernoulli conjugacy, posterior ). Thompson sampling: sample a parameter from each arm’s posterior, act greedily w.r.t. the sampled values, update the chosen arm’s posterior. It implements probability matching — select arm with probability that it is optimal, — which is automatically optimistic (more-uncertain arms have more upside mass). Achieves the Lai–Robbins lower bound; sensitive to prior misspecification (no mass on the truth → can’t converge). Contextual bandits add an i.i.d. context per step (between bandits and MDPs).
- Numeric anchor. UCB, two arms at : arm 1 pulled , mean ; arm 2 pulled , mean . Bonuses and ; indices vs → pull the less-tried arm 2 despite its lower mean (optimism in action). Thompson: arm with prior (mean ), observe reward 0 → posterior (mean ); a later reward 1 → (mean back to , but tighter).
Core competency set
- Define regret and decompose it into gaps × counts; explain why greedy/-greedy are linear and the log- lower bound.
- Derive the UCB bonus from Hoeffding (+ union bound) and sketch the regret argument.
- Explain Thompson sampling and that it implements probability matching.
9. Fast MDP learning and offline (batch) RL
- Optimism in MDPs: MBIE-EB adds an exploration bonus to rewards in a tabular MDP (the UCB idea lifted to states/actions); Bayesian MDPs maintain a posterior over dynamics.
- The batch/offline setting: you’re handed a fixed dataset of trajectories from a behavior policy and must evaluate/optimize a new policy without collecting more data — the counterfactual, censored-data problem (you only see outcomes of decisions actually taken). Assumptions to make it tractable: stationarity, Markov, sequential ignorability (no unrecorded confounders — the potential-outcomes link to track 9), and overlap ( wherever — you can’t evaluate actions the data never tried). The deadly triad bites again for off-policy value methods.
- Off-policy evaluation by importance sampling — strategy: importance reweighting (multiply and divide by the sampling density). To estimate from samples drawn from :
Multiply and divide by the sampling density :
Estimate from samples :
Sample under (behavior), reweight by — unbiased given overlap. Lifted to trajectories, , and expanding the trajectory probabilities, the dynamics cancel — only the product of policy ratios remains. So importance sampling is unbiased with no Markov assumption and no model — but high variance: the product of ratios makes variance scale exponentially in the horizon. Per-decision IS trims it (a reward only needs the ratios up to its own time, since later actions can’t affect it). (Effective sample size flags how little data a recommendation truly rests on.)
Core competency set
- List the offline-RL assumptions (stationarity, Markov, ignorability, overlap) and why overlap is required.
- Derive the importance-sampling estimator and the trajectory version where dynamics cancel; state its unbiasedness, the no-Markov property, and the exponential-in-horizon variance.
10. Model-based RL and Monte Carlo tree search
- Model-based RL: learn and from experience (supervised regression / density estimation), then plan on the learned model. Upside: data-efficient, and the model’s uncertainty can guide exploration. Downside: two error sources — model error and planning error on top of it.
- Sample-based planning: use the model only as a simulator of , then run any model-free method on the simulated experience.
- Simulation-based search computes a policy only for the current state (no full state-space sweep — efficient when you visit only a small subset). Simple MC search: from the current state, simulate episodes per action under a fixed policy and pick the highest mean return (one step of policy improvement). The expectimax tree does better — full lookahead taking at action nodes and expectation at state nodes (value iteration on the current sub-MDP) — but is . Picture (draw it): the expectimax tree — square max nodes (actions) alternating with round expectation nodes (next states), rooted at the current state; MCTS grows only the promising branches (UCB-selecting at each max node) and rolls out a default policy past the frontier, instead of expanding the whole tree.
- MCTS avoids building the whole tree: run simulations from the root, each with a tree policy (pick actions to maximize inside the explored tree) and a rollout policy (random/default once you leave it); a node’s value is the average return of simulations passing through it. Converges to the optimal action with enough simulations; best for large state space, small action space, long horizon.
- UCT = MCTS where each tree node is treated as its own bandit and actions are chosen by UCB: — so search effort concentrates on promising, under-explored branches. The simulating policy changes as estimates evolve.
- AlphaGo ties it together: an adversarial (minimax) tree, a value network for position evaluation and a policy network (bootstrapped by imitation learning of human moves, then self-play) to prune the huge action branching, bootstrapping instead of rolling to the leaf (MC → TD), and self-play to densify the win/loss reward signal.
Core competency set
- Contrast model-based (learn model, plan; two error sources) with model-free; explain sample-based planning.
- Explain MCTS (tree vs rollout policy, node value) and UCT (each node a UCB bandit); summarize AlphaGo’s value net + policy net + self-play.
11. Memorize cold
- Return ; value , ; .
- Bellman expectation (matrix solve ); optimality . Operators ; are their fixed points.
- is a -contraction in → Banach → unique , . (proof strategy: contraction + fixed point.)
- Policy iteration: evaluate + greedy; improvement theorem (telescoping) + finite policies → terminates at optimal. Value iteration: iterate .
- MC update (unbiased FV, high variance, episodic). TD(0) , (biased, low variance, online, Markov).
- SARSA (on-policy) target ; Q-learning (off-policy) target . Converge with R–M steps (); SARSA→ needs GLIE.
- Maximization bias: (Jensen) → double-Q (select with , evaluate with ).
- Deadly triad = bootstrapping + function approximation + off-policy → can diverge. DQN = replay + target network.
- Score-function trick: ; dynamics cancel in . REINFORCE uses . Baseline keeps it unbiased (); advantage ; TD error is an unbiased sample.
- Regret . UCB1 (Hoeffding + union bound) → regret. Thompson sampling = sample posterior, act greedy = probability matching.
- Importance sampling ; trajectory IS keeps only (dynamics cancel) — unbiased, no Markov, variance exponential in . Needs overlap.
- UCT = MCTS with a UCB bandit at each node.
Named moves (cross-track glossary): value-is-the-object (everything hangs off ); one-step-lookahead (the Bellman recursion); contraction-then-fixed-point (VI/PE convergence — Banach, track 2); monotone-improvement-over-finite-set (PI terminates); telescope-the-advantage (policy improvement & performance-difference lemmas); bootstrap-vs-sample-the-return (TD vs MC, the bias/variance dial); Robbins–Monro (stochastic-approximation step sizes); Jensen-overestimates-the-max (maximization bias → decouple select/evaluate); score-function-trick (, model-free policy gradient — tracks 11a/11b); subtract-a-mean-zero-baseline (variance reduction without bias); TD-error-is-the-advantage; optimism-under-uncertainty (UCB / MBIE / Thompson); concentration-plus-union-bound (UCB bonus & regret — track 1); probability-matching (Thompson); importance-reweighting (off-policy evaluation, dynamics cancel — track 9); bandit-at-every-node (UCT); simulate-don’t-enumerate (sample-based planning breaks the curse of dimensionality).