RLS RL, Read as Statistics

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 vπv_\pi and qπq_\pi as numbers to be estimated, and treated the return GtG_t 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 GtG_t 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 θ\theta denote the unknown environment: the dynamics p(s′,r∣s,a)p(s', r \mid s, a) of a finite MDP. A Bayesian agent holds a posterior over θ\theta given its data D\mathcal{D}. Fix a policy π\pi and a start state. The return GG then has a predictive distribution, obtained by drawing θ\theta from the posterior and then a trajectory from θ\theta. The law of total variance splits its variance:

Var⁡(G∣D)=Eθ∣D[Var⁡(G∣θ)]⏟aleatoric+Var⁡θ∣D(E[G∣θ])⏟epistemic.\operatorname{Var}(G \mid \mathcal{D}) = \underbrace{\mathbb{E}_{\theta \mid \mathcal{D}}\big[\operatorname{Var}(G \mid \theta)\big]}_{\text{aleatoric}} + \underbrace{\operatorname{Var}_{\theta \mid \mathcal{D}}\big(\mathbb{E}[G \mid \theta]\big)}_{\text{epistemic}} .

The two behave differently with data. Collect more transitions and the posterior over θ\theta concentrates, so the epistemic term goes to zero at the usual 1/n1/n 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 Na(t)N_a(t) 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 N×NN \times N 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, 0.01/N0.01/N. The only reward is +1+1 for being in the bottom-right corner on the last row. In our version each move is reversed with probability 0.10.1 (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 N−1N-1 consecutive moves go right.

Count how often a uniformly random policy succeeds. At every step the effective move is right with probability 12⋅0.9+12⋅0.1=12\tfrac12 \cdot 0.9 + \tfrac12 \cdot 0.1 = \tfrac12, so the chance of N−1N-1 rights in a row is 2−(N−1)2^{-(N-1)}. For N=12N = 12 that is 1/20481/2048 per episode, and an epsilon-greedy agent with ϵ=0.1\epsilon = 0.1 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 kk:

  1. Draw a model θ~k\tilde\theta_k from the posterior p(θ∣Dk)p(\theta \mid \mathcal{D}_k).
  2. Compute the optimal policy π~k\tilde\pi_k for θ~k\tilde\theta_k exactly (dynamic programming).
  3. Follow π~k\tilde\pi_k for the whole episode and record the transitions.
  4. 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 (s,a)(s, a), the next state is categorical. With a Dirichlet⁡(α1,…,αm)\operatorname{Dirichlet}(\alpha_1, \dots, \alpha_m) prior, after observing counts n1,…,nmn_1, \dots, n_m the posterior is Dirichlet⁡(α1+n1,…,αm+nm)\operatorname{Dirichlet}(\alpha_1 + n_1, \dots, \alpha_m + n_m).
  • 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 O~(τSAT)\tilde O(\tau S \sqrt{AT}) for TT steps, episode length τ\tau, SS states and AA 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 Dirichlet⁡(12,12,12)\operatorname{Dirichlet}(\tfrac12, \tfrac12, \tfrac12) prior. We try the action three times and see next states 1,3,31, 3, 3. The counts are (1,0,2)(1, 0, 2), so the posterior is Dirichlet⁡(32,12,52)\operatorname{Dirichlet}(\tfrac32, \tfrac12, \tfrac52). Its mean is

(3/2, 1/2, 5/2)9/2=(13, 19, 59).\frac{(3/2,\ 1/2,\ 5/2)}{9/2} = \left(\tfrac13,\ \tfrac19,\ \tfrac59\right).

The maximum-likelihood estimate from the same data is (13,0,23)(\tfrac13, 0, \tfrac23). The posterior keeps 19\tfrac19 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 Beta⁡(1,1)\operatorname{Beta}(1,1), so a draw exceeds 12\tfrac12 with probability 12\tfrac12. Of two such states, at least one draw exceeds 12\tfrac12 with probability 34\tfrac34. 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 00, the posterior sharpens (Beta⁡(1,1+n)\operatorname{Beta}(1, 1 + n) has mean 1/(n+2)1/(n+2)) 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 KK copies of the network and treat their disagreement as epistemic uncertainty. Bootstrapped DQN (Osband, Blundell, Pritzel and Van Roy, 2016) does this: KK 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 y=x⊤θ+εy = x^\top \theta + \varepsilon, the posterior under a Gaussian prior θ∼N(0,σ2λ−1I)\theta \sim \mathcal{N}(0, \sigma^2 \lambda^{-1} I) and noise ε∼N(0,σ2)\varepsilon \sim \mathcal{N}(0, \sigma^2) is

θ∣D∼N ⁣(θ^, σ2(X⊤X+λI)−1),θ^=(X⊤X+λI)−1X⊤y.\theta \mid \mathcal{D} \sim \mathcal{N}\!\big(\hat\theta,\ \sigma^2 (X^\top X + \lambda I)^{-1}\big), \qquad \hat\theta = (X^\top X + \lambda I)^{-1} X^\top y .

The bootstrap reproduces something like σ2(X⊤X)−1\sigma^2 (X^\top X)^{-1}, with no λ\lambda. In directions where the data say nothing (X⊤XX^\top X has no mass), the posterior variance is σ2/λ\sigma^2/\lambda, 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 fk(x)+c pk(x)f_k(x) + c\, p_k(x), where pkp_k is a random, fixed, untrained network and only fkf_k is trained.

In the linear model this has an exact reading. Draw θ0∼N(0,σ2λ−1I)\theta_0 \sim \mathcal{N}(0, \sigma^2 \lambda^{-1} I) and noise ε~∼N(0,σ2I)\tilde\varepsilon \sim \mathcal{N}(0, \sigma^2 I), and fit

θ~=arg⁡min⁡θ ∥y+ε~−Xθ∥2+λ∥θ−θ0∥2=(X⊤X+λI)−1(X⊤(y+ε~)+λθ0).\tilde\theta = \arg\min_\theta \ \lVert y + \tilde\varepsilon - X\theta \rVert^2 + \lambda \lVert \theta - \theta_0 \rVert^2 = (X^\top X + \lambda I)^{-1}\big(X^\top (y + \tilde\varepsilon) + \lambda \theta_0\big).

The mean of θ~\tilde\theta is θ^\hat\theta, and its covariance is

(X⊤X+λI)−1(σ2X⊤X+λ2⋅σ2λ−1I)(X⊤X+λI)−1=σ2(X⊤X+λI)−1.(X^\top X + \lambda I)^{-1}\big(\sigma^2 X^\top X + \lambda^2 \cdot \sigma^2 \lambda^{-1} I\big)(X^\top X + \lambda I)^{-1} = \sigma^2 (X^\top X + \lambda I)^{-1}.

So θ~\tilde\theta is an exact draw from the posterior. The random prior function plays the role of θ0\theta_0: 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 Z(s)Z(s) for the random return from state ss under π\pi (we used GtG_t before; ZZ emphasises that we treat it as a distribution-valued function of ss). The Bellman equation of chapter 1 was a statement about means, vπ(s)=E[Rt+1+γvπ(St+1)]v_\pi(s) = \mathbb{E}[R_{t+1} + \gamma v_\pi(S_{t+1})]. The same recursion holds one level up, for the whole random variable:

Z(s) =d Rt+1+γ Z(St+1),St=s,Z(s) \ \overset{d}{=}\ R_{t+1} + \gamma\, Z(S_{t+1}), \qquad S_t = s,

where =d\overset{d}{=} means equality in distribution and Z(St+1)Z(S_{t+1}) is drawn independently of Rt+1R_{t+1} given the next state. In words: the return distribution from ss is a mixture over (Rt+1,St+1)(R_{t+1}, S_{t+1}) of the next state's return distribution, shrunk by γ\gamma and shifted by Rt+1R_{t+1}. 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 π\pi, 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: ZZ 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

ρτ(u)=u (τ−1{u<0}),τ∈(0,1),\rho_\tau(u) = u\,\big(\tau - \mathbf{1}\{u < 0\}\big), \qquad \tau \in (0, 1),

applied to the residual u=y−qu = y - q. So ρτ(u)=τu\rho_\tau(u) = \tau u when u≥0u \ge 0 and (τ−1)u=(1−τ)∣u∣(\tau - 1) u = (1-\tau)\lvert u \rvert when u<0u < 0: an absolute-value loss tilted so that under-prediction costs τ\tau per unit and over-prediction costs 1−τ1 - \tau.

Claim. If YY has distribution function FF, then L(q)=E[ρτ(Y−q)]L(q) = \mathbb{E}[\rho_\tau(Y - q)] is minimised at any qq with F(q)=τF(q) = \tau (more precisely, at any τ\tau-quantile).

Derivation. Write

L(q)=τ E[(Y−q)1{Y>q}]+(1−τ) E[(q−Y)1{Y≤q}].L(q) = \tau\, \mathbb{E}\big[(Y - q)\mathbf{1}\{Y > q\}\big] + (1 - \tau)\, \mathbb{E}\big[(q - Y)\mathbf{1}\{Y \le q\}\big].

Differentiate in qq. The first term has derivative −τ P(Y>q)-\tau \, \mathbb{P}(Y > q) (the boundary term vanishes because the integrand is zero at Y=qY = q); the second has derivative (1−τ) P(Y≤q)(1 - \tau)\,\mathbb{P}(Y \le q). Hence

L′(q)=−τ (1−F(q))+(1−τ)F(q)=F(q)−τ.L'(q) = -\tau\,\big(1 - F(q)\big) + (1-\tau) F(q) = F(q) - \tau .

FF is non-decreasing, so L′L' is non-decreasing, LL is convex, and L′=0L' = 0 where F(q)=τF(q) = \tau. For τ=12\tau = \tfrac12 the loss is half the absolute error and the minimiser is the median, as it should be. □\square

A check by hand. Let YY be uniform on {1,2,6}\{1, 2, 6\} and τ=0.25\tau = 0.25. The 0.250.25-quantile is 11 (since F(1)=13≥0.25F(1) = \tfrac13 \ge 0.25). The loss at candidate values:

qqresiduals y−qy - qρ0.25\rho_{0.25} valuesmean loss
10,1,50, 1, 50, 0.25, 1.250,\ 0.25,\ 1.250.5000.500
1.5−0.5,0.5,4.5-0.5, 0.5, 4.50.375, 0.125, 1.1250.375,\ 0.125,\ 1.1250.5420.542
2−1,0,4-1, 0, 40.75, 0, 10.75,\ 0,\ 10.5830.583
6−5,−4,0-5, -4, 03.75, 3, 03.75,\ 3,\ 02.2502.250

The loss is smallest at q=1q = 1 and rises on either side.

Quantile TD

Quantile TD learning keeps NN numbers θi(s)\theta_i(s) per state, intended as the quantiles at the midpoint levels τi=(i−12)/N\tau_i = (i - \tfrac12)/N, and updates them with transitions (s,r,s′)(s, r, s') by treating the bootstrapped values as samples of the target distribution. For each ii and each target sample r+γθj(s′)r + \gamma\theta_j(s'),

θi(s)←θi(s)+α 1N∑j=1N(τi−1{r+γθj(s′)<θi(s)}).\theta_i(s) \leftarrow \theta_i(s) + \alpha\,\frac1N \sum_{j=1}^{N} \Big(\tau_i - \mathbf{1}\{r + \gamma\theta_j(s') < \theta_i(s)\}\Big).

This is exactly the stochastic pinball-loss gradient above with the empirical distribution of the targets in the role of YY. (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 NN-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 N×NN \times N with slip probability 0.10.1. The epsilon-greedy agent is tabular Q-learning with ϵ=0.1\epsilon = 0.1, step size 0.10.1 and zero initial values. PSRL uses a Dirichlet⁡(12,12,12)\operatorname{Dirichlet}(\tfrac12,\tfrac12,\tfrac12) prior over the three columns reachable from each cell, a Beta⁡(1,1)\operatorname{Beta}(1,1) 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 π\pi is fixed) with γ=0.9\gamma = 0.9. From the start state, with probability 12\tfrac12 each, the process moves to a good state or a bad state. In the good state the reward is N(2,0.52)\mathcal{N}(2, 0.5^2) each step and the process stays with probability 12\tfrac12, otherwise stops; the bad state is the same with mean −1.5-1.5. The return from the start is therefore a mixture of two separated clusters. We run quantile TD with N=21N = 21 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).

Output
(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 N=4N = 4 to the cap by N=8N = 8, and at N=12N = 12 no seed found the treasure in 3,000 episodes. (Seeds that did find it early did so by luck: the minimum for N=8N = 8 is 70 and for N=10N = 10 it is 15.) PSRL's median grows slowly, from 6 episodes at N=4N = 4 to 56 at N=12N = 12, and every seed succeeded. The growth is roughly polynomial, not the 2N2^{N} 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 0.5000.500 and only 0.7%0.7\% of returns fall within 0.50.5 of the mean 0.4060.406. The mean-only TD(0) estimate V(0)=0.425V(0) = 0.425 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 0.150.15 of the exact ones (for example −1.174-1.174 against −1.205-1.205 at τ=0.405\tau = 0.405), and the implied mass below zero is 0.4760.476, one quantile out of 21 away from 0.50.5.

Where it is worst is instructive. At τ=0.500\tau = 0.500 the estimate is 1.0161.016 against an exact 0.1510.151: 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 τ=0.976\tau = 0.976 the estimate is 6.7646.764 against 7.4087.408: 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

  1. (Pen and paper.) A return is +10+10 with probability 12\tfrac12 and −10-10 with probability 12\tfrac12 in model AA, and always 00 in model BB. What are the mean, the variance, and the 0.250.25-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?
  2. (Pen and paper.) Show that if YY is continuous with a density, the pinball loss is differentiable in qq, and that the stochastic update q←q+α(τ−1{y<q})q \leftarrow q + \alpha(\tau - \mathbf{1}\{y < q\}) has expected step α(τ−F(q))\alpha(\tau - F(q)). What goes wrong with the fixed point if FF has a flat piece at level τ\tau?
  3. (Pen and paper.) In the linear model with XX having a single row x=(1,0)x = (1, 0) and λ>0\lambda > 0, compute the posterior variance of each coordinate of θ\theta. Compare with the variance of a bootstrap of the OLS estimate in the coordinate with no data.
  4. (Change the code.) Set SLIP = 0.0 in the deep-sea experiment, or raise ϵ\epsilon to 0.30.3. Predict first: does epsilon-greedy get better, and by how much at N=8N = 8? Then run it. Does PSRL's advantage survive?
  5. (Change the code.) Increase NQ from 21 to 101 and re-run part (b). Predict which row of the table improves most. Then try lowering the step-size floor from 0.001 to 0.0003 and say what you expect to happen to the noise in V(0)V(0).

Sources