Chapter 09 · Part 3: Learning policies
Two kinds of uncertainty, and the whole return distribution
Epistemic versus aleatoric uncertainty in RL, posterior sampling and ensembles as exploration, and quantile regression as a way to estimate the entire distribution of the return.
Chapter 8 ended with an estimator problem: the policy gradient is noisy, and we spent the chapter reducing its variance. This chapter is about a different noise. Everything so far treated and as numbers to be estimated, and treated the return as a random variable whose spread is a nuisance. Two things were left out. First, the agent's uncertainty about its own estimate is information it can act on, as chapter 3 showed for bandits. Second, the spread of is itself something one can estimate, and for some purposes it is the object of interest, not the nuisance.
What are the two kinds of uncertainty?
Let denote the unknown environment: the dynamics of a finite MDP. A Bayesian agent holds a posterior over given its data . Fix a policy and a start state. The return then has a predictive distribution, obtained by drawing from the posterior and then a trajectory from . The law of total variance splits its variance:
The two behave differently with data. Collect more transitions and the posterior over concentrates, so the epistemic term goes to zero at the usual rate. The aleatoric term does not move, because dice stay random. This is why they are treated differently:
- Exploration should be driven by epistemic uncertainty. A state whose return is highly variable but well understood needs no more visits. A state never visited needs some, whatever its eventual variance.
- Risk-sensitive control cares about aleatoric uncertainty: two policies with the same mean return can differ in how often they end badly.
Chapter 2 made the first point for bandits: UCB's bonus is a confidence-interval half-width, which is epistemic, and it shrinks as grows. The rest of this chapter extends that to sequential problems and then turns to the aleatoric half.
Why does epsilon-greedy fail at deep exploration?
Epsilon-greedy acts greedily with respect to a point estimate and adds independent dithering. It has no notion of which estimates are uncertain. In a bandit that costs only a constant factor. In a sequential problem it can cost exponentially.
The standard test is the deep sea. The agent lives on an grid and starts in the top-left corner. Each step it moves down one row and chooses left or right (clamped at the walls). Choosing right costs a small known amount, . The only reward is for being in the bottom-right corner on the last row. In our version each move is reversed with probability (a slip). The greedy policy learns quickly that going left is free and going right is costly, and the treasure is out of reach unless consecutive moves go right.
Count how often a uniformly random policy succeeds. At every step the effective move is right with probability , so the chance of rights in a row is . For that is per episode, and an epsilon-greedy agent with that has learned to prefer left behaves worse than that. The agent does not need more luck. It needs to hold the hypothesis that something good is down the right-hand diagonal for long enough to test it, which means committing to a consistent plan for the whole episode. Epsilon-greedy re-flips its coin at every step.
What is posterior sampling for RL?
Posterior sampling for reinforcement learning (PSRL; Strens, 2000; analysed by Osband, Russo and Van Roy, 2013) is the following loop, repeated for each episode :
- Draw a model from the posterior .
- Compute the optimal policy for exactly (dynamic programming).
- Follow for the whole episode and record the transitions.
- Update the posterior.
This is Thompson sampling from chapter 3 with the arm replaced by an MDP and the action by a policy. The same argument applies: the probability of following a policy equals the posterior probability that it is optimal, so uncertain parts of the model get tried in proportion to the chance that they matter. Two features make it suited to sequential problems. A model drawn at once is internally consistent, so if it says the corner is rewarding, the policy heads there on a coordinated path, which is the deep exploration epsilon-greedy lacks. And the posterior is conjugate in the tabular case:
- Transitions: for each , the next state is categorical. With a prior, after observing counts the posterior is .
- Rewards: for a Bernoulli reward the posterior is Beta, exactly as in chapter 3.
Osband, Russo and Van Roy prove an expected Bayesian regret of order for steps, episode length , states and actions, and note that it is one of the first bounds for an algorithm that does not rely on optimism. The statement is about regret averaged over the prior the agent actually holds, which is the right comparison for a Bayesian method and not a worst-case guarantee.
A worked example by hand
Take one state-action pair with three possible next states and a prior. We try the action three times and see next states . The counts are , so the posterior is . Its mean is
The maximum-likelihood estimate from the same data is . The posterior keeps on the transition never seen. A single draw from this Dirichlet can put substantial mass on next state 2, and if state 2 is unvisited and its reward draw is high, the sampled model will try to reach it. Next, a Beta example: a never-visited state has reward posterior , so a draw exceeds with probability . Of two such states, at least one draw exceeds with probability . When many states are unexplored, some sampled reward is almost surely large, and PSRL is pulled towards unexplored territory. As a state is visited and its reward is seen to be , the posterior sharpens ( has mean ) and the pull fades.
Can an ensemble stand in for the posterior?
Exact posteriors over neural-network value functions are out of reach. A cheap substitute is to train copies of the network and treat their disagreement as epistemic uncertainty. Bootstrapped DQN (Osband, Blundell, Pritzel and Van Roy, 2016) does this: value heads share a trunk, each head sees each transition with a random mask, and at the start of each episode one head is chosen at random and followed greedily for the episode. That last step is PSRL with the posterior sample replaced by a bootstrap replicate.
The statistical rationale is that the bootstrap approximates the sampling distribution of an estimator, and in simple models the Bayesian posterior and the sampling distribution are close. The trouble is what the bootstrap leaves out. In the linear model , the posterior under a Gaussian prior and noise is
The bootstrap reproduces something like , with no . In directions where the data say nothing ( has no mass), the posterior variance is , set entirely by the prior. A bootstrap ensemble there has nothing to resample: each member is whatever its initialisation and optimiser give, which tends to be the same for all members, so the ensemble looks certain exactly where it knows least. Osband, Aslanides and Cassirer (2018) make this point and propose a remedy, the randomised prior function: each member is , where is a random, fixed, untrained network and only is trained.
In the linear model this has an exact reading. Draw and noise , and fit
The mean of is , and its covariance is
So is an exact draw from the posterior. The random prior function plays the role of : it makes the pull of each member towards its own random starting point a feature, not an accident. For nonlinear networks the identity is no longer exact. The paper's claim is empirical: the ensemble with priors explores much better than one without.
What does the distribution of the return add?
Now the other half of the variance split. Write for the random return from state under (we used before; emphasises that we treat it as a distribution-valued function of ). The Bellman equation of chapter 1 was a statement about means, . The same recursion holds one level up, for the whole random variable:
where means equality in distribution and is drawn independently of given the next state. In words: the return distribution from is a mixture over of the next state's return distribution, shrunk by and shifted by . Taking expectations of both sides returns the ordinary Bellman equation. This is the distributional Bellman equation (Bellemare, Dabney and Munos, 2017). They show that the corresponding operator is a contraction in the maximal Wasserstein distance, so repeated application converges to the return distribution of , and the practical algorithm C51 represents it on 51 fixed support points and projects after each update. A full treatment is in the book by Bellemare, Dabney and Rowland (2023), which is available free online.
Why bother, if the mean is what we maximise? For risk-neutral control the optimal policy depends on the mean only. Estimating the distribution is useful when the quantity of interest is a risk measure (a lower quantile, say), and the distributional-RL papers report that predicting the full distribution also improves performance in deep agents, which is often attributed to richer learning signals. It does not give epistemic uncertainty: is the aleatoric part, estimated from data, and a distributional agent can be confidently wrong about it in unvisited states.
Quantiles minimise the pinball loss
To represent a distribution, Dabney, Rowland, Bellemare and Munos (2018) use quantiles, fitted by quantile regression (Koenker and Bassett, 1978). The mean is the minimiser of squared error; a quantile is the minimiser of the pinball loss
applied to the residual . So when and when : an absolute-value loss tilted so that under-prediction costs per unit and over-prediction costs .
Claim. If has distribution function , then is minimised at any with (more precisely, at any -quantile).
Derivation. Write
Differentiate in . The first term has derivative (the boundary term vanishes because the integrand is zero at ); the second has derivative . Hence
is non-decreasing, so is non-decreasing, is convex, and where . For the loss is half the absolute error and the minimiser is the median, as it should be.
A check by hand. Let be uniform on and . The -quantile is (since ). The loss at candidate values:
| residuals | values | mean loss | |
|---|---|---|---|
| 1 | |||
| 1.5 | |||
| 2 | |||
| 6 |
The loss is smallest at and rises on either side.
Quantile TD
Quantile TD learning keeps numbers per state, intended as the quantiles at the midpoint levels , and updates them with transitions by treating the bootstrapped values as samples of the target distribution. For each and each target sample ,
This is exactly the stochastic pinball-loss gradient above with the empirical distribution of the targets in the role of . (QR-DQN uses a smoothed, "Huber" version of the loss near zero for optimisation; the idea is the same.) Midpoint levels are the choice that minimises the 1-Wasserstein error of an -point approximation, per Dabney et al.
Experiment
The companion file ch09_uncertainty.py runs both experiments below in about half a minute, NumPy only.
(a) Deep sea. The grid is with slip probability . The epsilon-greedy agent is tabular Q-learning with , step size and zero initial values. PSRL uses a prior over the three columns reachable from each cell, a prior on the reward received on arriving in each state, and solves each sampled MDP by backward induction over the rows. Both are run for at most 3,000 episodes; the table reports the median, minimum and maximum over 20 seeds of the episode in which the treasure is first reached, and in how many seeds that happened.
(b) Bimodal returns. A Markov reward process (no actions, so is fixed) with . From the start state, with probability each, the process moves to a good state or a bad state. In the good state the reward is each step and the process stays with probability , otherwise stops; the bad state is the same with mean . The return from the start is therefore a mixture of two separated clusters. We run quantile TD with quantiles for 150,000 episodes with a decaying step size, and compare with the exact quantiles from 200,000 Monte Carlo returns. We also run a mean-only TD(0).
(a) Deep sea: episodes until the first treasure (cap 3000), 20 seeds
N | eps-greedy med [min,max] | PSRL med [min,max]
4 | 22 [ 1, 521] 20/20 | 6 [ 2, 19] 20/20
6 | 997 [ 2,3000] 12/20 | 14 [ 2, 24] 20/20
8 | 3000 [ 70,3000] 4/20 | 20 [ 1, 62] 20/20
10 | 3000 [ 15,3000] 3/20 | 43 [ 14, 75] 20/20
12 | 3000 [3000,3000] 0/20 | 56 [ 7, 126] 20/20
(last column of each cell: seeds that found the treasure before the cap)
(b) Quantile TD vs exact (Monte Carlo, 200000 returns) from the start state
tau exact QTD
0.024 -5.660 -5.132
0.119 -3.318 -3.193
0.214 -2.274 -2.185
0.310 -1.627 -1.595
0.405 -1.205 -1.174
0.500 0.151 1.016
0.595 1.667 1.700
0.690 2.110 2.158
0.786 3.083 3.193
0.881 4.328 4.466
0.976 7.408 6.764
mean return, Monte Carlo : 0.406
mean from QTD quantiles : 0.488
mean-only TD(0) estimate V(0): 0.425
P(G < 0), Monte Carlo : 0.500
P(G < 0), from QTD quantiles : 0.476
P(|G - mean| < 0.5), MC : 0.007 (mass near the mean)Reading (a). The epsilon-greedy agent's median time to the treasure goes from tens of episodes at to the cap by , and at no seed found the treasure in 3,000 episodes. (Seeds that did find it early did so by luck: the minimum for is 70 and for it is 15.) PSRL's median grows slowly, from 6 episodes at to 56 at , and every seed succeeded. The growth is roughly polynomial, not the of the random walk. The cap makes the epsilon-greedy medians lower bounds, not estimates. Note too what this is not: it measures time to first reward, and the agent still has to learn a good policy afterwards. PSRL's policy is optimal for each sampled model, and as the posterior concentrates, the samples converge to the truth.
Reading (b). The exact quantiles show a cluster of returns below zero, then a gap, then a second cluster above. In our run the mass below zero is exactly and only of returns fall within of the mean . The mean-only TD(0) estimate is accurate for what it measures, and tells you nothing about the shape: the average outcome is a value that almost never happens. Quantile TD recovers the shape. Away from the extremes its quantiles are within about of the exact ones (for example against at ), and the implied mass below zero is , one quantile out of 21 away from .
Where it is worst is instructive. At the estimate is against an exact : the median sits in the gap between the two clusters, where the quantile function jumps, so a tiny change in the level moves the answer a long way. This is the usual ill-conditioning of a quantile where the density is near zero, not a bug. At the estimate is against : a 21-point midpoint representation cannot place a point in the far tail, and because each update bootstraps from the representation, the truncation feeds back. More quantiles, or a tail-specific treatment, would reduce it.
Exercises
- (Pen and paper.) A return is with probability and with probability in model , and always in model . What are the mean, the variance, and the -quantile of each? Which has more aleatoric variance? Suppose the agent does not know which model it is in and gives them equal posterior probability: what is the epistemic term in the variance decomposition for the mean return?
- (Pen and paper.) Show that if is continuous with a density, the pinball loss is differentiable in , and that the stochastic update has expected step . What goes wrong with the fixed point if has a flat piece at level ?
- (Pen and paper.) In the linear model with having a single row and , compute the posterior variance of each coordinate of . Compare with the variance of a bootstrap of the OLS estimate in the coordinate with no data.
- (Change the code.) Set
SLIP = 0.0in the deep-sea experiment, or raise to . Predict first: does epsilon-greedy get better, and by how much at ? Then run it. Does PSRL's advantage survive? - (Change the code.) Increase
NQfrom 21 to 101 and re-run part (b). Predict which row of the table improves most. Then try lowering the step-size floor from0.001to0.0003and say what you expect to happen to the noise in .
Sources
- Strens, M. J. A. (2000). A Bayesian Framework for Reinforcement Learning. ICML 2000.
- Osband, I., Russo, D., Van Roy, B. (2013). (More) Efficient Reinforcement Learning via Posterior Sampling. NeurIPS 2013.
- Osband, I., Blundell, C., Pritzel, A., Van Roy, B. (2016). Deep Exploration via Bootstrapped DQN. NeurIPS 2016.
- Osband, I., Aslanides, J., Cassirer, A. (2018). Randomized Prior Functions for Deep Reinforcement Learning. NeurIPS 2018.
- Bellemare, M. G., Dabney, W., Munos, R. (2017). A Distributional Perspective on Reinforcement Learning. ICML 2017.
- Dabney, W., Rowland, M., Bellemare, M. G., Munos, R. (2018). Distributional Reinforcement Learning with Quantile Regression. AAAI 2018.
- Koenker, R., Bassett, G. (1978). Regression Quantiles. Econometrica 46(1).
- Bellemare, M. G., Dabney, W., Rowland, M. (2023). Distributional Reinforcement Learning. MIT Press (free online).