Chapter 11
Off-policy Methods with Approximation
Tabular Q-learning makes off-policy learning look easy: learn about the greedy policy while behaving in any sufficiently exploratory way, and convergence is guaranteed. Chapter 10 carried on-policy control over to function approximation and stopped short of Q-learning. With function approximation the off-policy idea becomes treacherous. The difficulty has two parts. The first, already met in the tabular case, concerns the targets of the updates: returns generated by a behavior policy must be corrected, by importance sampling or by expectations, to say something about a target policy . The second part is new and is the real subject of this chapter. It concerns the distribution of the updates. In Chapter 9 the stability of semi-gradient TD rested, silently, on the fact that states were updated in proportion to how often visits them. Off-policy, they are updated as often as visits them, and that is enough to make the simplest linear TD method diverge. We first locate the mechanism of divergence exactly, in one matrix inequality; then we look at the geometry of linear value functions to see which objectives could be optimized instead; and we end with the two families of stable algorithms, Gradient-TD and Emphatic-TD, that this analysis produces.Richard S. Sutton and Andrew G. Barto. Reinforcement Learning: An Introduction. Adaptive Computation and Machine Learning. MIT Press, Cambridge, MA, second edition, 2018. ISBN 978-0-262-03924-6. URL http://incompleteideas.net/book/the-book-2nd.html
11.1Semi-gradient Off-policy Methods#
The first part of the challenge is handled exactly as in the tabular case. Each tabular off-policy algorithm of Chapter 6 and Chapter 7 becomes a semi-gradient algorithm by replacing the update of a table entry with an update of the weight vector along the gradient of the estimate. Most of them use the per-step importance sampling ratio, the one-factor case of (5.2):
(11.1)Algorithm 11.1 (Semi-gradient off-policy TD(0)). Input: target policy , behavior policy with whenever ; a differentiable with . Parameter: step size . Initialize: arbitrarily.
Loop for each step, from the current state :
- Choose ; take it, observe .
- and .
- ; .
In the average-reward setting of Section 10.3, is replaced by the differential TD error.
For action values the one-step algorithm needs no ratio at all: semi-gradient Expected Sarsa uses , because the only sampled action, , is the one whose value is being learned.With a table this argument is airtight. With function approximation it is less so: every pair contributes to a shared , and one could argue that pairs should be weighted by how often , not , would produce them. Sutton and Barto leave the question open; the emphatic weighting of Section 11.8 is one answer. Multi-step versions need products , or, in the tree-backup form, products of target probabilities instead of ratios. All of these correct the targets. None of them touch the distribution of states at which updates are made, and therefore none of them is guaranteed to be stable.
11.1.1The Expected Update#
From now on the approximation is linear, , with . Collect the feature vectors as the rows of the matrix , write for the distribution of states at which updates are made (here, the stationary distribution of the behavior policy), , for the state-transition matrix under , and . Conditioning on , the ratio turns the behavior expectation into a target expectation, , so
(11.2)This is the same pair as in the on-policy analysis of Chapter 9, with one change: now holds the behavior distribution while is still the target dynamics. The expected update has the TD fixed point of (9.5) as its only candidate limit, and it converges for small exactly when every eigenvalue of has positive real part. When does that hold? The following result answers the question for every weighting at once.The column-sum argument below is the one Sutton, Mahmood and White (2016) use for emphatic TD; applied to the on-policy weighting it gives a three-line proof of the positive definiteness that Tsitsiklis and Van Roy (1997) obtained from the norm inequality .Richard S. Sutton, A. Rupam Mahmood, and Martha White. An Emphatic Approach to the Problem of Off-Policy Temporal-Difference Learning. Journal of Machine Learning Research, 17(73):1–29, 2016; and John N. Tsitsiklis and Benjamin Van Roy. An Analysis of Temporal-Difference Learning with Function Approximation. IEEE Transactions on Automatic Control, 42(5):674–690, 1997. doi: 10.1109/9.580874
Theorem 11.2 (The key-matrix test). Let be a nonnegative matrix with row sums at most , , and a weighting of the states. Put . If the column sums of are nonnegative,
(11.3)then for every , with strict inequality for when . Consequently, if has full column rank, every eigenvalue of has positive real part.
Proof. The diagonal of is and its off-diagonal entries are . The symmetric matrix inherits both signs, and row of sums to (row sum of ) (column sum of ) . Because the off-diagonal entries are nonpositive, this row sum equals , so every Gershgorin disc of lies in , and . If the row sums are strictly positive and is positive definite. Finally, if only for and with of unit length, then . □
The test singles out the on-policy weighting. If is stationary for , then ; in the episodic case, with the expected number of visits and the start distribution (), the column sums are . This is why on-policy linear TD is stable (Theorem 9.4). For a behavior distribution there is no such identity: can put far more mass on a state than does, and then a column sum goes negative. Intuitively, a state that flows into heavily, but that is rarely updated, is a state whose value is used as a target much more often than it is corrected.
11.2Examples of Off-policy Divergence#
11.2.1From to #
Take two states with scalar features and , so their estimates are and , and a single deterministic transition from the first to the second with reward . The TD error of that transition is . The first state has only one action, so , and the off-policy update multiplies by a constant.The example and the next one are due to Tsitsiklis and Van Roy (1996); van Hasselt et al. (2018) use the same two states to open their study of the deadly triad in deep networks.John N. Tsitsiklis and Benjamin Van Roy. Feature-Based Methods for Large Scale Dynamic Programming. Machine Learning, 22(1–3):59–94, 1996. doi: 10.1007/BF00114724
One semi-gradient update on the transition from the -state to the -state: the weight is multiplied by .const upd2w = await wl`Function[{w}, w + \[Alpha] 1 (0 + \[Gamma] 2 w - w) 1]`
await show`Factor[${upd2w}[w]]`await show`Reduce[0 < \[Alpha] < 1 && 0 <= \[Gamma] <= 1 && Abs[1 + \[Alpha] (2 \[Gamma] - 1)] > 1, \[Gamma]]`Divergence does not depend on how small is: a smaller step only slows it down. The essential ingredient is that this one transition is updated over and over, while the transitions out of the state are not. Under they would have to occur, and each one would pull back down unless it led to a state of still higher value; a promise made by bootstrapping must eventually be paid by rewards. Off-policy, may wander off with an action never takes, the ratio is zero, and the promise is forgotten. In the language of Theorem 11.2: the state receives flow from the first one but is never updated, so its column sum is .
11.2.2Tsitsiklis and Van Roy’s Counterexample#
Complete the fragment into an episodic chain: from the state the process stays put with probability and terminates with probability , all rewards zero. Now is representable (), and we can ask whether doing more than a semi-gradient step helps. Suppose that at each iteration we fit by least squares, with equal weight on the two states, to the expected one-step targets computed from :
(11.4)The exact least-squares DP step on the two-state chain, solved in closed form.await show`Factor[x /. First[Solve[D[(x - 2 \[Gamma] w)^2 + (2 x - 2 (1 - \[Epsilon]) \[Gamma] w)^2, x] == 0, x]]]`So , which diverges as soon as : even a perfect fit at every step does not save dynamic programming from the wrong weighting. The same threshold appears for expected semi-gradient TD. With weights the scalar of (11.2) is .
The scalar under uniform weighting and under the on-policy weighting, which visits the second state times per episode.const aChain = await wl`Function[{m1, m2}, m1 (1 - 2 \[Gamma]) + m2 2 (2 - 2 \[Gamma] (1 - \[Epsilon]))]`
await show`{Simplify[${aChain}[1/2, 1/2]], Simplify[${aChain}[\[Epsilon]/(1 + \[Epsilon]), 1/(1 + \[Epsilon])]]}`Under the uniform weighting exactly when , the same condition; under the on-policy weighting for all and . The model, the features and the algorithm are identical; only the distribution of updates differs.
11.2.3Baird’s Counterexample#
Example 11.3 (Baird’s counterexample). Seven states, two actions, all rewards zero, . The dashed action moves to one of the states uniformly; the solid action moves to state . The behavior policy takes dashed with probability and solid with probability , so that its next-state distribution, and hence , is uniform. The target policy always takes solid, so sends every state to state . The features are for and in : linearly independent, more weights than states, exactly representable. Ratios are after solid and after dashed.Leemon C. Baird. Residual Algorithms: Reinforcement Learning with Function Approximation. In Proceedings of the Twelfth International Conference on Machine Learning (ICML 1995), pages 30–37. Morgan Kaufmann, 1995. doi: 10.1016/B978-1-55860-377-6.50013-X
Everything about this problem looks favorable, yet the weights of semi-gradient TD diverge from almost any start. Because the setting is fully specified we can compute of (11.2) exactly and look at the spectrum of the expected-update matrix .
Build (), and , and factor the characteristic polynomial of symbolically in .const Xb = await wl`Join[Table[2 UnitVector[8, i] + UnitVector[8, 8], {i, 6}], {UnitVector[8, 7] + 2 UnitVector[8, 8]}]`
const Pb = await wl`ConstantArray[UnitVector[7, 7], 7]`
const Ab = await wl`Transpose[${Xb}] . (IdentityMatrix[7]/7) . (IdentityMatrix[7] - \[Gamma] ${Pb}) . ${Xb}`
await show`Factor[CharacteristicPolynomial[-${Ab}, \[Lambda]]]`The factor belongs to the direction that maps to zero; five eigenvalues equal and are harmless. The remaining pair solves : its product is positive, so both roots have positive real part as soon as their sum is positive.
The exact range of discounts for which the expected semi-gradient TD update on Baird’s problem has an unstable mode.const bairdQuad = await wl`49 \[Lambda]^2 + (105 - 119 \[Gamma]) \[Lambda] + 26 (1 - \[Gamma])`
await show`Reduce[0 <= \[Gamma] < 1 && Max[Re[\[Lambda] /. Solve[${bairdQuad} == 0, \[Lambda]]]] > 0, \[Gamma]]`await show`Union[N[Eigenvalues[-${Ab} /. \[Gamma] -> 99/100], 3]]`Baird’s problem therefore diverges for every and is stable below.Sutton and Barto state the instability only for . The threshold follows from the factorization above: above it the expected update diverges for every step size ; below it, it converges for every small enough that the stable modes contract. The divergence has nothing to do with sampling. Replace the sampled update by the synchronous, DP-style sweep : this is , with the same unstable eigenvalues (Figure 11.1, left). Nothing is random and nothing is asynchronous, yet the simplest bootstrapping method with the simplest approximator fails, only because the sweep weights the states uniformly. The key-matrix test shows where: the column sum of state is , negative for any , because all seven states feed state under while it receives only a seventh of the updates. (The test is sufficient, not necessary, which is why the actual threshold is the larger .)
Counterexamples of the same kind exist for Q-learning with linear features. Two classic escape routes are partial. Least-squares fitting at each DP step fails, as we saw. Averagers, approximators such as nearest neighbors or kernel smoothing whose output at a state is a convex combination of stored targets, never extrapolate and are stable for any update distribution, because is then a sup-norm contraction; but tile coding and neural networks are not averagers.Geoffrey J. Gordon. Stable Function Approximation in Dynamic Programming. In Proceedings of the Twelfth International Conference on Machine Learning (ICML 1995), pages 261–268. Morgan Kaufmann, 1995. doi: 10.1016/B978-1-55860-377-6.50040-2
11.3The Deadly Triad#
The examples share three ingredients, and instability appears exactly when all three are present. Sutton calls them the deadly triad:Richard S. Sutton and Andrew G. Barto. Reinforcement Learning: An Introduction. Adaptive Computation and Machine Learning. MIT Press, Cambridge, MA, second edition, 2018. ISBN 978-0-262-03924-6. URL http://incompleteideas.net/book/the-book-2nd.html
- Function approximation: a representation, linear or nonlinear, that generalizes across states and has far fewer parameters than there are states.
- Bootstrapping: targets that contain current estimates, as in DP and TD, rather than complete returns.
- Off-policy training: updates distributed differently from the target policy’s own trajectories. A DP sweep that updates all states uniformly is off-policy in this sense.
Any two are safe. Tabular Q-learning bootstraps off-policy without generalization. On-policy linear TD generalizes and bootstraps, and Theorem 11.2 with guarantees its stability. Gradient Monte Carlo with importance sampling generalizes off-policy without bootstrapping, and is plain stochastic gradient descent on a fixed regression objective. Neither control nor learning is part of the problem: the instability appears in prediction, and in planning with a known model.
Which element could be given up? Not function approximation: it is what makes large problems tractable at all, and its cheaper substitutes (state aggregation, nonparametric memories, quadratic-cost LSTD) do not scale. Bootstrapping can be dropped, but at a large price in data efficiency, as the -step and experiments of Chapter 7 and Chapter 12 show, and in computation, since Monte Carlo must store a trajectory until its return is known. Off-policy learning is dispensable for a single control task (use Sarsa instead of Q-learning), but it is essential for the larger ambition of learning many predictions in parallel from one stream of experience: one behavior cannot coincide with many target policies. The rest of the chapter keeps all three and asks what must change in the algorithm.
11.4The Geometry of Linear Value Functions#
Think of a value function as a vector in and of the linear approximator as the subspace . Distances are measured in the weighted norm
so that as in (9.1). The closest representable function to is its projection
(11.5)an orthogonal projection for the inner product ( and ). Monte Carlo methods converge to . Bootstrapping methods aim at the Bellman operator
whose unique fixed point is (the Bellman equation (3.9) in vector form). Applied to a representable it usually leaves the subspace. The gap is the Bellman error vector
the expected TD error at each state. Four objectives can now be distinguished.
, minimized by .
The mean squared Bellman error , zero only at .
The mean squared projected Bellman error, the size of the part of the Bellman error that the approximator can see:
(11.6)The mean squared TD error .
The second form of (11.6) follows from . Its middle factor is , and its outer factor is the expected TD update, . Hence
(11.7)which vanishes exactly at the TD fixed point , the point where . In the on-policy case is a -contraction in ( is non-expansive and ), which is the deeper reason for the bound of Theorem 9.7. Off-policy, may exceed ; the projected iteration then expands, exactly as in (11.4), and , though it still exists when is invertible, may be arbitrarily far from .
The two forms of the projected Bellman error agree identically: here for three states, two features and arbitrary weights and Bellman errors .const Xg = await wl`{{1, 0}, {1, 1}, {0, 2}}`
await show`Module[{d = DiagonalMatrix[{Subscript[\[Mu], 1], Subscript[\[Mu], 2], Subscript[\[Mu], 3]}], dl = {Subscript[\[Delta], 1], Subscript[\[Delta], 2], Subscript[\[Delta], 3]}, proj}, proj = ${Xg} . Inverse[Transpose[${Xg}] . d . ${Xg}] . Transpose[${Xg}] . d; Simplify[{proj . proj - proj, (proj . dl) . d . (proj . dl) - (Transpose[${Xg}] . d . dl) . Inverse[Transpose[${Xg}] . d . ${Xg}] . (Transpose[${Xg}] . d . dl)}]]`11.5Gradient Descent in the Bellman Error#
Semi-gradient methods are not gradient methods, and that is where their fragility comes from. True stochastic gradient descent on a fixed objective can only go downhill and is stable under any data distribution. Which objective should we descend? The most immediate candidate is the , which is an expectation under and can therefore be sampled. Its stochastic gradient step,
(11.8)is semi-gradient TD plus the missing term . This naive residual-gradient algorithm converges robustly, but to the wrong place.Leemon C. Baird. Residual Algorithms: Reinforcement Learning with Function Approximation. In Proceedings of the Twelfth International Conference on Machine Learning (ICML 1995), pages 30–37. Morgan Kaufmann, 1995. doi: 10.1016/B978-1-55860-377-6.50013-X
Example 11.4 (The A-split example). Episodes start in , move with reward to or with probability each, and then terminate with reward from and from ; , on-policy, tabular values . The true values are , , .Peter Dayan. The Convergence of TD() for General . Machine Learning, 8(3–4):341–362, 1992. doi: 10.1007/BF00992701
const tdeSplit = await wl`Function[{a, b, c}, (1/2) ((1/2) (b - a)^2 + (1/2) (c - a)^2) + (1/2) ((1/2) (1 - b)^2 + (1/2) (0 - c)^2)]`
await show`Minimize[${tdeSplit}[a, b, c], {a, b, c}]`At the true values the TD errors are on the first step and on the second, a of ; the values , spread the error as over both steps and achieve . Penalizing every TD error produces temporal smoothing, not prediction.
The natural repair is to square the expected TD error, that is, to descend the . Conditioning on ,
a product of two expectations over the same next state. One sample of gives an unbiased estimate of each factor but a biased estimate of the product (it estimates , not ); this is the double-sampling problem. The residual-gradient algorithm is unbiased only if the environment is deterministic, or if a simulator can be reset to draw a second, independent from the same . Then it converges, for linear and nonlinear approximators, to a minimum of the . But three objections remain. It is slow. It still finds bad values: in the A-presplit variant, where two start states (always going to ) and (always going to ) share one feature, all transitions are deterministic, so , and the minimizer is again , while semi-gradient TD finds and . And, most seriously, the next section shows that the cannot be learned from data at all.
11.6The Bellman Error Is Not Learnable#
Call a quantity learnable if it is a function of the distribution of the observable data, the sequence of feature vectors, actions and rewards, so that it could be estimated, with enough experience, without access to the underlying states. This is learnability in principle, not in the PAC sense of efficiency.
The is not learnable. A single state emitting rewards and at random, and two states with deterministic rewards and that switch at random, produce indistinguishable data streams when both look alike to the features; with and the first has and the second . Yet its minimizer is learnable, because it coincides with that of the mean squared return error, which is an expectation of observables.
Proposition 11.5 (Return error and value error). On-policy, , so the two objectives have the same minimizers.
Proof. Write and square. The cross term has conditional expectation , because . Taking expectations over leaves plus a term free of . □
The Bellman error has no such escape: two processes can generate the same data and still have different minimizers.
Example 11.6 (Two MRPs with the same data and different BE minimizers). First MRP: states with distinct features. goes to with reward ; from , with probability each, stay in with reward or go to with reward . Second MRP: states , where and share a feature. goes to or (probability each, reward ); goes to or (probability each, reward ); goes to with reward . In both, the observer sees an with reward , then apparent ’s, each followed by except the last, followed by , with ; the weights are in the first and in the second. Weights are .
In the first MRP is representable and minimizes the for every . In the second, with , the Bellman errors are at , at and at .
Minimize the of the second MRP in closed form.const be2 = await wl`Function[{a, b}, ((\[Gamma] b - a)^2 + (-1 + (\[Gamma] - 1) b)^2 + (1 + \[Gamma] a - b)^2)/3]`
const wBE = await show`Simplify[{a, b} /. First[Solve[{D[${be2}[a, b], a] == 0, D[${be2}[a, b], b] == 0}, {a, b}]]]`await show`Limit[${wBE}, \[Gamma] -> 1]`await show`{Simplify[${be2}[b - 1/2, b] /. \[Gamma] -> 1], Factor[Det[D[${be2}[a, b], {{a, b}, 2}]]]}`So the minimizer depends on structure that the data do not reveal.Sutton and Barto give the limit as ; the computation above gives . For every the is a strictly convex quadratic, so its minimizer is unique, and these minimizers converge to . At the objective sees only and is minimized on the whole line , which contains both points; is the minimizer when is held at , in line with the book’s remark that the value of is approximately zero, but it is not the limit. The value of is pulled negative because the deterministic reward on entering from says that should be worth one more than , and must share its value with . Contrast the projected Bellman error: , and in (11.7) are expectations of observables (, , ), so the and its minimizer are learnable, and so is the .
The matrix computed from each MRP’s hidden structure (rows: features, transitions, rewards, ): they coincide, as they must, being expectations of observables.const aOf = await wl`Function[{X, P, mu}, Simplify[Transpose[X] . DiagonalMatrix[mu] . (IdentityMatrix[Length[mu]] - \[Gamma] P) . X]]`
await show`{${aOf}[IdentityMatrix[2], {{0, 1}, {1/2, 1/2}}, {1/3, 2/3}], ${aOf}[{{1, 0}, {0, 1}, {0, 1}}, {{0, 1/2, 1/2}, {0, 1/2, 1/2}, {1, 0, 0}}, {1/3, 1/3, 1/3}]}`Both MRPs also give (the rewards and out of average out), so the TD fixed point is in both. The can be minimized only with access to the underlying states, which is exactly what the double sample of the residual-gradient algorithm provides. This, more than its slowness, is why attention turns to the .
11.7Gradient-TD Methods#
Gradient-TD methods are stochastic gradient methods for the with cost per step.Richard S. Sutton, Hamid Reza Maei, Doina Precup, Shalabh Bhatnagar, David Silver, Csaba Szepesvári, and Eric Wiewiora. Fast Gradient-Descent Methods for Temporal-Difference Learning with Linear Function Approximation. In Proceedings of the 26th International Conference on Machine Learning (ICML 2009), pages 993–1000, 2009. doi: 10.1145/1553374.1553501 From (11.7),
(11.9)The first and last factors both involve , so multiplying single samples would be biased again; storing the matrices would cost . The way out is to learn the product of the last two factors as a second weight vector,
which is the least-squares solution for predicting from , and is found by the LMS rule . Substituting into and sampling gives GTD2. Alternatively, first use (because ) to write ; sampling this form gives semi-gradient TD plus a correction, TDC (TD with gradient correction, also called GTD(0)).
Algorithm 11.7 (TDC and GTD2 (linear, off-policy)). Input: , , features with . Parameters: step sizes , typically . Initialize: arbitrary, .
Loop for each step, from with features :
- Choose , observe ; , .
- and (computing first keeps the cost ).
- TDC: . GTD2 instead: .
- ; .
The two learning processes form a cascade: the secondary vector tracks a quantity defined by , while relies on being accurate. Convergence proofs use two time scales, and , so that is effectively always at its target. For GTD2, however, stability of the expected dynamics holds for any ratio of step sizes, and the proof is short. Write ; the expected update of is times
(11.10)Theorem 11.8 (Stability of expected GTD2). If is nonsingular and is positive definite, every eigenvalue of has negative real part, for every and whatever the sign structure of . The unique equilibrium is , .
Proof. Let with nonzero, that is, and . If , the first equation gives and then the second gives , a contradiction. Multiply the second equation on the left by and use :
and taking real parts,
If then with , impossible; so , the right side is negative, and . At an equilibrium forces and then . □
The contrast with semi-gradient TD is the whole point: there, stability needed itself to be positive (stable), which the off-policy distribution can destroy; here enters only through the block structure, and only its invertibility matters. TDC is usually the faster of the two in practice, but its stability needs the secondary process to be fast enough. Both facts can be seen on the scalar chain of Section 11.2.2, with and scalars.
The eigenvalues of the scalar GTD2 matrix: for , their real parts are negative whatever the sign of .const gtd2M = await wl`{{0, a}, {-\[Eta] a, -\[Eta] c}}`
await show`Eigenvalues[${gtd2M}]`const tdcM = await wl`{{-a, -(c - a)}, {-\[Eta] a, -\[Eta] c}}`
await show`Simplify[{Tr[${tdcM}], Det[${tdcM}]}]`On Baird’s counterexample and are singular (rank in ), so one direction is neutral and the theorem applies on the complement; the remaining eigenvalues of have negative real parts.
The spectrum of the expected TDC dynamics on Baird’s problem, , , summarized: the largest real part, the number of zero eigenvalues (the two null directions of , one for and one for ), and the largest real part among the others.const Cb = await wl`Transpose[${Xb}] . (IdentityMatrix[7]/7) . ${Xb}`
const tdcBaird = await wl`ArrayFlatten[{{-${Ab}, -(${Cb} - Transpose[${Ab}])}, {-\[Eta] ${Ab}, -\[Eta] ${Cb}}}] /. {\[Gamma] -> 99/100, \[Eta] -> 10}`
await show`With[{ev = Chop[N[Eigenvalues[${tdcBaird}]], 10^-10]}, {Max[Re[ev]], Count[ev, 0], Max[Re[DeleteCases[ev, 0]]]}]`As Figure 11.1 shows, the goes to zero quickly but the weights approach a good value function very slowly: on Baird’s problem the TD solution set is a line, and the is nearly flat along the way to it. Gradient-TD methods are today the best understood stable off-policy learners. They extend to action values and control (GQ), to eligibility traces (GTD(), GQ(), Section 12.9), and to nonlinear approximators, and hybrid versions (HTD) reduce to ordinary TD when .
11.8Emphatic-TD Methods#
The second strategy keeps the cheap semi-gradient update and repairs the distribution: reweight the updates so that their effective weighting passes the test of Theorem 11.2. Which weighting? Think of discounting as pseudo-termination: with probability per step the process “ends” and immediately restarts from where it is. Any distribution obtained by starting somewhere and then following until (pseudo-)termination is an on-policy distribution in the sense required by the test, and the starts are ours to choose. If every state visited by is treated as a start with interest , and the subsequent “on-policy continuation” is tracked by importance sampling, the weight that state should receive is the followon traceRichard S. Sutton, A. Rupam Mahmood, and Martha White. An Emphatic Approach to the Problem of Off-Policy Temporal-Difference Learning. Journal of Machine Learning Research, 17(73):1–29, 2016
(11.11)Algorithm 11.9 (One-step emphatic TD (linear)). As Algorithm 11.1, with interest and a scalar at the start. At each step, after observing and computing and :
- (the emphasis; here it equals the followon trace).
- .
- ; .
Proposition 11.10 (Emphatic TD passes the key-matrix test). Let . Then , the expected update of Algorithm 11.9 is , and satisfies (11.3). In particular, if and has full column rank, expected emphatic TD is stable.
Proof. depends only on the past, so given it is independent of , and . Taking expectations in (11.11) at stationarity, , that is, . The same independence gives , hence the expected update. Its column sums are , and (Neumann series of a nonnegative matrix), so Theorem 11.2 applies. □
const fB = await show`Simplify[ConstantArray[1/7, 7] . Inverse[IdentityMatrix[7] - \[Gamma] ${Pb}]]`await show`Simplify[{${fB} . (IdentityMatrix[7] - \[Gamma] ${Pb}), ConstantArray[1/7, 7] . (IdentityMatrix[7] - \[Gamma] ${Pb})}]`const AeB = await wl`Transpose[${Xb}] . DiagonalMatrix[${fB}] . (IdentityMatrix[7] - \[Gamma] ${Pb}) . ${Xb}`
await show`Factor[CharacteristicPolynomial[-${AeB}, \[Lambda]]]`So emphatic TD converges on Baird’s problem in expectation (Figure 11.1, right). In practice it is another matter. The weight of state relative to its frequency is at , and it is delivered by products of ratios that are or : the followon trace is almost always small and occasionally enormous. Its variance is so large that sampled runs on this problem are erratic, although the method is convergent in theory.Full convergence proofs for emphatic TD, with traces and state-dependent , are due to Yu (2015); Hallak et al. (2016) analyzed its variance and proposed a bounded variant.Huizhen Yu. On Convergence of Emphatic Temporal-Difference Learning. In Proceedings of The 28th Conference on Learning Theory (COLT 2015), volume 40 of Proceedings of Machine Learning Research, pages 1724–1751, 2015; and Assaf Hallak, Aviv Tamar, Rémi Munos, and Shie Mannor. Generalized Emphatic Temporal Difference Learning: Bias-Variance Analysis. In Proceedings of the Thirtieth AAAI Conference on Artificial Intelligence (AAAI-16), pages 1631–1637. AAAI Press, 2016. doi: 10.1609/aaai.v30i1.10227
11.9Reducing Variance#
Off-policy learning is inherently noisier than on-policy learning: the further is from , the less each sample says about , and in the limit nothing at all. Importance ratios have expectation but products of them have high, sometimes infinite, variance, and in stochastic gradient methods they multiply the step size. A single huge step can carry the weights to a region with a different gradient. Several remedies help, none solves the problem: small or adaptive per-parameter step sizes, momentum and Polyak–Ruppert averaging, “importance-weight-aware” updates, approximations of weighted importance sampling with cost, and methods that avoid ratios altogether as tree backup does, or clip them, as Retrace and V-trace do (Section 12.11). Another option is to let the target policy depend on the behavior, so that ratios are bounded by construction, as in the recognizers of Precup et al.Doina Precup, Richard S. Sutton, Cosmin Paduraru, Anna Koop, and Satinder Singh. Off-Policy Learning with Options and Recognizers. In Advances in Neural Information Processing Systems 18 (NIPS 2005), pages 1097–1104. MIT Press, 2006 The positive side of the coin is the raison d’être of off-policy learning: any policy has many neighbors, policies that visit similar states and take similar actions, and one stream of experience can teach a great deal about all of them.
11.10Beyond the Book: The Deadly Triad in Deep Reinforcement Learning#
Since 2015 almost every large-scale value-based agent has embodied all three elements of the triad: deep networks, bootstrapped targets, and replayed off-policy data. Why does it work at all?Beyond Sutton and Barto (2018). The book mentions DQN only as an application. The analyses below (van Hasselt et al., 2018; Liu et al., 2015, in the saddle-point form; Kumar et al., 2020) relate the triad to deep and offline reinforcement learning, which developed after or alongside the second edition.
DQN’s two stabilizers. The deep Q-network of Mnih et al. (Section 15.5) learns by Q-learning from minibatches drawn from a replay memory, with targets computed by a target network that is copied from the online network only every steps.Volodymyr Mnih, Koray Kavukcuoglu, David Silver, Andrei A. Rusu, Joel Veness, Marc G. Bellemare, Alex Graves, Martin Riedmiller, Andreas K. Fidjeland, Georg Ostrovski, Stig Petersen, Charles Beattie, Amir Sadik, Ioannis Antonoglou, Helen King, Dharshan Kumaran, Daan Wierstra, Shane Legg, and Demis Hassabis. Human-Level Control through Deep Reinforcement Learning. Nature, 518(7540):529–533, 2015. doi: 10.1038/nature14236 Between copies this is an ordinary regression problem with fixed targets, so each phase is a true gradient method, a stochastic version of the least-squares DP of (11.4). The target network removes the immediate feedback loop of the example, in which raising also raises its own target; it does not remove the triad, because the outer iteration can still expand (Section 15.5.1 checks this on the same two states). Replay decorrelates consecutive samples and averages the behavior over many past policies, which makes the data more off-policy, not less.
How often does the triad bite? Van Hasselt et al. trained many DQN variants on Atari and tracked the largest action value, calling values beyond the largest attainable return soft divergence.Hado van Hasselt, Yotam Doron, Florian Strub, Matteo Hessel, Nicolas Sonnerat, and Joseph Modayil. Deep Reinforcement Learning and the Deadly Triad, 2018 Soft divergence was common, but unbounded divergence never occurred. Its frequency fell sharply with longer multi-step returns (one-step Q-learning soft-diverged in of runs, -step in ), fell with target networks and with double Q-learning’s correction of overestimation, and rose with stronger prioritized replay, which pushes the update distribution further from the on-policy one; larger networks were, against expectation, slightly less stable. Each element of the triad thus behaves as a dial, not a switch, in the direction that Theorem 11.2 suggests.
Gradient-TD as a saddle point. The secondary vector of Algorithm 11.7 has a clean interpretation. For fixed ,
attained at . Minimizing the is therefore a convex–concave saddle-point problem, and GTD2 is stochastic gradient descent in and ascent in on it (Exercise 11.12). Liu et al. used this view to obtain the first finite-sample bounds for Gradient-TD and accelerated variants (projected GTD2 and the mirror-prox GTD2-MP).Bo Liu, Ji Liu, Mohammad Ghavamzadeh, Sridhar Mahadevan, and Marek Petrik. Finite-Sample Analysis of Proximal Gradient TD Algorithms. In Proceedings of the Thirty-First Conference on Uncertainty in Artificial Intelligence (UAI 2015), pages 504–513, Amsterdam, 2015 For nonlinear approximators, Maei et al. had already shown that GTD2 and TDC, with the projection taken onto the tangent space of the value manifold and an extra Hessian-vector term, converge almost surely to local optima of a projected Bellman objective, at cost linear in the number of parameters.Hamid R. Maei, Csaba Szepesvári, Shalabh Bhatnagar, Doina Precup, David Silver, and Richard S. Sutton. Convergent Temporal-Difference Learning with Arbitrary Smooth Function Approximation. In Advances in Neural Information Processing Systems 22 (NIPS 2009), pages 1204–1212, 2009
Offline RL: the triad with no exploration. In offline reinforcement learning the agent must learn from a fixed dataset and can never correct its mistakes by acting. The danger moves from the state distribution to the action distribution: the Bellman target queries actions the data never contain, their values are pure extrapolation, and maximization selects exactly the overestimated ones. Conservative Q-learning (CQL) adds to the squared Bellman error a penalty that pushes values down under a policy that maximizes them and up under the data’s actions,Aviral Kumar, Aurick Zhou, George Tucker, and Sergey Levine. Conservative Q-Learning for Offline Reinforcement Learning. In Advances in Neural Information Processing Systems, volume 33, pages 1179–1191. Curran Associates, Inc., 2020
with the empirical behavior policy, and proves that the resulting policy value is a lower bound on the true one. Conservatism replaces importance correction: rather than reweight toward , it refuses to trust what never tried.
All the methods of this chapter were one-step methods. Chapter 12 unifies one-step and Monte Carlo updates through eligibility traces, and returns at its end to the off-policy question with traces: importance-sampled and tree-backup traces, and the Gradient-TD and Emphatic-TD methods of this chapter extended to .
11.11Exercises#
Exercise 11.11. In the chain of Section 11.2.2, compute the episodic on-policy distribution (start in the first state; the second is visited times on average) and verify the key-matrix test (11.3) directly: show that both column sums of are nonnegative, and find for which the uniform weighting fails it.
Solution
With (the missing mass is termination) and , normalized to , the column sums are .
Column sums of the key matrix for the on-policy weighting and for the uniform weighting.const Pchain = await wl`{{0, 1}, {0, 1 - \[Epsilon]}}`
await show`Simplify[{({\[Epsilon], 1}/(1 + \[Epsilon])) . (IdentityMatrix[2] - \[Gamma] ${Pchain}), {1/2, 1/2} . (IdentityMatrix[2] - \[Gamma] ${Pchain})}]`The on-policy sums are and , both nonnegative, as the episodic identity predicts after normalization. The uniform weighting has second column sum , negative for ; the test then gives no guarantee, and indeed the scalar turns negative at the larger threshold , where the features enter.
Exercise 11.12. Show that for fixed the function is maximized at with value . Then show that the expected GTD2 update is up to the step-size ratio, so GTD2 is gradient descent–ascent.
Solution
is strictly concave in because is positive definite; vanishes at . In two dimensions with symbolic entries:
Maximize over for a symmetric positive definite and compare with half the written with .const gS = await wl`{Subscript[g, 1], Subscript[g, 2]}`
const cS = await wl`{{Subscript[c, 11], Subscript[c, 12]}, {Subscript[c, 12], Subscript[c, 22]}}`
await show`Module[{v1, v2, sol}, sol = Solve[Thread[D[{v1, v2} . ${gS} - (1/2) {v1, v2} . ${cS} . {v1, v2}, {{v1, v2}}] == 0], {v1, v2}]; Simplify[({v1, v2} . ${gS} - (1/2) {v1, v2} . ${cS} . {v1, v2} /. First[sol]) - (1/2) ${gS} . Inverse[${cS}] . ${gS}]]`The gradients are , the expected -update divided by , and , the expected -update divided by .
Exercise 11.13. Show that on Baird’s counterexample the expected TDC dynamics are not stable for every step-size ratio: find, for , an for which of (11.10) has an eigenvalue with positive real part, and compare with GTD2 at the same .
Solution
By the scalar computation of Section 11.7, TDC needs the secondary process to be fast where has an unstable direction; so try a small .
Largest real part of the spectra of and on Baird’s problem at .const tdcSlow = await wl`ArrayFlatten[{{-${Ab}, -(${Cb} - Transpose[${Ab}])}, {-\[Eta] ${Ab}, -\[Eta] ${Cb}}}] /. {\[Gamma] -> 99/100, \[Eta] -> 1/10}`
const gtdSlow = await wl`ArrayFlatten[{{0 ${Ab}, Transpose[${Ab}]}, {-\[Eta] ${Ab}, -\[Eta] ${Cb}}}] /. {\[Gamma] -> 99/100, \[Eta] -> 1/10}`
await show`Chop[{Max[Re[N[Eigenvalues[${tdcSlow}]]]], Max[Re[N[Eigenvalues[${gtdSlow}]]]]}, 10^-10]`With TDC has an unstable mode, while GTD2’s largest real part is (only the neutral directions of the singular and ), as Theorem 11.8 predicts on the complement of the null space. This is why TDC is run with larger than (the experiments in Figure 11.1 use ).
Exercise 11.14. In the first, single-state MRP of Section 11.6 (rewards and with probability , ), and in the second, two-state one, compute and as functions of . Check that the s differ, the s coincide, and all four are minimized at , as Proposition 11.5 requires.
Solution
With the return is the next reward. In the first MRP ; in the second, the state emitting has and the other , each with . In both, is or with probability .
for the two indistinguishable MRPs.await show`Expand[{(w - 1)^2, (1/2) (w - 0)^2 + (1/2) (w - 2)^2, (1/2) (0 - w)^2 + (1/2) (2 - w)^2, (1/2) (0 - w)^2 + (1/2) (2 - w)^2}]`for all , the variance is in the first and in the second, and in both: every objective is minimized at .