Contents

Deep Reinforcement Learning Core Algorithm Notes: From the Bellman Equation and DQN to GAE, PPO, and SAC

Reinforcement Learning
#Reinforcement Learning#Bellman Equation#DQN#GAE#PPO#DPG#DDPG#TD3#SAC

0. Origin and How to Read This Note

This note comes from a screen recording, scrolled on a phone, of a Chinese review note on deep reinforcement learning (Deep Reinforcement Learning, DRL, i.e., using deep neural networks to approximate value functions or policies in reinforcement learning). The original note was compiled on 2026-10-28; its content is arranged by chapter number and runs from value functions all the way to Proximal Policy Optimization (PPO) and Soft Actor-Critic (SAC).

The scrolling order of the recording is not strictly the chapter order: the derivation and the questions and answers of the Deep Q-Network (DQN) appear first, then the Bellman equation is revisited, after which Monte Carlo, Generalized Advantage Estimation (GAE), Actor-Critic (AC), PPO, Deterministic Policy Gradient (DPG), and an algorithm comparison table follow in turn. To make the content readable, this article rearranges everything in knowledge-dependency order: first define return and value, then discuss the Bellman equation, then the three families of solution approaches (dynamic programming, Monte Carlo, temporal difference), and finally the two main lines of deep reinforcement learning—value-based methods and policy-gradient methods—and the combination of the two.

Notation conventions (used uniformly throughout the rest of the text):

SymbolMeaning
s, a, r, s′s,\ a,\ r,\ s'State (state), action (action), reward (reward), and the next state after executing the action
π(a∣s)\pi(a\mid s)Policy (policy), the probability of choosing action aa in state ss
πθ\pi_\thetaA parameterized policy controlled by parameters θ\theta (usually a neural network)
μθ(s)\mu_\theta(s)A deterministic policy that directly outputs one deterministic action
Vπ(s)V_\pi(s)State value (state value), the expected return when starting from state ss and acting according to policy π\pi
Qπ(s,a)Q_\pi(s,a)Action value (action value), the expected return when starting from state ss, first executing action aa, and afterwards acting according to π\pi
γ\gammaDiscount factor, 0≤γ<10\le\gamma<1; rewards further in the future carry less weight
α\alphaLearning rate (step size), controlling the magnitude of each parameter update
ε\varepsilonExploration rate, or the clipping range in PPO
λ\lambdaThe parameter in GAE that controls the trade-off between bias and variance
DDExperience replay buffer
θ−\theta^- or θ′\theta'Parameters of the target network

Note: the main text is dominated by the formulas, pseudocode, and questions and answers of the recorded note. So that the chapters can be connected, a few of the most basic Markov Decision Process (Markov Decision Process, MDP, the mathematical framework that describes sequential decision making with states, actions, transition probabilities, and rewards) definitions have been supplied by this article and are flagged here.

How to read this: chapters 1 to 16 go through the algorithms one by one in knowledge-dependency order; chapter 19 is a cross-sectional summary that puts all the algorithms side by side in one master table, six key divergences, and a single selection decision chain, so it suits both rereading after finishing the earlier text and direct skimming by readers who came only to ask “which algorithm should I pick” (read the master table in 19.1 first, then walk the decision chain in 19.3). Chapter 17 and chapter 18 are “Algorithm lineage and comparison of key characteristics” and “Summary of key formulas and loop strategies” respectively, and are good intermediate stops for table lookup.


1. Return, Value Functions, and Optimal Policies

1.1 Return: discounting future rewards back to the present

After step tt, the agent receives a sequence of rewards Rt+1,Rt+2,Rt+3,…R_{t+1}, R_{t+2}, R_{t+3},\dots. Accumulating this sequence with the discount factor gives the return:

Gt=Rt+1+γRt+2+γ2Rt+3+⋯=∑k=0∞γkRt+k+1G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \cdots = \sum_{k=0}^{\infty}\gamma^k R_{t+k+1}

The discount factor has two roles: first, it makes “a reward obtainable right now” worth more than “a reward obtainable only long afterwards”, which matches engineering intuition; second, it makes the return of an infinitely long episode converge mathematically.

Derivation 1: recursive form and boundedness of the discounted return

Step one: split the first term out of the sum. By the definition, split the terms directly and factor out γ\gamma:

Gt=∑k=0∞γkRt+k+1=Rt+1+γ∑k=0∞γkRt+k+2=Rt+1+γGt+1G_t=\sum_{k=0}^{\infty}\gamma^k R_{t+k+1}=R_{t+1}+\gamma\sum_{k=0}^{\infty}\gamma^k R_{t+k+2}=R_{t+1}+\gamma G_{t+1}

This step uses only “the sum can be split into terms” and “factoring out a common factor”; it is independent of the Markov property, and therefore holds for any reward sequence.

Step two: prove that the infinite sum does not diverge. Suppose the rewards are bounded, ∣Rt+k+1∣≤Rmax⁡|R_{t+k+1}|\le R_{\max}; then

∣Gt∣≤∑k=0∞γk∣Rt+k+1∣≤Rmax⁡∑k=0∞γk=Rmax⁡1−γ|G_t|\le\sum_{k=0}^{\infty}\gamma^k\left|R_{t+k+1}\right|\le R_{\max}\sum_{k=0}^{\infty}\gamma^k=\frac{R_{\max}}{1-\gamma}

For γ<1\gamma<1 the geometric series converges and the return is bounded. If γ=1\gamma=1, the upper bound degenerates to Rmax⁡⋅∞R_{\max}\cdot\infty and the return of an infinite episode may diverge—this is the mathematical reason why the discount factor must be strictly less than 1, not a matter of “that is how it is conventionally chosen”.

Step three: γ\gamma controls both “weight” and “horizon”. The weight of a reward kk steps later is γk\gamma^k, and the number of steps needed for the weight to decay to one half is k1/2=log⁡(1/2)/log⁡γk_{1/2}=\log(1/2)/\log\gamma. With γ=0.99\gamma=0.99 this is about 69 steps; with γ=0.9\gamma=0.9, about 6.6 steps. So tuning γ\gamma changes the “effective horizon length” and the “order-of-magnitude upper bound of the return” at the same time, which is why γ\gamma must be retuned whenever the task changes.

1.2 State value and action value

The state value is the expectation of the return when “standing in state ss and thereafter always acting according to policy π\pi”:

Vπ(s)=Eπ[Gt∣St=s]V_\pi(s) = \mathbb{E}_\pi\left[G_t \mid S_t = s\right]

The action value is the expectation of the return when “standing in state ss, first executing action aa, and thereafter acting according to π\pi”:

Qπ(s,a)=Eπ[Gt∣St=s, At=a]Q_\pi(s,a) = \mathbb{E}_\pi\left[G_t \mid S_t = s,\ A_t = a\right]

The relation between the two is a weighted average by the policy probabilities:

Vπ(s)=∑aπ(a∣s) Qπ(s,a)V_\pi(s) = \sum_a \pi(a\mid s)\, Q_\pi(s,a)

This sentence is worth remembering: VV is “if I have already decided to follow the policy, how much do I get on average”, while QQ is “if I first execute a particular action and then follow the policy, how much do I get on average”. VV is the weighted average of QQ over the action dimension.

Derivation 2: why $V$ is a weighted average of $Q$, and why the converse does not hold

Step one: use the law of total probability for conditional expectations. Starting from the definition of VV, treat the first action AtA_t as an extra conditioning variable:

Vπ(s)=Eπ[Gt∣St=s]=∑aπ(a∣s) Eπ[Gt∣St=s, At=a]V_\pi(s)=\mathbb{E}_\pi\left[G_t\mid S_t=s\right]=\sum_a\pi(a\mid s)\,\mathbb{E}_\pi\left[G_t\mid S_t=s,\ A_t=a\right]

The first equality is the definition of VV; the second equality is the law of total probability for conditional expectations—the randomness of “first draw an action according to the policy, then draw the subsequent trajectory according to the environment” is split into an outer sum whose weights are exactly π(a∣s)\pi(a\mid s).

Step two: recognize that the inner term is exactly QQ. The inner conditional expectation is word-for-word the definition of Qπ(s,a)Q_\pi(s,a), hence

Vπ(s)=∑aπ(a∣s) Qπ(s,a)V_\pi(s)=\sum_a\pi(a\mid s)\,Q_\pi(s,a)

Step three: why the reverse equality does not exist. In Qπ(s,a)Q_\pi(s,a) the action aa “has already been fixed”, so it carries action information; whereas Vπ(s)V_\pi(s) has already taken a weighted average over actions and erased the information of “which action was chosen”. A weighted average is an irreversible marginalization, so in general QQ cannot be recovered from VV. Only in the degenerate case where one additionally knows that “the policy at ss is deterministic” does Qπ(s,π(s))=Vπ(s)Q_\pi(s,\pi(s))=V_\pi(s) hold.

Step four: this explains the difference between the two technical routes. Learning QQ yields a policy directly through arg⁡max⁡a\arg\max_a, so the value-based control methods (Q-learning, DQN, DDPG) all learn QQ; learning VV can only evaluate “the current policy”, and improving the policy then requires knowing the environment’s transition probabilities (dynamic programming) or learning an additional QQ (the Critic in Actor-Critic).

1.3 Optimal value functions and optimal policies

The optimal state value and the optimal action value are respectively “the maximum over all policies”:

V∗(s)=max⁡πVπ(s),Q∗(s,a)=max⁡πQπ(s,a)V^*(s) = \max_\pi V_\pi(s),\qquad Q^*(s,a) = \max_\pi Q_\pi(s,a)

Once Q∗Q^* has been obtained, the optimal policy is simply

π∗(s)=arg⁡max⁡aQ∗(s,a)\pi^*(s) = \arg\max_a Q^*(s,a)

That is, once Q∗Q^* is known, the policy does not need to be learned separately—one only has to pick, in every state, the action with the largest current Q value. An optimal policy is defined as one that makes the VV of every state maximal, not one that makes only a single state maximal.

1.4 The two technical routes

Two main lines branch off from here:

  • Value-based methods: first learn VV or QQ, then derive the policy from the value. Dynamic Programming (DP), Monte Carlo (MC), Temporal Difference (TD), Q-learning, and DQN all belong to this class.
  • Policy-gradient methods: bypass arg⁡max⁡\arg\max and directly optimize the policy πθ(a∣s)\pi_\theta(a\mid s) with parameters θ\theta so that the expected return J(θ)J(\theta) grows. REINFORCE, PPO, and others belong to this class.

The two lines later merge under the Actor-Critic framework: the Actor is responsible for the policy, the Critic is responsible for the value, and the value acts as the “referee” of the policy update.


2. The Bellman Equation: Folding the Future Back into the Present

2.1 Expectation form

Split the return GtG_t into the first reward and the remainder:

Gt=Rt+1+γ(Rt+2+γRt+3+⋯ )=Rt+1+γGt+1G_t = R_{t+1} + \gamma\left(R_{t+2} + \gamma R_{t+3} + \cdots\right) = R_{t+1} + \gamma G_{t+1}

Taking the expectation of both sides, using the linearity of expectation together with the Markov property (the future depends only on the current state and not on earlier history), gives the Bellman equation for the state value:

Vπ(s)=Eπ[Rt+1+γVπ(St+1)∣St=s]V_\pi(s) = \mathbb{E}_\pi\left[R_{t+1} + \gamma V_\pi(S_{t+1}) \mid S_t = s\right]

Expanding it into a double sum over actions and over next states:

Vπ(s)=∑aπ(a∣s)∑s′P(s′∣s,a)[R(s,a,s′)+γVπ(s′)]V_\pi(s) = \sum_a \pi(a\mid s)\sum_{s'} P(s'\mid s,a)\left[R(s,a,s') + \gamma V_\pi(s')\right]

The action value works the same way, except that in the first sum “weighting by the policy” is replaced by “the action is already fixed to aa”:

Qπ(s,a)=∑s′P(s′∣s,a)[R(s,a,s′)+γ∑a′π(a′∣s′) Qπ(s′,a′)]Q_\pi(s,a) = \sum_{s'} P(s'\mid s,a)\left[R(s,a,s') + \gamma \sum_{a'}\pi(a'\mid s')\,Q_\pi(s',a')\right]

The meaning of these two equations is: the value of a state equals “the reward received immediately” plus “the discounted expectation of the value of the next state”. It turns an infinitely long sum into a recursion that depends only on the next state.

Derivation 3: from $G_t=R_{t+1}+\gamma G_{t+1}$ to the Bellman expectation equation (including which step uses the Markov property)

Step one: take the conditional expectation of the recursion and split terms by linearity.

Vπ(s)=Eπ[Gt∣St=s]=Eπ[Rt+1∣St=s]+γ Eπ[Gt+1∣St=s]V_\pi(s)=\mathbb{E}_\pi\left[G_t\mid S_t=s\right]=\mathbb{E}_\pi\left[R_{t+1}\mid S_t=s\right]+\gamma\,\mathbb{E}_\pi\left[G_{t+1}\mid S_t=s\right]

Step two: the first term is the expectation of the immediate reward; use the law of total probability twice. First draw the action according to the policy, then draw the next state according to the transition probabilities:

Eπ[Rt+1∣St=s]=∑aπ(a∣s)∑s′P(s′∣s,a) R(s,a,s′)\mathbb{E}_\pi\left[R_{t+1}\mid S_t=s\right]=\sum_a\pi(a\mid s)\sum_{s'}P(s'\mid s,a)\,R(s,a,s')

Step three: the second term is the key one, and this is where the Markov property enters. Refine the conditioning step by step:

Eπ[Gt+1∣St=s]=∑aπ(a∣s)∑s′P(s′∣s,a) Eπ[Gt+1∣St=s,At=a,St+1=s′]\mathbb{E}_\pi\left[G_{t+1}\mid S_t=s\right]=\sum_a\pi(a\mid s)\sum_{s'}P(s'\mid s,a)\,\mathbb{E}_\pi\left[G_{t+1}\mid S_t=s,A_t=a,S_{t+1}=s'\right]

Then, by the Markov property, “given St+1=s′S_{t+1}=s', the earlier history (s,a)(s,a) has no influence on the conditional distribution of the future”, so

Eπ[Gt+1∣St=s,At=a,St+1=s′]=Eπ[Gt+1∣St+1=s′]=Vπ(s′)\mathbb{E}_\pi\left[G_{t+1}\mid S_t=s,A_t=a,S_{t+1}=s'\right]=\mathbb{E}_\pi\left[G_{t+1}\mid S_{t+1}=s'\right]=V_\pi(s')

This step is the only place in the whole derivation that uses the Markov property. If the environment is non-Markov (for instance partially observable, or the history influences the future), this equality fails and the Bellman equation fails with it—which is also why partially observable problems must first supplement the observation into a belief state before the Bellman equation can be applied.

Step four: put the pieces together and factor out the common factor.

Vπ(s)=∑aπ(a∣s)∑s′P(s′∣s,a)[R(s,a,s′)+γVπ(s′)]V_\pi(s)=\sum_a\pi(a\mid s)\sum_{s'}P(s'\mid s,a)\left[R(s,a,s')+\gamma V_\pi(s')\right]

Pulling γ\gamma outside the inner sum is legitimate because γ\gamma depends on neither aa nor s′s'.

Step five: the action-value version. The action is already fixed, so the outer level is no longer weighted by π\pi; but the randomness of “afterwards still acting according to π\pi” remains, so the actions of the next state must be weighted by π\pi:

Qπ(s,a)=∑s′P(s′∣s,a)[R(s,a,s′)+γ∑a′π(a′∣s′) Qπ(s′,a′)]Q_\pi(s,a)=\sum_{s'}P(s'\mid s,a)\left[R(s,a,s')+\gamma\sum_{a'}\pi(a'\mid s')\,Q_\pi(s',a')\right]

Replacing the innermost level with the definition of Vπ(s′)V_\pi(s') (1.2) gives a form structurally identical to the VV version:

Qπ(s,a)=∑s′P(s′∣s,a)[R(s,a,s′)+γVπ(s′)]Q_\pi(s,a)=\sum_{s'}P(s'\mid s,a)\left[R(s,a,s')+\gamma V_\pi(s')\right]

Step six: division of roles between the two equations. The VV equation hands “action selection” to the policy π\pi, so it suits policy evaluation; the QQ equation fixes the action on the left-hand side, so it suits control (because taking arg⁡max⁡\arg\max over QQ already improves the policy). Dynamic programming uses both versions at once: policy evaluation uses the VV version, policy improvement uses the QQ version (see 3.3 and 3.4).

2.2 Optimal form

Replacing “weighted average by the policy probabilities” with “take the maximum” gives the Bellman optimality equation:

V∗(s)=max⁡a∑s′P(s′∣s,a)[R(s,a,s′)+γV∗(s′)]V^*(s) = \max_a \sum_{s'} P(s'\mid s,a)\left[R(s,a,s') + \gamma V^*(s')\right] Q∗(s,a)=∑s′P(s′∣s,a)[R(s,a,s′)+γmax⁡a′Q∗(s′,a′)]Q^*(s,a) = \sum_{s'} P(s'\mid s,a)\left[R(s,a,s') + \gamma \max_{a'} Q^*(s',a')\right]

The Q-learning update is a sampled approximation of this optimality equation: one real transition (s,a,r,s′)(s,a,r,s') replaces the sum over P(s′∣s,a)P(s'\mid s,a), and the current estimate replaces the true optimal value.

Derivation 4: why the optimality equation contains $\max$, and how the $V^*$ and $Q^*$ versions derive each other

Step one: the optimal value is “the maximum over policies”, and the policy only affects the weighting coefficients. From Vπ(s)=∑aπ(a∣s)Qπ(s,a)V_\pi(s)=\sum_a\pi(a\mid s)Q_\pi(s,a), for any policy,

Vπ(s)=∑aπ(a∣s)Qπ(s,a)≤max⁡aQπ(s,a)V_\pi(s)=\sum_a\pi(a\mid s)Q_\pi(s,a)\le\max_a Q_\pi(s,a)

because a weighted average cannot exceed the maximum of the averaged items. Equality is attained when “the policy puts all probability on the action with the largest current QQ”. Hence, for each fixed state, the optimal policy is simply the arg⁡max⁡\arg\max, and

V∗(s)=max⁡πVπ(s)=max⁡aQ∗(s,a)V^*(s)=\max_\pi V_\pi(s)=\max_a Q^*(s,a)

Step two: take the maximum over policies of the Bellman expectation equation for QQ. In the expression for QπQ_\pi, the dependence on π\pi appears only in the inner term γ∑a′π(a′∣s′)Qπ(s′,a′)\gamma\sum_{a'}\pi(a'\mid s')Q_\pi(s',a'). Taking the maximum over π\pi amounts to taking, independently for each next state s′s', the maximum over actions:

max⁡π∑a′π(a′∣s′)Qπ(s′,a′)=max⁡a′Qπ(s′,a′)\max_\pi\sum_{a'}\pi(a'\mid s')Q_\pi(s',a')=\max_{a'}Q_\pi(s',a')

Being able to push the max⁡\max inside the sum relies on two facts: the weights P(s′∣s,a)P(s'\mid s,a) are nonnegative and independent of π\pi; and the maximization over each s′s' can be carried out independently (one and the same π\pi may choose a different greedy action in different states, which is not a conflict). Hence

Q∗(s,a)=∑s′P(s′∣s,a)[R(s,a,s′)+γmax⁡a′Q∗(s′,a′)]Q^*(s,a)=\sum_{s'}P(s'\mid s,a)\left[R(s,a,s')+\gamma\max_{a'}Q^*(s',a')\right]

Step three: substitute V∗(s)=max⁡aQ∗(s,a)V^*(s)=\max_a Q^*(s,a) to obtain the VV version. Note that max⁡a\max_a must stay outside the sum:

V∗(s)=max⁡a∑s′P(s′∣s,a)[R(s,a,s′)+γV∗(s′)]V^*(s)=\max_a\sum_{s'}P(s'\mid s,a)\left[R(s,a,s')+\gamma V^*(s')\right]

The order cannot be swapped: first fix the action, then sum over next states, and finally take the maximum over actions. This is exactly the opposite of the expectation form’s “first weight by the policy, then sum over actions”, and it is the only structural difference between “optimal” and “expectation”.

Step four: why the fixed point exists and is unique. Define the Bellman optimality operator

(T∗V)(s)=max⁡a∑s′P(s′∣s,a)[R(s,a,s′)+γV(s′)](\mathcal{T}^*V)(s)=\max_a\sum_{s'}P(s'\mid s,a)\left[R(s,a,s')+\gamma V(s')\right]

max⁡\max is 1-Lipschitz (∣max⁡axa−max⁡aya∣≤max⁡a∣xa−ya∣|\max_a x_a-\max_a y_a|\le\max_a|x_a-y_a|), and together with the weighted average over transition probabilities this yields

∥T∗U−T∗V∥∞≤γ∥U−V∥∞\Vert\mathcal{T}^*U-\mathcal{T}^*V\Vert_\infty\le\gamma\Vert U-V\Vert_\infty

that is, T∗\mathcal{T}^* is also a γ\gamma-contraction. By the Banach fixed-point theorem it has a unique fixed point V∗V^*, and iterating from an arbitrary initial value converges—which is precisely the basis on which value iteration (3.4) rests.

2.3 Why using max⁡\max in the target yields an “off-policy” algorithm

The target of Q-learning is to converge to the optimal action value Q∗Q^*, so the target uses max⁡a′\max_{a'} rather than “the weighted average by the probabilities of the current policy”. This allows the learned policy and the sampling policy to differ:

  • sampling uses ε\varepsilon-greedy (ε\varepsilon-greedy, choosing the current best action with probability 1−ε1-\varepsilon and a random action with probability ε\varepsilon) to guarantee exploration;
  • the learning target, however, is always “the optimal one”, independent of the sampling policy.

Algorithms in which the “behavior policy” and the “target policy” differ are called off-policy algorithms. By contrast, on-policy algorithms can only use data just collected by the current policy.


3. Dynamic Programming: Policy Evaluation and Policy Iteration

3.1 Policy evaluation

Policy evaluation (policy evaluation) has to answer the question: given policy π\pi, find VπV_\pi. The method is to apply the Bellman expectation equation repeatedly, substituting the old value estimate to compute a new value estimate:

Vk+1(s)=∑aπ(a∣s)∑s′P(s′∣s,a)[R(s,a,s′)+γVk(s′)]V_{k+1}(s) = \sum_a \pi(a\mid s)\sum_{s'} P(s'\mid s,a)\left[R(s,a,s') + \gamma V_k(s')\right]

This iteration is called iterative policy evaluation (iterative policy evaluation). It has two important points:

  1. Synchronous update: the (k+1)(k+1)-th round uses the entire value table of the kk-th round and must not overwrite values while computing them; otherwise the convergence analysis becomes more complicated.
  2. Each round takes Vk(s′)V_k(s') as the estimate of the next state’s value; there is no need to wait for the episode to end, and no real sampling is needed—because dynamic programming assumes that the complete transition probabilities P(s′∣s,a)P(s'\mid s,a) are known.
Derivation 5: why policy evaluation always converges ($\gamma$-contraction and fixed point)

Step one: write the iteration in operator form. Define the Bellman expectation operator Tπ\mathcal{T}^\pi:

(TπV)(s)=∑aπ(a∣s)∑s′P(s′∣s,a)[R(s,a,s′)+γV(s′)](\mathcal{T}^\pi V)(s)=\sum_a\pi(a\mid s)\sum_{s'}P(s'\mid s,a)\left[R(s,a,s')+\gamma V(s')\right]

Policy evaluation is simply repeatedly doing Vk+1=TπVkV_{k+1}=\mathcal{T}^\pi V_k.

Step two: prove that it is a γ\gamma-contraction in the infinity norm. Take any two value tables U,VU,V; for each state ss:

∣(TπU)(s)−(TπV)(s)∣=∣γ∑aπ(a∣s)∑s′P(s′∣s,a)[U(s′)−V(s′)]∣\left|(\mathcal{T}^\pi U)(s)-(\mathcal{T}^\pi V)(s)\right|=\left|\gamma\sum_a\pi(a\mid s)\sum_{s'}P(s'\mid s,a)\left[U(s')-V(s')\right]\right| ≤γ∑aπ(a∣s)∑s′P(s′∣s,a)∣U(s′)−V(s′)∣≤γ∥U−V∥∞\le\gamma\sum_a\pi(a\mid s)\sum_{s'}P(s'\mid s,a)\left|U(s')-V(s')\right|\le\gamma\Vert U-V\Vert_\infty

The first inequality is the triangle inequality; the second uses ∑aπ=1\sum_a\pi=1, ∑s′P=1\sum_{s'}P=1, and the fact that each absolute value is at most ∥U−V∥∞\Vert U-V\Vert_\infty. Taking the maximum over all ss gives

∥TπU−TπV∥∞≤γ∥U−V∥∞\Vert\mathcal{T}^\pi U-\mathcal{T}^\pi V\Vert_\infty\le\gamma\Vert U-V\Vert_\infty

Step three: the contraction property directly yields a geometric convergence rate. Since VπV_\pi is a fixed point of Tπ\mathcal{T}^\pi (it satisfies the Bellman equation), substituting repeatedly into the contraction inequality:

∥Vk−Vπ∥∞=∥TπVk−1−TπVπ∥∞≤γ∥Vk−1−Vπ∥∞≤γk∥V0−Vπ∥∞\Vert V_k-V_\pi\Vert_\infty=\Vert\mathcal{T}^\pi V_{k-1}-\mathcal{T}^\pi V_\pi\Vert_\infty\le\gamma\Vert V_{k-1}-V_\pi\Vert_\infty\le\gamma^k\Vert V_0-V_\pi\Vert_\infty

So the error shrinks by at least a factor of γ\gamma every round; the convergence rate does not depend on the initial value and is determined only by γ\gamma.

Step four: the necessary condition for convergence and its engineering meaning. The contraction property requires γ<1\gamma<1; the closer γ\gamma is to 1, the slower the convergence (with γ=0.99\gamma=0.99 it takes about log⁡(1/ϵ)/log⁡(1/γ)≈100log⁡(1/ϵ)\log(1/\epsilon)/\log(1/\gamma)\approx100\log(1/\epsilon) rounds to push the error down to order ϵ\epsilon). This is the mathematical root of why long-horizon tasks need more iterations and are harder to train. Note that this conclusion holds only for a fixed policy: the operator contains no max⁡\max; value iteration inserts the max⁡\max and the contraction property still holds (see step four of 2.2), but the fixed point becomes V∗V^*.

3.2 Pseudocode: policy evaluation

Input: policy π, discount factor γ, transition probabilities P, rewards R, threshold θ
Initialize: for all s, V(s) ← 0

Loop:
    Δ ← 0
    For each state s:
        v ← V(s)
        V(s) ← Σ_a π(a|s) Σ_{s'} P(s'|s,a)[R(s,a,s') + γ V(s')]
        Δ ← max(Δ, |v − V(s)|)
    Until Δ < θ (converged)

Output: V ≈ V_π

Here Δ\Delta records the largest change of the value table in this round, and Δ<θ\Delta<\theta means that the value table has essentially stopped moving.

3.3 Pseudocode: policy iteration

Policy iteration (policy iteration) is the loop of “evaluation—improvement”:

1. Initialize: for each s, set π(s) ∈ A randomly; for each s, V(s) ← 0
2. Policy evaluation:
   Loop (update V with the policy-evaluation formula above) until V converges
3. Policy improvement:
   policy_stable ← true
   For each state s:
       old_action ← π(s)
       π(s) ← argmax_a Σ_{s'} P(s'|s,a)[R(s,a,s') + γ V(s')]
       If old_action ≠ π(s), then policy_stable ← false
4. If policy_stable is true, stop and return π ≈ π*; otherwise go back to step 2

3.4 The policy improvement theorem

The policy improvement theorem (policy improvement theorem) says: if a greedy action is taken in every state according to the current value function, the resulting new policy is no worse than the old one. Formally, if

π′(s)=arg⁡max⁡aQπ(s,a)\pi'(s) = \arg\max_a Q_\pi(s,a)

then for every state ss, Vπ′(s)≥Vπ(s)V_{\pi'}(s)\ge V_\pi(s). This theorem guarantees that “policy iteration” does not get worse with each improvement, and also that the practice in “value iteration” of “taking the max while updating the value” is safe.

Derivation 6: complete proof of the policy improvement theorem (including why all states must be greedy simultaneously)

Step one: first prove the lemma that “one step of greed is no worse”. Let π′(s)=arg⁡max⁡aQπ(s,a)\pi'(s)=\arg\max_a Q_\pi(s,a); then by the VV–QQ relation of 1.2:

Qπ(s,π′(s))=max⁡aQπ(s,a)≥Qπ(s,π(s))=∑aπ(a∣s)Qπ(s,a)=Vπ(s)Q_\pi\left(s,\pi'(s)\right)=\max_a Q_\pi(s,a)\ge Q_\pi\left(s,\pi(s)\right)=\sum_a\pi(a\mid s)Q_\pi(s,a)=V_\pi(s)

The meaning is: under the same QπQ_\pi, the greedy action chosen from QQ has a value no lower than the weighted average value of the original policy. Equality holds if and only if π\pi at ss places probability only on the action with the largest QQ.

Step two: unroll this inequality step by step along the trajectory. Unroll once in TD form:

Vπ(s)≤Qπ(s,π′(s))=Eπ′[Rt+1+γVπ(St+1)∣St=s]V_\pi(s)\le Q_\pi\left(s,\pi'(s)\right)=\mathbb{E}_{\pi'}\left[R_{t+1}+\gamma V_\pi(S_{t+1})\mid S_t=s\right]

Note that the expectation subscript has already changed to π′\pi' (actions are sampled from the new policy), but the value being compared is still the old policy’s VπV_\pi—this step compares the two policies’ values at the same state, rather than substituting Vπ′V_{\pi'} in advance. Then apply the lemma of step one to St+1S_{t+1} (the “new policy” is still the same π′\pi'):

≤Eπ′[Rt+1+γQπ(St+1,π′(St+1))∣St=s]\le\mathbb{E}_{\pi'}\left[R_{t+1}+\gamma Q_\pi\left(S_{t+1},\pi'(S_{t+1})\right)\mid S_t=s\right]

Continuing the unrolling for nn steps, using the same inequality once per step:

≤Eπ′[∑k=0n−1γkRt+k+1+γnVπ(St+n)∣St=s]\le\mathbb{E}_{\pi'}\left[\sum_{k=0}^{n-1}\gamma^kR_{t+k+1}+\gamma^nV_\pi(S_{t+n})\mid S_t=s\right]

Step three: let n→∞n\to\infty to obtain the conclusion. By the boundedness of 1.1, ∣Vπ∣≤Rmax⁡/(1−γ)|V_\pi|\le R_{\max}/(1-\gamma), the tail term γnVπ(St+n)→0\gamma^nV_\pi(S_{t+n})\to0, hence

Vπ(s)≤Eπ′[∑k=0∞γkRt+k+1∣St=s]=Vπ′(s)V_\pi(s)\le\mathbb{E}_{\pi'}\left[\sum_{k=0}^{\infty}\gamma^kR_{t+k+1}\mid S_t=s\right]=V_{\pi'}(s)

Step four: why “every state must be greedy”. Every step of the unrolling chain requires Qπ(s,π′(s))≥Vπ(s)Q_\pi\left(s,\pi'(s)\right)\ge V_\pi(s) to hold at the state actually reached. If only some states are greedy while the rest keep their old actions, then upon reaching a state that keeps its old action the inequality may become an equality or even reverse, the chain breaks there, and the conclusion fails. Hence the premise of the theorem is “take greed uniformly in all states”, not “pick a few states and change them”.

Step five: the equality condition and finite-step convergence. If every state satisfies Qπ(s,π′(s))=Vπ(s)Q_\pi\left(s,\pi'(s)\right)=V_\pi(s), then Vπ′=VπV_{\pi'}=V_\pi, which means the greedy policy and the old policy are equivalent at that state; at that point the Bellman optimality equation is already satisfied and π′\pi' is the optimal policy. If at least one state is strictly unequal, then Vπ′V_{\pi'} is strictly larger at that state. In the tabular case the policy space is finite, and every strict improvement makes the value strictly increase, so an infinite loop is impossible; policy iteration therefore terminates at π∗\pi^* within finitely many steps.

Value iteration (value iteration) merges evaluation and improvement into one step:

Vk+1(s)=max⁡a∑s′P(s′∣s,a)[R(s,a,s′)+γVk(s′)]V_{k+1}(s) = \max_a \sum_{s'} P(s'\mid s,a)\left[R(s,a,s') + \gamma V_k(s')\right]
Derivation 7: why value iteration equals "one round of evaluation plus one round of improvement", and why its limit satisfies the optimality equation

Step one: write one round of iteration as “improve first, then evaluate once”. From the current VkV_k, define the greedy policy and its action value:

πk+1(s)=arg⁡max⁡aQVk(s,a),QVk(s,a)=∑s′P(s′∣s,a)[R(s,a,s′)+γVk(s′)]\pi_{k+1}(s)=\arg\max_a Q_{V_k}(s,a),\qquad Q_{V_k}(s,a)=\sum_{s'}P(s'\mid s,a)\left[R(s,a,s')+\gamma V_k(s')\right]

Perform only one round of policy evaluation for πk+1\pi_{k+1}:

Vk+1(s)=∑s′P(s′∣s,πk+1(s))[R(s,a,s′)+γVk(s′)]V_{k+1}(s)=\sum_{s'}P\left(s'\mid s,\pi_{k+1}(s)\right)\left[R(s,a,s')+\gamma V_k(s')\right]

Step two: rewrite “summing under the greedy policy” as a max⁡\max. Because πk+1\pi_{k+1} is a deterministic policy, the outer sum over s′s' leaves only a single action, so

∑s′P(s′∣s,πk+1(s))[⋯ ]=max⁡a∑s′P(s′∣s,a)[⋯ ]\sum_{s'}P\left(s'\mid s,\pi_{k+1}(s)\right)\left[\cdots\right]=\max_a\sum_{s'}P(s'\mid s,a)\left[\cdots\right]

This is an identity, not an approximation: the action selected by max⁡\max is exactly πk+1(s)\pi_{k+1}(s). The value iteration formula in the main text follows.

Step three: if the iteration converges, the limit must satisfy the optimality equation. Suppose Vk→V∞V_k\to V_\infty; take the limit of both sides of the equation above:

V∞(s)=max⁡a∑s′P(s′∣s,a)[R(s,a,s′)+γV∞(s′)]V_\infty(s)=\max_a\sum_{s'}P(s'\mid s,a)\left[R(s,a,s')+\gamma V_\infty(s')\right]

The right-hand side is exactly the result of applying the Bellman optimality operator T∗\mathcal{T}^*, so V∞V_\infty is a fixed point of T∗\mathcal{T}^*; by the contraction property and uniqueness in step four of 2.2, V∞=V∗V_\infty=V^*.

Step four: why evaluation need not be carried to convergence. Policy iteration requires the inner evaluation to converge sufficiently (possibly tens or hundreds of rounds), whereas value iteration evaluates for merely one round and then improves immediately. Convergence is unaffected because T∗\mathcal{T}^* as a whole is still a γ\gamma-contraction: every round guarantees that the error shrinks by a factor of γ\gamma, only “the path taken each round” differs. This is why value iteration costs less computation, and why it is the direct precursor of Q-learning—replacing the max⁡\max and the sum by sampling yields the Q-learning update.

It does not need to drive policy evaluation to full convergence every round, costs less computation, and is the direct precursor of Q-learning.

The three preconditions of dynamic programming: the model is known (PP and RR), the state space can be enumerated, and every round must sweep all states. Real problems usually violate all three, which motivates the two “model-free” methods below.


4. Monte Carlo: Using the True Return of Complete Episodes

4.1 Basic idea

Monte Carlo (Monte Carlo, MC, using random sampling to estimate expectations) needs no transition probabilities; it needs only the experience of complete episodes (episodes). It estimates values in the most naive way:

V(St)←average(Returns(St))V(S_t) \leftarrow \text{average}\left(\text{Returns}(S_t)\right)

That is: collect all the returns GtG_t that were actually obtained after state StS_t in history, take the average, and use it as the estimate of V(St)V(S_t). The more samples, the closer the average is to the true expectation.

Derivation 8: why the sample mean is unbiased, and why the error decreases as $1/\sqrt{n}$

Step one: the expectation of the sample mean equals the true value. Suppose nn return samples G(1),…,G(n)G^{(1)},\dots,G^{(n)} are collected for state ss; they are mutually independent and each satisfies E[G(i)]=Vπ(s)\mathbb{E}\left[G^{(i)}\right]=V_\pi(s) (because the sampling process of every episode is identically distributed). By the linearity of expectation:

E[1n∑i=1nG(i)]=1n∑i=1nE[G(i)]=Vπ(s)\mathbb{E}\left[\frac{1}{n}\sum_{i=1}^{n}G^{(i)}\right]=\frac{1}{n}\sum_{i=1}^{n}\mathbb{E}\left[G^{(i)}\right]=V_\pi(s)

This shows that the estimate is unbiased, regardless of how large nn is—even a single episode is correct in expectation.

Step two: the variance decreases as 1/n1/n. Independence makes every covariance term zero:

Var[1n∑i=1nG(i)]=1n2∑i=1nVar[G(i)]=σ2n\mathrm{Var}\left[\frac{1}{n}\sum_{i=1}^{n}G^{(i)}\right]=\frac{1}{n^2}\sum_{i=1}^{n}\mathrm{Var}\left[G^{(i)}\right]=\frac{\sigma^2}{n}

The standard deviation is therefore σ/n\sigma/\sqrt{n}: to halve the error, the number of samples must be quadrupled. This is the quantitative root of the low sample efficiency of Monte Carlo.

Step three: how large is the variance of a single return itself. Expanding Gt=∑k=0∞γkRt+k+1G_t=\sum_{k=0}^{\infty}\gamma^kR_{t+k+1}, if the rewards at each step are independent with common variance σR2\sigma_R^2:

Var[Gt]=σR2∑k=0∞γ2k=σR21−γ2\mathrm{Var}\left[G_t\right]=\sigma_R^2\sum_{k=0}^{\infty}\gamma^{2k}=\frac{\sigma_R^2}{1-\gamma^2}

With γ=0.99\gamma=0.99 this is about a 50-fold amplification. The longer the episode and the closer the discount is to 1, the larger the variance of a single sample and the more samples are needed. This explains “MC is unbiased but has large variance”—the unbiasedness comes from step one, the large variance from the long sum in step three.

Step four: unbiased does not mean low error. The mean squared error of the estimate decomposes as

MSE=Bias2+Var=σ2n\mathrm{MSE}=\mathrm{Bias}^2+\mathrm{Var}=\frac{\sigma^2}{n}

When the bias is zero, the MSE is entirely determined by the variance. So “unbiased” is only a necessary condition for a good estimate: with a fixed sample budget, a slightly biased estimate with very small variance (such as TD) may have a smaller error. This is precisely the bias-variance trade-off discussed in chapters 5 and 9.

4.2 First-visit and every-visit variants

Within one episode, a state may be visited several times. There are then two conventions:

  • First-visit MC (first-visit MC): within one episode, only the return of the first visit to that state is added to the statistics;
  • Every-visit MC (every-visit MC): within one episode, the return of every visit to that state is added to the statistics.

A concrete example: in a certain episode, state ss is visited at t=1t=1, t=3t=3, and t=5t=5, with corresponding returns G1=4G_1=4, G3=8G_3=8, and G5=6G_5=6.

  • First-visit: Returns(s) = [4], so V(s)=4V(s)=4;
  • Every-visit: Returns(s) = [4, 8, 6], so V(s)=(4+8+6)/3=6V(s)=(4+8+6)/3=6.

Both converge to the same target (both Vπ(s)V_\pi(s)); the difference lies in how the samples are used.

4.3 Computing backwards: obtaining the return of any time step in O(1)O(1)

There is a trick in the implementation of Monte Carlo that is easy to overlook but crucial: the return is accumulated backwards from the end of the episode.

For t = T−1, T−2, …, 0 (traverse backwards, accumulating the return step by step):
    G ← γG + R_{t+1}
    If S_t has not appeared in S_0, …, S_{t−1} (first-visit check):
        Append G to Returns(S_t)
        V(S_t) ← average(Returns(S_t))

Why compute backwards? Because the return satisfies the recursion

Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1}

Starting from the end, each step backwards needs only one multiply-add to obtain the return of that time step. Computing forwards would require re-summing all later rewards at every time step, with complexity O(T2)O(T^2); computing backwards is O(T)O(T).

Derivation 9: why backward recursion reduces $O(T^2)$ to $O(T)$

Step one: the cost of recomputing by definition in forward order. If at each time step tt one sums directly by definition:

Gt=∑k=0T−t−1γkRt+k+1G_t=\sum_{k=0}^{T-t-1}\gamma^kR_{t+k+1}

then the tt-th time step requires computing T−tT-t terms, and the total amount of computation is

∑t=0T−1(T−t)=T(T+1)2=O(T2)\sum_{t=0}^{T-1}(T-t)=\frac{T(T+1)}{2}=O(T^2)

Step two: backward recursion needs only one multiply-add. From the recursion Gt=Rt+1+γGt+1G_t=R_{t+1}+\gamma G_{t+1}, starting at the end:

GT−1=RT+γGT=RT,GT−2=RT−1+γGT−1,…G_{T-1}=R_T+\gamma G_T=R_T,\qquad G_{T-2}=R_{T-1}+\gamma G_{T-1},\quad\dots

Each step backwards performs only “one multiplication and one addition”, for TT operations in total, i.e., O(T)O(T).

Step three: the base case of the recursion must be GT=0G_T=0. The episode terminates at time TT and there are no rewards afterwards, so GT≡0G_T\equiv0; substituting into the recursion gives GT−1=RTG_{T-1}=R_T, consistent with the definition. If the base case were written as something else (for example bootstrapping with V(ST)V(S_T)), it would no longer be Monte Carlo but TD—which is exactly the starting point of chapter 5.

Step four: why this structure also determines “must wait for the episode to end”. Backward recursion requires the complete reward sequence first, so MC can only update after the episode ends; whereas TD replaces the remainder term with V(St+1)V(S_{t+1}) and can therefore update at every step. The implementation difference between the two (offline vs online) comes directly from whether this step bootstraps.

The “first-visit” check also relies on backward traversal: first generate the complete episode, then walk backwards, using “whether this state appeared at an earlier time step” to decide whether the current visit is the first one. Walking forwards, one cannot know in advance whether the state will be visited again later.

4.4 Why the first-visit variant is more common

Both conventions are unbiased, but the first-visit variant is more common in practice, for two reasons:

  1. Theoretical analysis is simpler: the return samples that first-visit MC collects for each state are statistically independent of one another and satisfy the independent and identically distributed (i.i.d., mutually independent and identically distributed) assumption, which makes it convenient to prove convergence and give variance bounds; the samples of the every-visit variant are correlated, and the analysis needs several more layers.
  2. Smaller variance: multiple visits to the same state within one episode are highly correlated, and including them all does not bring an equivalent amount of new information, but rather increases the variance of the estimate.

4.5 Pseudocode: every-visit MC

Identical to the first-visit variant, except that the "first-visit" check is removed:

For t = T−1, T−2, …, 0:
    G ← γG + R_{t+1}
    Append G to Returns(S_t)        # no check for first visit
    V(S_t) ← average(Returns(S_t))

4.6 What “append GG to Returns” actually does

This step is often misread; in fact it involves only three things:

  • Returns(S_t) is the list of historical return samples of state StS_t. Each time an episode is completed, the return GG corresponding to each state visited in that episode is appended.
  • Append G to Returns(S_t) is exactly sample collection. GG is “the true discounted return obtained from StS_t in this episode”; it is a random sample, not an estimated value.
  • V(S_t) ← average(Returns(S_t)) is exactly updating the value estimate: take the average of all historical sample returns of that state; the more samples, the closer the average to the true expectation—this is precisely “approximating an expectation by a sample mean”.

One more common question: if a state is visited several times in one episode (say at t=1,3,5t=1,3,5), should GG be appended to Returns at every visit? That depends on the convention: every-visit appends three times, first-visit appends only the first one. Both are legitimate estimates, only their statistical properties differ.


5. Temporal Difference TD(0): Update After a Single Step

5.1 Taking half from DP and half from MC

Temporal Difference (Temporal Difference, TD, using the difference between value estimates at adjacent time steps as the update signal) combines the bootstrapping idea of dynamic programming (bootstrap, using an existing estimate to update another estimate) with the sampling idea of Monte Carlo:

  • like MC, it needs no environment model;
  • like DP, it does not need to wait for the episode to end; after every step it can update the current value using “the current reward plus the current value estimate of the successor state”.

The update amount of TD comes from the TD error (TD error):

δt=Rt+1+γV(St+1)−V(St)\delta_t = R_{t+1} + \gamma V(S_{t+1}) - V(S_t)

Here Rt+1+γV(St+1)R_{t+1}+\gamma V(S_{t+1}) is called the TD target (TD target): it uses the actual one-step reward plus the estimated value of the successor state to assemble a “pseudo return”.

Derivation 10: why the TD target is a "one-step truncated return", and where the bias and the variance each come from

Step one: split the true return into “one step plus a remainder”. From the recursion in 1.1:

Gt=Rt+1+γGt+1G_t=R_{t+1}+\gamma G_{t+1}

What the TD target does is to replace the unknown remainder Gt+1G_{t+1} by its expected estimate V(St+1)V(S_{t+1}):

Gt≈Rt+1+γV(St+1)G_t\approx R_{t+1}+\gamma V(S_{t+1})

This replacement is the only dividing line between TD and MC: MC keeps unrolling until the episode ends, whereas TD truncates here and bootstraps (bootstrap, substituting its own estimate for the unknown true value).

Step two: where the bias comes from. Take the conditional expectation of the target:

E[Rt+1+γV(St+1)∣St=s]=∑aπ(a∣s)∑s′P(s′∣s,a)[R(s,a,s′)+γV(s′)]\mathbb{E}\left[R_{t+1}+\gamma V(S_{t+1})\mid S_t=s\right]=\sum_a\pi(a\mid s)\sum_{s'}P(s'\mid s,a)\left[R(s,a,s')+\gamma V(s')\right]

The right-hand side is exactly the Bellman operator Tπ\mathcal{T}^\pi applied to VV. It equals Vπ(s)V_\pi(s) precisely only when V=VπV=V_\pi; otherwise the bias is

Bias=γ E[V(St+1)−Vπ(St+1)∣St=s]\text{Bias}=\gamma\,\mathbb{E}\left[V(S_{t+1})-V_\pi(S_{t+1})\mid S_t=s\right]

that is, the discounted expectation of the “next state’s estimation error”. Note that the bias is not averaged away by sampling—it is a systematic error that propagates along the trajectory through bootstrapping.

Step three: why the variance is small. The TD target contains only one random reward and one state transition:

Var[Rt+1+γV(St+1)]=σR2+γ2Var[V(St+1)]\mathrm{Var}\left[R_{t+1}+\gamma V(S_{t+1})\right]=\sigma_R^2+\gamma^2\mathrm{Var}\left[V(S_{t+1})\right]

whereas by step three of 4.1 the variance of GtG_t is σR2/(1−γ2)\sigma_R^2/(1-\gamma^2). Take γ=0.99\gamma=0.99: the former is about 11 times σR2\sigma_R^2 plus a term of estimation jitter, the latter about 50 times. TD trades “introduced bias” for “a variance reduction of one to two orders of magnitude”, and with a limited sample budget the net gain is usually positive.

Step four: the nn-step return interpolates between the two. Define the nn-step return

Gt(n)=∑k=0n−1γkRt+k+1+γnV(St+n)G_t^{(n)}=\sum_{k=0}^{n-1}\gamma^kR_{t+k+1}+\gamma^nV(S_{t+n})

n=1n=1 is TD(0), and n→∞n\to\infty (beyond the episode length) is MC. The larger nn is, the smaller the bias and the larger the variance. GAE (chapter 9) writes this interpolation as an exponentially weighted average over all nn, thereby tuning bias and variance continuously with a single parameter λ\lambda.

5.2 The TD(0) update rule

V(St)←V(St)+α[Rt+1+γV(St+1)−V(St)]V(S_t) \leftarrow V(S_t) + \alpha\left[R_{t+1} + \gamma V(S_{t+1}) - V(S_t)\right]

Three important points:

  • α\alpha is the learning rate (step size), controlling the magnitude of each update;
  • the bracket contains the TD error δt\delta_t, measuring the gap between “the actual value (one-step reward plus successor estimate)” and “the current estimate”;
  • when δt>0\delta_t>0, the current estimate is too low and is adjusted upward; when δt<0\delta_t<0, it is adjusted downward.

5.3 Why the expectation of the TD error is 0

For a fixed policy π\pi, if VV already equals the true VπV_\pi, then

Eπ[Rt+1+γVπ(St+1)−Vπ(St)∣St=s]=0\mathbb{E}_\pi\left[R_{t+1} + \gamma V_\pi(S_{t+1}) - V_\pi(S_t)\mid S_t=s\right] = 0

because the expectation inside the bracket is exactly “the expression for Vπ(s)V_\pi(s)” on the right-hand side of the Bellman equation, and subtracting Vπ(s)V_\pi(s) naturally gives zero. This property is called the residual property; it says that the TD error is zero-mean noise that “fluctuates around the true value”, so that stochastic-gradient-style corrections of VV based on it converge to the true value.

Derivation 11: why the residual property holds, and why it makes TD(0) a "semi-gradient" descent

Step one: expand the conditional expectation into a double sum.

Eπ[δt∣St=s]=∑aπ(a∣s)∑s′P(s′∣s,a)[R(s,a,s′)+γVπ(s′)]−Vπ(s)\mathbb{E}_\pi\left[\delta_t\mid S_t=s\right]=\sum_a\pi(a\mid s)\sum_{s'}P(s'\mid s,a)\left[R(s,a,s')+\gamma V_\pi(s')\right]-V_\pi(s)

Step two: recognize that the bracketed term is the right-hand side of the Bellman equation. By the double-sum expression in step four of 2.1, the first term equals exactly Vπ(s)V_\pi(s), hence

Eπ[δt∣St=s]=Vπ(s)−Vπ(s)=0\mathbb{E}_\pi\left[\delta_t\mid S_t=s\right]=V_\pi(s)-V_\pi(s)=0

This is the residual property: at the true value, the conditional mean of the TD error is zero.

Step three: zero mean shows that the true value is a fixed point. Writing the update as V←V+αδV\leftarrow V+\alpha\delta, its expected increment is α(TπV−V)\alpha\left(\mathcal{T}^\pi V-V\right); at V=VπV=V_\pi this term is zero, so VπV_\pi is a fixed point in the probabilistic sense—the update does not push it away.

Step four: why it is called “semi-gradient”. Treating the Bellman residual as the target, define

J(V)=12∑sμ(s)[TπV(s)−V(s)]2J(V)=\frac{1}{2}\sum_s\mu(s)\left[\mathcal{T}^\pi V(s)-V(s)\right]^2

When differentiating with respect to VV, the V(s′)V(s') inside TπV\mathcal{T}^\pi V also depends on the parameters, and a rigorous derivative must carry this term; the TD update deliberately drops it and differentiates only the “subtracted V(s)V(s)”:

∇θJ≈−∑sμ(s)[TπV(s)−V(s)]∇θV(s)\nabla_\theta J\approx-\sum_s\mu(s)\left[\mathcal{T}^\pi V(s)-V(s)\right]\nabla_\theta V(s)

The descent direction obtained after ignoring the derivative of the target term is called the semi-gradient (semi-gradient). It is not the true gradient of any scalar function, so convergence is not guaranteed under function approximation; in the tabular case (one independent parameter per state), however, the dropped term happens not to affect the update and convergence does hold.

Step five: this property is sensitive to the policy and the form of the target. It requires that the target contain γVπ(St+1)\gamma V_\pi(S_{t+1}), i.e., “the expectation under the current policy”. The target of Q-learning is r+γmax⁡a′Q(s′,a′)r+\gamma\max_{a'}Q(s',a'), whose conditional mean is no longer zero; combined with off-policy sampling and function approximation, the three appearing at once form the well-known deadly triad (deadly triad), which can produce divergence or oscillation.

Step six: the step-size conditions needed for convergence. Stochastic approximation theory requires the step sizes to satisfy the Robbins–Monro conditions:

∑tαt=∞,∑tαt2<∞\sum_{t}\alpha_t=\infty,\qquad \sum_t\alpha_t^2<\infty

The first guarantees that one can travel arbitrarily far (the step size does not decay so fast that progress stalls), the second guarantees that noise is averaged away. The commonly used αt=1/t\alpha_t=1/t or piecewise constant decay approximately satisfy both; a fixed large step size violates the second and therefore keeps jittering around the optimum.

5.4 Pseudocode: TD(0)

Input: policy π, step size α ∈ (0, 1)
Initialize: for all s ∈ S, V(s) ← arbitrary value (usually 0)

Loop (for each episode):
    Initialize state S
    For each step in the episode:
        Choose action A from S according to policy π, execute it, observe reward R and next state S'
        V(S) ← V(S) + α[R + γ V(S') − V(S)]
        S ← S'
    Until S is a terminal state

5.5 The bias-variance trade-off between MC and TD

This is the most central contrast in reinforcement learning:

DimensionMonte CarloTemporal difference TD(0)
Needs an environment modelNoNo
Must wait for the episode to endYesNo, updates at every step
Update targetThe true return GtG_tOne-step reward plus successor estimate Rt+1+γV(St+1)R_{t+1}+\gamma V(S_{t+1})
BiasUnbiased (GtG_t is the true return)Biased (depends on the current estimate V(St+1)V(S_{t+1}))
VarianceLarge (the return accumulates the randomness of the whole trajectory)Small (uses only one random reward)
Convergence speedSlow, and only for episodes that terminateFast, can be used for continuing tasks
Sensitivity to initial valuesInsensitiveSensitive (bootstrapping propagates the initial error back)

One-sentence mnemonic: MC has large variance and small bias; TD has small variance and large bias. All later efforts with “multi-step returns” and “GAE” are essentially searching for a better compromise point between the two ends.


6. Q-learning and DQN

6.1 Q-learning: learning the optimal action value directly

Q-learning applies the TD idea to action values and takes a max⁡\max in the target, so it approximates Q∗Q^* directly:

Q(S,A)←Q(S,A)+α[R+γmax⁡a′Q(S′,a′)−Q(S,A)]Q(S,A) \leftarrow Q(S,A) + \alpha\left[R + \gamma \max_{a'} Q(S',a') - Q(S,A)\right]

Two details:

  • Why the target uses max⁡\max: Q-learning must converge to the optimal Q∗Q^*, so it uses max⁡a′\max_{a'} rather than weighting by the policy probabilities. This also makes it an off-policy algorithm—sampling may use ε\varepsilon-greedy while the learning target is always the optimum.
  • When S′S' is a terminal state: by convention max⁡a′Q(S′,a′)=0\max_{a'}Q(S',a')=0, and the update degenerates to Q(S,A)←Q(S,A)+α[R−Q(S,A)]Q(S,A)\leftarrow Q(S,A)+\alpha[R-Q(S,A)], i.e., pulling the action value of the last step toward “the last reward actually received”.
Derivation 12: how the Q-learning update comes from the Bellman optimality equation, and why it is off-policy and why it converges

Step one: the starting point is the Bellman optimality equation containing only max⁡\max. From step two of 2.2:

Q∗(s,a)=∑s′P(s′∣s,a)[R(s,a,s′)+γmax⁡a′Q∗(s′,a′)]Q^*(s,a)=\sum_{s'}P(s'\mid s,a)\left[R(s,a,s')+\gamma\max_{a'}Q^*(s',a')\right]

Step two: replace the expectation with one real transition. When sampling, only one (s,a,r,s′)(s,a,r,s') can be observed, so the weighted sum over s′s' is replaced by a single sample:

∑s′P(s′∣s,a)[⋯ ] ≈ r+γmax⁡a′Q(s′,a′)\sum_{s'}P(s'\mid s,a)\left[\cdots\right]\ \approx\ r+\gamma\max_{a'}Q(s',a')

The sampling of s′s' itself is unbiased (s′∼P(⋅∣s,a)s'\sim P(\cdot\mid s,a)), but the QQ inside the bracket is the current estimate rather than Q∗Q^*, so the whole expression is still biased with respect to Q∗Q^*—this bias comes from bootstrapping, not from sampling.

Step three: write the fixed-point iteration in incremental form. With step size α\alpha, update only the visited pair (s,a)(s,a):

Qk+1(s,a)=(1−α)Qk(s,a)+α[r+γmax⁡a′Qk(s′,a′)]Q_{k+1}(s,a)=(1-\alpha)Q_k(s,a)+\alpha\left[r+\gamma\max_{a'}Q_k(s',a')\right]

Rearranging gives the form in the main text. It can also be seen as “a discounted moving average of the current estimate”: new estimate = old estimate + step size × (sampled target − old estimate).

Step four: why it converges to Q∗Q^*. In the tabular case, if (1) every (s,a)(s,a) is visited infinitely often; (2) the step sizes satisfy the Robbins–Monro conditions ∑αt=∞\sum\alpha_t=\infty, ∑αt2<∞\sum\alpha_t^2<\infty; (3) γ<1\gamma<1, then this is a stochastic approximation of a contraction operator and Qk→Q∗Q_k\to Q^* almost surely. Intuitively, the per-step error satisfies

∣Qk+1(s,a)−Q∗(s,a)∣≤(1−α)∣Qk(s,a)−Q∗(s,a)∣+αγ∥Qk−Q∗∥∞+α∣sampling noise∣\left|Q_{k+1}(s,a)-Q^*(s,a)\right|\le(1-\alpha)\left|Q_k(s,a)-Q^*(s,a)\right|+\alpha\gamma\left\|Q_k-Q^*\right\|_\infty+\alpha\left|\text{sampling noise}\right|

The first term shrinks the error of the pair itself by 1−α1-\alpha, the second introduces the neighbours’ error scaled by αγ\alpha\gamma, and taking maxima over the third step together with step-size decay averages the noise away, so the total error converges.

Step five: why it is off-policy. The target in the update uses max⁡a′\max_{a'} and is completely independent of “which policy produced the data”; the expression also contains no importance weights such as π(a∣s)\pi(a\mid s). Therefore, as long as the behavior policy (behavior policy, the policy actually used for sampling) can visit all (s,a)(s,a), whether it is ε\varepsilon-greedy, random, or human demonstrations, what is learned is the same Q∗Q^*. This is the precise definition of “off-policy”: the target policy is decoupled from the behavior policy.

Step six: why ε\varepsilon-greedy is part of the convergence conditions. If the behavior policy never tries a certain action, the corresponding QQ value can never be corrected and the first condition “visited infinitely often” fails. ε>0\varepsilon>0 guarantees that every action has a positive probability of being tried; ε\varepsilon must also stay nonzero during training (or at least decay slowly enough), otherwise late in training it degenerates into visiting only the greedy action again. This is also why the “explore first, exploit later” schedule must be designed carefully.

6.2 The limitations of the tabular approach

Tabular Q-learning needs to store one value for every (s,a)(s,a) pair. As soon as the number of states grows, this explodes:

  • with image input (for instance the 210×160210\times160 pixel frames of Atari games), the number of states is practically infinite;
  • a continuous state space cannot be enumerated at all;
  • both storage and lookup become infeasible.

The solution is to use a function approximator (a neural network) that takes the state as input and outputs the Q values of all actions—this is DQN.

6.3 The two key techniques of DQN

DQN (Deep Q-Network) is the flagship deep reinforcement learning work proposed by DeepMind in 2015 (the Nature paper, used to play Atari games). It approximates the Q function with a neural network Q(s,a;θ)Q(s,a;\theta), replacing the Q table of Q-learning. But plugging a neural network directly into Q-learning runs into two chronic diseases: correlated samples and unstable targets. DQN treats both with two key techniques:

First, why do these “two chronic diseases” appear? Reinforcement learning has three conditions—function approximation (using a neural network instead of a table), bootstrapping (using estimates to update estimates), and off-policy (using data produced by historical policies to update the current policy). Each alone is fine, but once all three appear simultaneously they form the deadly triad (deadly triad): their interaction amplifies estimation errors and feeds them back into the estimates, and training may diverge. DQN happens to satisfy all three—the neural network is function approximation, the max⁡Q\max Q target is bootstrapping, and experience replay is off-policy. So the experience replay and target network below are not “finishing touches” but necessary conditions for stable convergence.

Key technique one: Experience Replay

Transitions (s,a,r,s′)(s,a,r,s') produced by interaction are stored in a replay buffer (Replay Buffer, DD), and during training a mini-batch is drawn uniformly at random to update the network. It has three effects:

  • it breaks the temporal correlation between samples so that the training data is approximately i.i.d., stabilizing gradient descent;
  • one experience can be reused many times, improving sample efficiency;
  • it smooths the data distribution and prevents the network from being “dragged along” by the most recent trajectory.

Key technique two: Target Network

A “frozen” network with parameters θ−\theta^- is maintained and used to compute the TD target yjy_j; the online network’s parameters are copied over only every CC steps. Effects:

  • the TD target stays stable for a period of time, avoiding the divergence caused by “the target chasing the prediction”;
  • it amounts to giving the regression problem a “temporarily fixed teacher”.

6.4 The core idea and pseudocode of DQN

DQN turns the reinforcement learning problem into a supervised-learning-style regression problem: the input is state sjs_j, the online network outputs the Q values of all actions, and the output Q(sj,aj;θ)Q(s_j,a_j;\theta) corresponding to the target action aja_j should regress toward the target value yjy_j:

yj={rj,terminal staterj+γmax⁡a′Q(sj+1,a′;θ−),non-terminal statey_j = \begin{cases} r_j, & \text{terminal state}\\ r_j + \gamma \max_{a'} Q(s_{j+1},a';\theta^-), & \text{non-terminal state} \end{cases}

The loss function (mean squared error):

L(θ)=E[(yj−Q(sj,aj;θ))2]L(\theta) = \mathbb{E}\left[\left(y_j - Q(s_j,a_j;\theta)\right)^2\right]
Derivation 13: where the DQN loss comes from, why the target must be detached, and what bias Double DQN corrects

Step one: rewrite the incremental Q-learning update as one gradient-descent step. For a single sample, define the squared error

ℓ=12(y−Q(s,a;θ))2\ell=\frac{1}{2}\left(y-Q(s,a;\theta)\right)^2

Its derivative with respect to QQ is −(y−Q)-\left(y-Q\right). So "Q←Q+α[y−Q]Q\leftarrow Q+\alpha\left[y-Q\right]" is exactly a gradient-descent step of size α\alpha on ℓ\ell (the learning rate absorbs the factor 2). Replacing the single sample by a mini-batch drawn from the replay buffer and taking the expectation gives

L(θ)=E(s,a,r,s′)∼D[(y−Q(s,a;θ))2],∇θL=−2 E[(y−Q(s,a;θ))∇θQ(s,a;θ)]L(\theta)=\mathbb{E}_{(s,a,r,s')\sim D}\left[\left(y-Q(s,a;\theta)\right)^2\right],\qquad \nabla_\theta L=-2\,\mathbb{E}\left[\left(y-Q(s,a;\theta)\right)\nabla_\theta Q(s,a;\theta)\right]

Note the minus sign: gradient descent moves along −∇L-\nabla L, which pulls the prediction toward the target yy.

Step two: why yy must be treated as a constant (detach). If the target’s Q(s′,a′;θ−)Q(s',a';\theta^-) were replaced by a form differentiable with respect to θ\theta, the gradient would acquire an extra term

−2(y−Q(s,a;θ))γ∇θmax⁡a′Q(s′,a′;θ)-2\left(y-Q(s,a;\theta)\right)\gamma\nabla_\theta\max_{a'}Q(s',a';\theta)

This term lets the “label” move with the parameters too, turning the optimization problem from “regress to a fixed label” into “chase a moving target”, which may diverge or produce a fake convergence in which “the loss decreases while the Q values drift as a whole”. So the target term must either be placed inside torch.no_grad() or explicitly .detach()-ed.

Step three: why a separate target network is still needed. Even with detach, if the label is computed from the newest θ\theta at every step, the labels of adjacent mini-batches remain highly correlated and the gradient direction jitters a lot. Using θ−\theta^- and synchronizing every CC steps is equivalent to fixing the target within a time window CC, approximating “non-stationary regression” by “piecewise stationary regression”. If CC is too small it degenerates to no target network; if CC is too large the labels become stale and learning slows—which is why the “hard copy period” in the pitfall checklist of 6.4 needs a compromise.

Step four: why experience replay reduces the gradient variance. When sampling in temporal order, (st,at)(s_t,a_t) and (st+1,at+1)(s_{t+1},a_{t+1}) are nearly identical, the gradients are highly correlated, and the effective sample size is far smaller than the batch size NN. Drawing uniformly at random from DD makes the samples approximately independent and reduces the gradient variance roughly as 1/N1/N—the same reasoning as the 1/n1/n in step two of 4.1.

Step five: how large is the overestimation bias caused by max⁡\max. Suppose the estimate of each action carries independent zero-mean noise ϵa\epsilon_a:

E[max⁡a(Q∗(s,a)+ϵa)]≥max⁡aQ∗(s,a)\mathbb{E}\left[\max_a\left(Q^*(s,a)+\epsilon_a\right)\right]\ge\max_aQ^*(s,a)

because max⁡\max is convex and Jensen’s inequality gives “the maximum of the expectations ≥ the expectation of the maximum”. The more actions and the larger the noise, the more severe the upward bias. Moreover this bias accumulates through the bootstrap γmax⁡\gamma\max, manifesting as Q values inflating as a whole while the return does not rise (the first row of the pitfall checklist in 6.4).

Step six: how Double DQN removes this term. Split “choosing the action” and “estimating the value” onto two networks:

y=r+γ Q(s′,arg⁡max⁡a′Q(s′,a′;θ);θ−)y=r+\gamma\,Q\left(s',\arg\max_{a'}Q(s',a';\theta);\theta^-\right)

The action is chosen by the online network θ\theta and the value is given by the target network θ−\theta^-. The noises of the two networks are approximately independent, so the selection bias of a∗a^* and the estimation bias of QQ no longer add up in the same direction, and the overestimation drops markedly. The price is only one extra forward pass; no additional network is needed.

The complete pseudocode:

Input: online network parameters θ, target network parameters θ⁻ (initially θ⁻ = θ), replay buffer D,
       step size α, discount factor γ

Initialize the state sequence s_t = {x_t}; after preprocessing the state φ_t = φ(s_t)

Loop (for each episode / each time step):
    Choose action a_t with the ε-greedy policy
    Execute a_t, observe reward r_t and the next frame x_{t+1}
    Let s_{t+1} = s_t ∪ {x_{t+1}}, φ_{t+1} = φ(s_{t+1})
    Store the transition (φ_t, a_t, r_t, φ_{t+1}) in D
    Draw a mini-batch of samples (φ_j, a_j, r_j, φ_{j+1}) uniformly at random from D
        Let y_j = r_j (terminal state)
            y_j = r_j + γ max_{a'} Q(φ_{j+1}, a'; θ⁻) (non-terminal state)
    Take one gradient-descent step on the loss L = (1/N) Σ_j (y_j − Q(φ_j, a_j; θ))², updating θ
    Every C steps do θ⁻ ← θ

Line-by-line commentary.

  1. Why φ_t = φ(s_t) rather than the raw frame: a single frame shows neither the direction nor the speed of motion. Only after stacking the most recent few frames (commonly 4) as input can the network infer speed from “the displacement difference”. This step is not an optional trick but a necessary means of approximately restoring a partially observable problem to an observable one.
  2. Why ε-greedy must exist: the Q values given by the network are basically wrong early in training; pure greed would repeatedly walk the same path, no new samples would enter the replay buffer, and learning would stall. ε decays with training (for example linearly from 1.0 to 0.01), emphasizing exploration early and exploitation late.
  3. Why φ_t rather than the raw s_t is stored in D: at replay time it must be guaranteed that “the state seen during training” is exactly the same as “the state seen during sampling”. If raw frames were stored and re-stacked when sampling, extra implementation complexity and risk of inconsistency would be introduced.
  4. What correlation the random mini-batch breaks: samples from consecutive time steps are highly correlated (adjacent frames are almost identical), and training directly in order would make the gradient point in the same direction repeatedly over a short period, equivalent to using a very small effective batch. Random sampling makes the samples approximately independent and identically distributed.
  5. The two branches of y_j are exactly the terminal mask: there is no future reward after a terminal state, so the second term must be 0. A common pitfall is to judge termination by “the episode ended”—when the episode is cut off by a time limit the environment could still continue and bootstrapping should be kept. This is the same distinction between termination and truncation discussed in 9.4; in DQN, where there is no advantage recursion, the symptom is “the Q values are systematically underestimated near the time limit”.
  6. The loss acts only on “the chosen action”: one forward pass of the network outputs the Q values of all actions, but one sample only provides a supervision signal for “the action actually executed aja_j”. In implementation, gather is used to pick out the column corresponding to that action before computing the error; the other actions do not participate in this loss—otherwise “actions not executed” would also be pulled toward the same target.
  7. Hard copying every C steps rather than updating every step: the role of the target network is to “keep the target still for a period of time”. If it were synchronized at every step, θ⁻ would be identical to θ, the target would become a moving target again, and the target network would lose its meaning.

Gradient flow and detach. y_j is a label and must be treated as a constant: when computing the target, put the forward pass of θ⁻ inside torch.no_grad(), or explicitly .detach() the result, and let only the branch Q(φ_j,a_j;θ) participate in backpropagation. Without detach, the gradient of the loss with respect to θ would also flow back through the target term, equivalent to “the prediction and the target moving together”, and training would exhibit a fake convergence in which the loss decreases while the Q values drift as a whole. This is the same principle as the requirement that the value label be detached in PPO: the target describes “an estimate from the past”, not the variable to be optimized this time.

Implementation pitfall checklist.

SymptomPossible causeFix
Q values keep inflating while the return does not changeNo target network, or the target is not detached, or max is used without DoubleFix θ⁻, detach the target, switch to Double DQN
Q values abnormally low near the time limitTruncation treated as terminationSplit done/truncated; truncation should still bootstrap
Performance suddenly collapses late in trainingε decays too fast, learning rate too largeSlow down the ε decay, lower the learning rate, add gradient clipping
Cannot learn when return scales differ widelyRewards not scaledClip rewards to [−1,1][-1,1] or apply running normalization
The replay buffer contains only similar samplesBuffer too small, sampling strategy too narrowEnlarge the buffer, increase early exploration
Performance degrades immediately after target-network syncHard copy period too shortIncrease C (commonly 1000–10000 steps)

6.5 Six common questions about DQN

Question one: what are Q(sj,aj;θ)Q(s_j,a_j;\theta) and yjy_j respectively?

Q(sj,aj;θ)Q(s_j,a_j;\theta) is the Q-value prediction given by the online network for “the action actually executed in the sample, aja_j”; it is the “prediction” to be optimized. yjy_j is the regression target computed from “the actual reward rjr_j and the maximum Q estimate of the next state from the target network”; it is the relatively fixed “teacher”. The training direction is always the prediction moving toward the target, never yjy_j moving toward the prediction.

Question two: what is θ\theta?

θ\theta is the set of learnable parameters of a neural network (the weights WW and the biases bb). The online network and the target network have the same architecture but not the same values—the target network lags behind the online network, which is exactly the meaning of the “frozen teacher”.

Question three: what are the input and the output of the network?

The input is the state ss (or the preprocessed ϕ\phi, for example several stacked frames that carry motion information), and the output is the Q values of all actions in that state. Taking the branch corresponding to the chosen action aja_j gives Q(sj,aj;θ)Q(s_j,a_j;\theta). This design of “one forward pass producing all action values” avoids running one forward pass per action and is efficient.

Question four: why is a target network needed?

If the target were computed only with the online network, the max⁡Q\max Q inside the target yjy_j would also be produced by the network being updated—“the target chases the prediction”, which is like aiming at a constantly moving target, and training easily diverges. The target network fixes yjy_j at θ−\theta^- (synchronized only every CC steps), providing a stable regression target for the optimization.

Question five: why use max⁡\max rather than averaging over the policy?

Because DQN inherits Q-learning and its target is Q∗Q^*, so the maximum must be taken. Sampling can still use ε\varepsilon-greedy exploration, and the learning target is decoupled from the sampling policy; DQN is therefore also an off-policy algorithm and can reuse the replay buffer.

Question six: what later improvements does DQN have?

  • Double DQN (Double DQN): decouples “choosing the action” from “estimating the value” and alleviates the maximization bias (maximization bias) caused by max⁡\max—taking the maximum over a set of noisy estimates is systematically higher in expectation than the true maximum, and the overestimation of DQN arises exactly from this; Double DQN lets the online network choose the action and the target network evaluate it, separating “choice” from “evaluation”, and the bias drops accordingly;
  • Dueling DQN (Dueling DQN): splits QQ into a state value VV and an advantage AA;
  • Prioritized Replay (Prioritized Replay): samples with priority according to the TD error;
  • DDPG: carries the ideas of DQN over to continuous action settings.

6.6 The limitations of DQN

DQN can only handle discrete action spaces: the output layer has one node per action, and arg⁡max⁡\arg\max can simply pick among finitely many values. When actions are continuous (for example robot joint angles), arg⁡max⁡aQ(s,a)\arg\max_a Q(s,a) requires extremizing over a continuous space and cannot be computed efficiently with one forward pass. Continuous control needs policy gradient or actor-critic methods.


7. Policy Gradient and REINFORCE

7.1 Why policy gradients are needed

All the preceding methods (MC, TD, Q-learning, DQN) are “learn a value function first, then derive the policy from the value function”. Policy gradient (Policy Gradient, PG) takes another route: represent the policy πθ(a∣s)\pi_\theta(a\mid s) directly with a neural network parameterized by θ\theta and maximize the expected return J(θ)J(\theta) by gradient ascent, with no arg⁡max⁡\arg\max needed.

The advantages of policy gradients:

  • Handling continuous actions naturally: the output is the mean and variance of the action distribution, and one samples directly; there is no need to solve arg⁡max⁡\arg\max over a continuous space;
  • Supporting stochastic policies naturally: more robust in partially observable, adversarial, and similar settings;
  • Smoother updates: a small change of a Q value does not cause an abrupt jump of the action (arg⁡max⁡\arg\max switches action suddenly when Q values are close).

7.2 The policy gradient theorem

The gradient of the expected return J(θ)J(\theta) with respect to θ\theta can be written as:

∇θJ(θ)=Eτ∼πθ[∑t∇θlog⁡πθ(at∣st) Gt]\nabla_\theta J(\theta) = \mathbb{E}_{\tau\sim\pi_\theta}\left[\sum_t \nabla_\theta \log \pi_\theta(a_t\mid s_t)\, G_t\right]

where τ\tau denotes a trajectory (trajectory). Reading this formula intuitively:

  • for a trajectory τ\tau, if the return GtG_t it brings is high, the “probability of this trajectory” is adjusted upward (the gradient direction is weighted by GtG_t); if the return is low, it is adjusted downward.
  • the gradient of log⁡π\log \pi comes from the “log-derivative trick”: moving the derivative of the action probability inside the expectation so that the gradient can be estimated by sampling, without differentiating the state distribution.

The core identity of the log-derivative trick (log-derivative trick) is

∇θπθ(a∣s)=πθ(a∣s) ∇θlog⁡πθ(a∣s)\nabla_\theta \pi_\theta(a\mid s) = \pi_\theta(a\mid s)\,\nabla_\theta \log \pi_\theta(a\mid s)

It turns “differentiating the probability” into “differentiating the probability times its logarithm”, so that the gradient can be written as an expectation.

Derivation 14: complete derivation of the policy gradient theorem (log-derivative trick → environment terms vanish → causality removes future terms)

Step one: write down the objective and the trajectory distribution. Let the trajectory be τ=(s0,a0,s1,a1,…,sT)\tau=(s_0,a_0,s_1,a_1,\dots,s_T), whose probability is

pθ(τ)=p(s0)∏t=0T−1πθ(at∣st) P(st+1∣st,at)p_\theta(\tau)=p(s_0)\prod_{t=0}^{T-1}\pi_\theta(a_t\mid s_t)\,P(s_{t+1}\mid s_t,a_t)

The objective is J(θ)=Eτ∼pθ(τ)[R(τ)]J(\theta)=\mathbb{E}_{\tau\sim p_\theta(\tau)}\left[R(\tau)\right], where R(τ)R(\tau) is the return of the whole trajectory.

Step two: turn “the derivative of a distribution” into “an expectation over samples”. First use the log-derivative trick ∇θpθ(τ)=pθ(τ)∇θlog⁡pθ(τ)\nabla_\theta p_\theta(\tau)=p_\theta(\tau)\nabla_\theta\log p_\theta(\tau):

∇θJ(θ)=∫∇θpθ(τ)R(τ) dτ=∫pθ(τ)∇θlog⁡pθ(τ)R(τ) dτ=Eτ∼pθ[R(τ)∇θlog⁡pθ(τ)]\nabla_\theta J(\theta)=\int\nabla_\theta p_\theta(\tau)R(\tau)\,d\tau=\int p_\theta(\tau)\nabla_\theta\log p_\theta(\tau)R(\tau)\,d\tau=\mathbb{E}_{\tau\sim p_\theta}\left[R(\tau)\nabla_\theta\log p_\theta(\tau)\right]

The significance of this step: the gradient changes from “integrating over all possible trajectories” into “averaging over samples drawn from the current policy”, so it can be estimated from samples without knowing the environment model.

Step three: take the logarithm and decompose; all environment terms vanish. After taking the logarithm it is a sum:

log⁡pθ(τ)=log⁡p(s0)+∑t=0T−1[log⁡πθ(at∣st)+log⁡P(st+1∣st,at)]\log p_\theta(\tau)=\log p(s_0)+\sum_{t=0}^{T-1}\left[\log\pi_\theta(a_t\mid s_t)+\log P(s_{t+1}\mid s_t,a_t)\right]

When differentiating with respect to θ\theta, the initial state distribution p(s0)p(s_0) and the transition probabilities PP do not depend on θ\theta, so their derivatives vanish:

∇θlog⁡pθ(τ)=∑t=0T−1∇θlog⁡πθ(at∣st)\nabla_\theta\log p_\theta(\tau)=\sum_{t=0}^{T-1}\nabla_\theta\log\pi_\theta(a_t\mid s_t)

This is the fundamental reason why policy gradients are “model-free”: the unknown dynamics of the environment are cancelled automatically by the structure of the logarithm.

Step four: use causality to delete the rewards “before the action”. Split R(τ)R(\tau) into the part before tt and the part after tt. Given sts_t, the rewards before tt are independent of ata_t, and

Ea∼πθ(⋅∣st)[∇θlog⁡πθ(a∣st)]=∑aπθ(a∣st)∇θπθ(a∣st)πθ(a∣st)=∇θ∑aπθ(a∣st)=∇θ1=0\mathbb{E}_{a\sim\pi_\theta(\cdot\mid s_t)}\left[\nabla_\theta\log\pi_\theta(a\mid s_t)\right]=\sum_a\pi_\theta(a\mid s_t)\frac{\nabla_\theta\pi_\theta(a\mid s_t)}{\pi_\theta(a\mid s_t)}=\nabla_\theta\sum_a\pi_\theta(a\mid s_t)=\nabla_\theta 1=0

so the expectation of “the earlier rewards” times ∇θlog⁡π\nabla_\theta\log\pi is zero and the whole block can be deleted. What remains are only the rewards at tt and afterwards, i.e., GtG_t. Hence

∇θJ(θ)=E[∑t∇θlog⁡πθ(at∣st) Gt]\nabla_\theta J(\theta)=\mathbb{E}\left[\sum_t\nabla_\theta\log\pi_\theta(a_t\mid s_t)\,G_t\right]

(In the rigorous form there is still a γt\gamma^t factor in front; absorbing it into the definition of “sampling according to the discounted distribution” yields the expression above. Many textbooks simply drop this layer of weighting, which does not affect the conclusion.)

Step five: why it is unbiased, and where the variance comes from. Every step above is an identity transformation; the only approximation is replacing the expectation by an average over finitely many samples, so the gradient estimate of REINFORCE is unbiased. The reason for the large variance lies in the same place: GtG_t is the random sum of a whole trajectory, large in magnitude and volatile; and the norm of ∇θlog⁡π\nabla_\theta\log\pi grows sharply when the policy approaches determinism (as π→0\pi\to0, 1/π1/\pi explodes). Their product makes the single-sample gradient noise very large. Subtracting a baseline changes only the variance of the second factor, not the expectation of the first—8.1 gives the proof.

Step six: why importance weights are necessary when the samples come from an old policy. All the expectations above are taken with respect to the current πθ\pi_\theta. If the data were collected by an old policy πθold\pi_{\theta_{\mathrm{old}}}, using them directly yields a biased gradient; the correct approach is to multiply by the importance ratio

ρt=πθ(at∣st)πθold(at∣st)\rho_t=\frac{\pi_\theta(a_t\mid s_t)}{\pi_{\theta_{\mathrm{old}}}(a_t\mid s_t)}

This is the starting point of TRPO and PPO (chapters 10 and 11): first sample a batch of data with the old policy, then correct it with importance weights, so that the same batch can be reused several times.

7.3 REINFORCE: the most naive policy gradient

REINFORCE uses the return GtG_t of a complete episode as the weight:

θ←θ+α Gt ∇θlog⁡πθ(at∣st)\theta \leftarrow \theta + \alpha\, G_t\, \nabla_\theta \log \pi_\theta(a_t\mid s_t)

It is unbiased but has very large variance: GtG_t is the random return of a whole trajectory, large in absolute value and volatile, so the gradient noise is also large. The remedy is a baseline (baseline); the actor-critic of the next section is its systematic version.

The complete pseudocode:

Algorithm: REINFORCE (Monte Carlo policy gradient)
Input: policy π_θ, learning rate α, discount factor γ
Output: the trained θ

Loop (for each episode):
    Sample an entire trajectory with π_θ: s_0, a_0, r_1, s_1, a_1, r_2, …, s_T
    For each time step record logp_t ← log π_θ(a_t|s_t)      # computed at sampling time, detach
    G ← 0
    for t = T-1 downto 0:                          # accumulate the return backwards
        G ← r_{t+1} + γ·G                          # or G ← γ·G + r_{t+1}
        G_t ← G                                    # the return of that time step, detach
    L ← −(1/T) Σ_t logp_t · G_t                    # minus sign: turn gradient ascent into minimization
    Backpropagate and update θ                     # only this one trajectory, one update

Line-by-line commentary.

  1. The whole trajectory must be sampled first: the weight of REINFORCE is GtG_t, and GtG_t can only be computed fully after the episode ends. This is the most essential difference from TD methods—it cannot update online, only episode by episode.
  2. logp_t is computed at sampling time and G_t is computed backwards: the two are separated for different reasons. logp_t must be computed under “the version of the policy at that time”, otherwise it is not the true log-probability of this trajectory; G_t must be accumulated backwards so that a single O(T)O(T) pass yields the returns of all time steps (forward order would need O(T2)O(T^2)).
  3. The order of G ← γ·G + r cannot be reversed: the correct form is “multiply the discount first, then add the current step’s reward”, i.e., Gt=rt+1+γGt+1G_t = r_{t+1} + \gamma G_{t+1}. Writing G ← G + γ·r misaligns the discount exponent, and earlier rewards end up with smaller weights instead.
  4. The minus sign in L: deep learning frameworks minimize by default, whereas the policy gradient must maximize JJ, so the loss is negated. An equivalent form is loss = -(logp * G).mean().
  5. One update per episode: all time steps of this trajectory contribute their gradients together, rather than one update per time step. With per-step updates, later updates would change the policy and the logp of earlier time steps would be stale.
  6. Both G_t and logp_t must be detached: they are weights and labels, not variables to be optimized. If G_t carried gradients (for example if computed by a value network), the policy gradient would acquire an extra component flowing back through the value network, and the Actor and the Critic would interfere with each other.

Why the variance is large, and how a baseline helps. The expectation of GtG_t is Qπ(st,at)Q^\pi(s_t,a_t), whose magnitude varies with the reward scale of the task (it may be tens or hundreds), and the GtG_t of adjacent time steps within one trajectory are highly correlated. Subtracting a baseline b(st)b(s_t) does not change the gradient expectation (the unbiasedness derivation is in the log-derivative trick of 7.2), yet it turns the weight from “absolute return” into “relative advantage” and reduces the variance markedly:

∇θJ=E[∇θlog⁡πθ(at∣st)(Gt−b(st))]\nabla_\theta J = \mathbb{E}\left[\nabla_\theta\log\pi_\theta(a_t|s_t)\left(G_t - b(s_t)\right)\right]

Taking b(st)=Vπ(st)b(s_t)=V^\pi(s_t), the weight becomes the advantage AtA_t; in practice VV is estimated by another network, which is the natural transition to actor-critic.

Derivation 15: the REINFORCE update is a single-sample estimate of the policy gradient, and why subtracting a baseline is both unbiased and variance-reducing

Step one: write the update as the gradient of a loss function. The REINFORCE update is

θ←θ+α Gt ∇θlog⁡πθ(at∣st)\theta\leftarrow\theta+\alpha\,G_t\,\nabla_\theta\log\pi_\theta(a_t\mid s_t)

Deep learning frameworks minimize by default, so define

L(θ)=−1T∑tlog⁡πθ(at∣st) GtL(\theta)=-\frac{1}{T}\sum_{t}\log\pi_\theta(a_t\mid s_t)\,G_t

Its gradient is ∇θL=−1T∑tGt∇θlog⁡πθ(at∣st)\nabla_\theta L=-\frac{1}{T}\sum_tG_t\nabla_\theta\log\pi_\theta(a_t\mid s_t), which matches the expression above after taking the negative sign. Note that GtG_t is a scalar coefficient inside LL and must be detach-ed in the implementation.

Step two: its expectation is exactly the policy gradient. By the conclusion of 7.2, taking the expectation over a single trajectory:

Eτ[∑tGt∇θlog⁡πθ(at∣st)]=∇θJ(θ)\mathbb{E}_{\tau}\left[\sum_tG_t\nabla_\theta\log\pi_\theta(a_t\mid s_t)\right]=\nabla_\theta J(\theta)

So it is an unbiased Monte Carlo estimate of ∇θJ\nabla_\theta J, which is the precise meaning of the phrase “the most naive policy gradient”.

Step three: subtracting a baseline does not change the expectation. For any function b(st)b(s_t) that depends only on the state:

E[∇θlog⁡πθ(at∣st) b(st)]=Est[b(st) Eat∼πθ[∇θlog⁡πθ(at∣st)]]=0\mathbb{E}\left[\nabla_\theta\log\pi_\theta(a_t\mid s_t)\,b(s_t)\right]=\mathbb{E}_{s_t}\left[b(s_t)\,\mathbb{E}_{a_t\sim\pi_\theta}\left[\nabla_\theta\log\pi_\theta(a_t\mid s_t)\right]\right]=0

The inner expectation is zero because ∑aπθ(a∣s)∇θlog⁡πθ(a∣s)=∇θ∑aπθ(a∣s)=∇θ1=0\sum_a\pi_\theta(a\mid s)\nabla_\theta\log\pi_\theta(a\mid s)=\nabla_\theta\sum_a\pi_\theta(a\mid s)=\nabla_\theta1=0. So after subtracting b(st)b(s_t) the gradient expectation is unchanged and still unbiased.

Step four: the variance does decrease, and by how much can be computed. For a fixed state ss, write g=∇θlog⁡πθ(a∣s)g=\nabla_\theta\log\pi_\theta(a\mid s); then

Var[g(G−b(s))]=E[g2(G−b(s))2]−(E[g(G−b(s))])2\mathrm{Var}\left[g\left(G-b(s)\right)\right]=\mathbb{E}\left[g^2\left(G-b(s)\right)^2\right]-\left(\mathbb{E}\left[g\left(G-b(s)\right)\right]\right)^2

The second term equals (∇θJ)2\left(\nabla_\theta J\right)^2 and does not depend on bb. Differentiate the first term with respect to bb and set it to zero:

∂∂bE[g2(G−b)2]=−2 E[g2(G−b)]=0\frac{\partial}{\partial b}\mathbb{E}\left[g^2\left(G-b\right)^2\right]=-2\,\mathbb{E}\left[g^2\left(G-b\right)\right]=0

Solving gives the minimum-variance baseline

b∗(s)=E[g2G∣s]E[g2∣s]b^*(s)=\frac{\mathbb{E}\left[g^2G\mid s\right]}{\mathbb{E}\left[g^2\mid s\right]}

It is the return average weighted by “the squared norm of the gradient”. When g2g^2 and GG are approximately independent, it degenerates to E[G∣s]=Vπ(s)\mathbb{E}[G\mid s]=V^\pi(s). This explains why V(s)V(s) is used as the baseline in practice: it is a natural approximation of the optimal baseline, and it incidentally provides a learnable critic.

Step five: why subtracting the baseline does not erase the information about “good actions”. Two things must be distinguished: the absolute magnitude of GtG_t determines the size of the update, and the sign of Gt−b(st)G_t-b(s_t) determines the direction. After subtracting the baseline, actions better than average are still positive and actions worse than average are still negative, so the directional information is fully preserved; the magnitude, however, is compressed to the order of “relative advantage” and the variance decreases accordingly.

Implementation pitfall checklist.

SymptomPossible causeFix
Gradient noise extremely large, hardly convergingNo baseline, no return normalizationSubtract a baseline; apply running normalization to GtG_t
The policy suddenly collapses mid-trainingLearning rate too large, single-episode update step too aggressiveLower the learning rate, add gradient clipping, or switch to PPO
No improvement for a long timeEpisode too long, discount too strong so the signal vanishesShorten the episode, increase γ\gamma, switch to nn-step returns
Enormous variance in continuous control tasksNo constraint on the action-distribution variancePut a lower bound on the policy’s log⁡σ\log\sigma, or switch to SAC
Results vary hugely between runsSingle-trajectory estimates, sensitive to random seedsRun parallel environments, enlarge the batch, evaluate over multiple seeds

REINFORCE’s position is clear: it is the minimal working example for understanding policy gradients, not an algorithm that can go to production. Fix its variance problem step by step and you get A2C; then keep the update magnitude in check and you get TRPO/PPO.


8. Actor-Critic and A2C/A3C

8.1 Why a baseline is subtracted

In policy gradients, GtG_t is large in absolute value and large in variance. If a baseline b(st)b(s_t) that depends only on the state is subtracted from the weight, the gradient expectation is unchanged (because Ea∼π[∇θlog⁡πθ(a∣s)]=0\mathbb{E}_{a\sim\pi}[\nabla_\theta\log\pi_\theta(a\mid s)]=0), but the variance drops markedly:

∇θJ(θ)=E[∇θlog⁡πθ(at∣st)(Gt−b(st))]\nabla_\theta J(\theta) = \mathbb{E}\left[\nabla_\theta\log\pi_\theta(a_t\mid s_t)\left(G_t - b(s_t)\right)\right]

The most natural baseline is the state value V(st)V(s_t). The quantity left after subtracting it,

At=Gt−V(st)A_t = G_t - V(s_t)

is called the advantage (advantage): it measures “how much better taking action aa in state ss is than average”. At>0A_t>0 means the action is better than average and deserves encouragement; At<0A_t<0 means it is worse than average and should be suppressed.

Derivation 16: why the advantage is defined as "$Q$ minus $V$", and why its expectation over actions is zero

Step one: the standard definition of the advantage is action value minus state value.

Aπ(s,a)=Qπ(s,a)−Vπ(s,a)A^\pi(s,a)=Q^\pi(s,a)-V^\pi(s,a)

Step two: Gt−V(st)G_t-V(s_t) is its unbiased single sample. By definition E[Gt∣st,at]=Qπ(st,at)\mathbb{E}\left[G_t\mid s_t,a_t\right]=Q^\pi(s_t,a_t) and E[Gt∣st]=Vπ(st)\mathbb{E}\left[G_t\mid s_t\right]=V^\pi(s_t); subtracting the two:

E[Gt−Vπ(st)∣st,at]=Qπ(st,at)−Vπ(st)=Aπ(st,at)\mathbb{E}\left[G_t-V^\pi(s_t)\mid s_t,a_t\right]=Q^\pi(s_t,a_t)-V^\pi(s_t)=A^\pi(s_t,a_t)

So “return minus baseline” is not an arbitrary choice but the unbiased estimate of the advantage.

Step three: the expectation of the advantage over actions is exactly zero. By the fact in 1.2 that VV is a weighted average of QQ:

Ea∼π[Aπ(s,a)∣s]=∑aπ(a∣s)Qπ(s,a)−Vπ(s)=Vπ(s)−Vπ(s)=0\mathbb{E}_{a\sim\pi}\left[A^\pi(s,a)\mid s\right]=\sum_a\pi(a\mid s)Q^\pi(s,a)-V^\pi(s)=V^\pi(s)-V^\pi(s)=0

This step gives the geometric meaning of the baseline: subtracting VV shifts QQ along the “average under the policy” direction so that the mean of the advantage is zero. The strength of “raise good actions, lower bad actions” in the policy gradient is therefore naturally balanced and does not break normalization by pushing probabilities up overall.

Step four: why subtracting VV is better than subtracting a constant. A constant baseline removes only the “global offset”; the differences between states remain. V(s)V(s) varies with the state and also removes the term “how good this state itself is”, leaving only the differences that are comparable across actions. The better the state, the larger V(s)V(s), and the more the remaining weight concentrates on “actions better than the average level of that state”, giving a smaller variance.

Step five: why use G−VG-V rather than Q−VQ-V. Using QπQ^\pi directly requires additionally estimating values along the action dimension; GtG_t is already an unbiased single sample of QπQ^\pi, and subtracting a VV that only needs the state dimension gives an unbiased estimate of the advantage at the lowest estimation cost.

8.2 Division of labor between the actor and the critic

  • Actor (Actor): the policy πθ(a∣s)\pi_\theta(a\mid s), updated with the advantage AtA_t as the weight, raising the probability of high-advantage actions;
  • Critic (Critic): the value Vw(s)V_w(s), trained with temporal-difference or multi-step returns as regression labels, approximating “the expected return starting from ss”;
  • the two cooperate: the better the critic learns, the more accurate the baseline, the smaller the variance of the actor, and the more stable the policy update.

Why does the actor use the advantage rather than the return? Because the return GtG_t is large in absolute value and large in variance; after the V(s)V(s) baseline is subtracted only “the part beyond average” remains, so the gradient direction is cleaner and the variance smaller.

8.3 A2C: synchronous advantage actor-critic

A2C (Advantage Actor-Critic) estimates the advantage with nn-step returns:

At=∑k=0n−1γkrt+k+γnV(st+n)−V(st)A_t = \sum_{k=0}^{n-1}\gamma^k r_{t+k} + \gamma^n V(s_{t+n}) - V(s_t)

The overall objective is the sum of three losses:

L=−E[log⁡πθ(a∣s) At]+β E[(Vw(s)−Gt)2]−αH H(πθ)L = -\mathbb{E}\left[\log\pi_\theta(a\mid s)\,A_t\right] + \beta\,\mathbb{E}\left[\left(V_w(s)-G_t\right)^2\right] - \alpha_H\,H(\pi_\theta)
  • the first term: treating the advantage as a weight and using the policy gradient to raise the probability of actions that “bring a high advantage” (the leading minus sign is there because gradient ascent is wanted while deep learning frameworks minimize by default);
  • the second term: the critic’s regression, making VwV_w approach the true return;
  • the third term: entropy regularization (entropy regularization). H(πθ)H(\pi_\theta) is the policy entropy, measuring how random the policy is; a large entropy means a more uniform action distribution and more exploration. Subtracting αHH\alpha_H H (equivalent to adding negative entropy to the loss) encourages randomness and prevents the policy from becoming deterministic too early and getting stuck in a local optimum.

Why the three terms are composed this way: the first term is responsible for “moving toward good actions”, the second for “calibrating the referee”, and the third for “not locking the actions down too early”. Without the first there is no learning signal; without the second the baseline is inaccurate and the variance large; without the third the policy converges prematurely.

Derivation 17: what the gradients of the three A2C losses are, why coefficients are necessary, and how the bias and variance of $n$-step returns trade off

Step one: the gradient of the policy term. For

Lπ=−E[log⁡πθ(a∣s) A]L_\pi=-\mathbb{E}\left[\log\pi_\theta(a\mid s)\,A\right]

the gradient treats AA as a constant (detach):

∇θLπ=−E[A ∇θlog⁡πθ(a∣s)]\nabla_\theta L_\pi=-\mathbb{E}\left[A\,\nabla_\theta\log\pi_\theta(a\mid s)\right]

Gradient descent then moves along −∇Lπ=E[A∇θlog⁡π]-\nabla L_\pi=\mathbb{E}\left[A\nabla_\theta\log\pi\right], exactly the ascent direction of the policy gradient: the probability of A>0A>0 actions is raised and that of A<0A<0 actions lowered. The minus sign only translates “ascent” into the framework’s “minimization”.

Step two: the gradient and sign of the value term. For

LV=12E[(Vw(s)−G)2]L_V=\frac{1}{2}\mathbb{E}\left[\left(V_w(s)-G\right)^2\right]

the gradient is ∇wLV=E[(Vw(s)−G)∇wVw(s)]\nabla_wL_V=\mathbb{E}\left[\left(V_w(s)-G\right)\nabla_wV_w(s)\right]. After the update w←w−α∇wLVw\leftarrow w-\alpha\nabla_wL_V, if Vw>GV_w>G then VwV_w decreases, and if Vw<GV_w<G it increases, i.e., it moves toward the target GG. Note that GG must be detached here: it is a label, not a quantity to be optimized.

Step three: the gradient of the entropy term. The policy entropy is

H(πθ)=−∑aπθ(a∣s)log⁡πθ(a∣s)H(\pi_\theta)=-\sum_a\pi_\theta(a\mid s)\log\pi_\theta(a\mid s)

Differentiating with respect to the parameters (using ∇π=π∇log⁡π\nabla\pi=\pi\nabla\log\pi):

∇θH=−∑a∇θπθ(a∣s)(log⁡πθ(a∣s)+1)\nabla_\theta H=-\sum_a\nabla_\theta\pi_\theta(a\mid s)\left(\log\pi_\theta(a\mid s)+1\right)

Under a softmax parameterization this can be written further as ”−π⊙(log⁡π+1)-\pi\odot(\log\pi+1) minus its π\pi-weighted mean”, whose geometric meaning is pushing the distribution toward greater uniformity. Taking −αHH-\alpha_HH in the loss means the descent direction is αH∇H\alpha_H\nabla H, i.e., increasing the entropy. Note that when some action probability approaches 0 or 1, πalog⁡πa→0\pi_a\log\pi_a\to0 and the entropy gradient saturates accordingly—so entropy regularization can only act “while the policy is not yet fully deterministic” and cannot by itself prevent premature convergence.

Step four: why the three terms need coefficients. The three terms have different units: the policy term is “log-probability × advantage”, the value term is “squared error of the value”, and the entropy term is “nats (nat, the unit of entropy)”. Their magnitudes typically differ by one or two orders of magnitude. If the value term greatly exceeds the policy term, the gradient is dominated by the critic and the actor barely updates, showing up as “the value loss decreases steadily while neither the return nor the entropy moves”; if the entropy term is too large, the policy stays random for a long time and never learns deterministic behavior. The empirical values of the value coefficient β≈0.5\beta\approx0.5 and the entropy coefficient αH≈0.01\alpha_H\approx0.01 in practice are exactly what brings the three back to the same order of magnitude.

Step five: the bias-variance trade-off of nn-step returns. A2C uses

Gt(n)=∑k=0n−1γkrt+k+γnV(st+n)G_t^{(n)}=\sum_{k=0}^{n-1}\gamma^k r_{t+k}+\gamma^nV(s_{t+n})

Its bias comes from the bootstrapping at the last step, of order γn\gamma^n times the value estimation error; its variance comes from accumulating the rewards of the first nn steps, roughly σR2∑k=0n−1γ2k\sigma_R^2\sum_{k=0}^{n-1}\gamma^{2k}. Hence:

  • n=1n=1: the largest bias (almost entirely bootstrapped) and the smallest variance, degenerating to pure TD;
  • n→∞n\to\infty: the smallest bias and the largest variance, degenerating to pure MC;
  • nn between 5 and 32: the compromise point commonly used in engineering.

This limitation—“a fixed nn allows only one compromise point”—is exactly what GAE solves: GAE does not compromise on a single nn but takes an exponentially weighted average over all nn and tunes it continuously with one parameter λ\lambda.

8.4 The difference between A3C and A2C

A3C (Asynchronous Advantage Actor-Critic) is the asynchronous version of A2C (Mnih 2016): several workers each hold a copy of the policy parameters, interact with their own environments, compute gradients independently, and push the gradients back asynchronously to update the global network (lock-free).

The differences:

  • A3C: asynchronous updates, the workers do not wait for each other, the implementation is complex, and there are stale gradients (stale gradient, gradients computed with old parameters used to update new parameters);
  • A2C: synchronous updates; all workers complete a batch, then the gradients are computed together and averaged for one update, which is simpler to implement and more stable to train.

In practice A2C usually performs comparably to or even better than A3C, so modern implementations prefer A2C. The historical value of A3C lies in proving that “asynchronous parallelism” works in deep reinforcement learning, but the stale gradients and engineering complexity it brings made the synchronous version the mainstream default.

8.5 Pseudocode: A2C

Input: Actor parameters θ, Critic parameters w, step size α, advantage steps n, discount γ

Initialize: N environments in parallel

Loop (for each update time step):
    Clear the trajectory buffer
    For each environment in parallel:
        Interact with the environment for n steps using the current policy π_θ, collecting (s, a, r, s')
    Compute the advantage A_t of each time step with the n-step return
    Accumulate the policy loss −log π_θ(a|s) A_t, the value loss (V_w(s) − G_t)², and the entropy term −α_H H(π_θ)
    Take a gradient-descent step on the total loss, updating θ and w

Section-by-section commentary.

  1. Why open NN environments synchronously: the consecutive samples of a single environment are highly correlated, and the gradient would point in the same direction repeatedly over a short period. Parallel environments provide samples of “the same moment, different initial states”, decorrelating naturally and keeping the batch size controllable. A3C achieves a similar effect with asynchronous multithreading, but synchronous batching is simpler to implement and friendlier to hardware.
  2. What the nn-step return is: the target of each time step is not GtG_t waiting for the episode to end, but “the real rewards of nn steps plus the value estimate at the nn-th step”. It lies between one-step TD and Monte Carlo: too small an nn gives a large bias (much bootstrapping), too large an nn gives a large variance (much accumulation). The common choices are n=5n=5, 16, or 32, or simply replacing the fixed number of steps with GAE.
  3. The difference between the advantage and the value target: the advantage A^t=Gt(n)−Vw(st)\hat{A}_t = G_t^{(n)} - V_w(s_t) is for the Actor; the value target is just Gt(n)G_t^{(n)}, for the Critic to regress. The two share the same nn-step return, but one is “a relative quantity after subtracting the baseline” and the other “an absolute quantity”; they must not be mixed up.
  4. Why the three losses are combined this way: the policy loss −log⁡πθ(a∣s)A^t-\log\pi_\theta(a|s)\hat{A}_t drives up the probability of good actions; the value loss (⋅)2(\cdot)^2 trains the baseline; the entropy term −centH-c_{\mathrm{ent}}H maintains exploration. The three typically differ greatly in magnitude and must be balanced by coefficients (the value coefficient and the entropy coefficient), otherwise one of them dominates the gradient.
  5. One update with all samples together: unlike REINFORCE’s “one trajectory, one update”, A2C aggregates N×nN\times n samples into a single batch and updates with one backpropagation, giving higher sample efficiency and a more stable gradient.

Gradient flow and detach. The easiest thing to get wrong here is the dual role of Vw(st)V_w(s_t): in the advantage it is the baseline (which should be detached, so that the policy gradient is not back-propagated to the Critic through it), while in the value loss it is the prediction (which must carry gradients). The correct approach is one forward pass producing v, then building the advantage and target with v.detach() and computing the value loss with v itself:

v = critic(s)                       # needs gradients
adv = (returns - v.detach())        # baseline: detach
loss_pi = -(logp * adv.detach()).mean()
loss_v = ((v - returns) ** 2).mean()

If the same gradient-carrying v were used in both places, the policy gradient would acquire an extra component “flowing back through the Critic”, and the Actor would change its actions in order to reduce the value error, which is not the direction the policy gradient theorem intends.

Implementation pitfall checklist.

SymptomPossible causeFix
Policy and value oscillate togetherShared network with too large a value lossSeparate the networks, or reduce the value coefficient
The advantage is systematically too large or too smallThe nn-step return is not handled with the terminal maskDo not bootstrap at terminal steps; truncated steps still bootstrap
Exploration is lost earlyEntropy coefficient too small, or the policy’s log⁡σ\log\sigma has no lower boundRaise the entropy coefficient, put a lower bound on the variance
The value loss decreases but the return does not riseThe advantage uses a value that was not detached, or the sign is flippedDetach the advantage, check the sign of -logp*adv
The learning rate must be retuned for different tasksReward scales differ, the advantage is not normalizedNormalize the advantage within the batch, scale the rewards

A2C is a “just works” baseline: simple to implement, few hyperparameters, and functional for most continuous and discrete tasks. Its weakness is that neither sample efficiency nor stability matches PPO—no clipping, no importance-sampling reuse, one use per batch of data. So in engineering PPO is usually used directly, while A2C serves as the teaching example for understanding the actor-critic structure.


9. GAE: Generalized Advantage Estimation

9.1 An Unavoidable Question: How Should the Advantage Be Estimated

The advantage function is defined as

A(s,a)=Q(s,a)−V(s)A(s,a) = Q(s,a) - V(s)

It measures “how much better than average it is to take action aa in state ss.” The gradients of almost all modern actor-critic algorithms (A2C, PPO, TRPO) are based on an advantage estimate, and the problem is how exactly to estimate the advantage. Both ends of the spectrum have drawbacks:

  • Using a one-step temporal difference (TD) error as the advantage: δt=rt+γV(st+1)−V(st)\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t). This has large bias and small variance—only rtr_t in the expression is a real signal, everything else relies on bootstrapping from the estimated value VV, so when VV is inaccurate the bias persists; the variance is small because it accumulates only a single random reward.
  • Using the multi-step (up to the end of the episode) return as the advantage: Gt∞=∑k=0∞γkrt+kG_t^{\infty} = \sum_{k=0}^{\infty}\gamma^k r_{t+k}, then subtracting V(st)V(s_t). This has small bias and large variance—there is no bootstrapping and all rewards are real, so it is unbiased; but dozens or hundreds of random rewards along the trajectory are summed together, and the randomness grows linearly with them.

Generalized Advantage Estimation (GAE, Schulman 2016) uses exponential weighting to smoothly combine advantage estimates of different lengths, and uses a single parameter λ∈[0,1]\lambda\in[0,1] to unify the bias–variance trade-off.

9.2 The GAE Formula

First define the kk-step TD error

δtV=rt+γV(st+1)−V(st)\delta_t^V = r_t + \gamma V(s_{t+1}) - V(s_t)

The GAE advantage is the exponentially weighted sum of these TD errors:

AtGAE(γ,λ)=∑l=0∞(γλ)l δt+lV=δtV+γλ δt+1V+(γλ)2 δt+2V+⋯A_t^{\mathrm{GAE}(\gamma,\lambda)} = \sum_{l=0}^{\infty}(\gamma\lambda)^l\,\delta_{t+l}^V = \delta_t^V + \gamma\lambda\,\delta_{t+1}^V + (\gamma\lambda)^2\,\delta_{t+2}^V + \cdots

In other words, it is neither “trust only one step” nor “trust all the way to the end of the episode,” but rather the farther a TD error is, the more its weight decays by γλ\gamma\lambda. The parameter λ\lambda is exactly the knob that controls how fast the decay is.

Derivation 18: Why GAE can be written as an exponentially weighted sum of TD errors (including the $\lambda\to0/1$ limits and the recursive form)

Step one: Definition of the nn-step advantage. Use the nn-step return minus the baseline:

At(n)=∑k=0n−1γkrt+k+γnV(st+n)−V(st)A_t^{(n)}=\sum_{k=0}^{n-1}\gamma^k r_{t+k}+\gamma^nV(s_{t+n})-V(s_t)

Step two: Rewrite the nn-step return as an accumulation of TD errors (telescoping sum). Note that

∑k=0n−1γkδt+k=∑k=0n−1γk[rt+k+γV(st+k+1)−V(st+k)]\sum_{k=0}^{n-1}\gamma^k\delta_{t+k}=\sum_{k=0}^{n-1}\gamma^k\left[r_{t+k}+\gamma V(s_{t+k+1})-V(s_{t+k})\right]

Expanding the sum, the intermediate terms cancel in pairs:

=∑k=0n−1γkrt+k+∑k=0n−1[γk+1V(st+k+1)−γkV(st+k)]=∑k=0n−1γkrt+k+γnV(st+n)−V(st)=\sum_{k=0}^{n-1}\gamma^k r_{t+k}+\sum_{k=0}^{n-1}\left[\gamma^{k+1}V(s_{t+k+1})-\gamma^kV(s_{t+k})\right]=\sum_{k=0}^{n-1}\gamma^kr_{t+k}+\gamma^nV(s_{t+n})-V(s_t)

The right-hand side is exactly At(n)A_t^{(n)}. So we obtain an important identity:

At(n)=∑k=0n−1γkδt+kA_t^{(n)}=\sum_{k=0}^{n-1}\gamma^k\delta_{t+k}

Step three: Take an exponentially weighted average over all nn. The definition of GAE is “the weighted average of the nn-step advantages of all lengths, with weights (1−λ)λn−1(1-\lambda)\lambda^{n-1}”:

AtGAE=(1−λ)∑n=1∞λn−1At(n)=(1−λ)∑n=1∞λn−1∑k=0n−1γkδt+kA_t^{\mathrm{GAE}}=(1-\lambda)\sum_{n=1}^{\infty}\lambda^{n-1}A_t^{(n)} =(1-\lambda)\sum_{n=1}^{\infty}\lambda^{n-1}\sum_{k=0}^{n-1}\gamma^k\delta_{t+k}

Swap the order of the two sums. The term δt+k\delta_{t+k} appears only when n≥k+1n\ge k+1, and its total weight is

(1−λ)∑n=k+1∞λn−1=(1−λ)λk1−λ=λk(1-\lambda)\sum_{n=k+1}^{\infty}\lambda^{n-1}=(1-\lambda)\frac{\lambda^k}{1-\lambda}=\lambda^k

Therefore

AtGAE=∑k=0∞λkγkδt+k=∑l=0∞(γλ)lδt+lA_t^{\mathrm{GAE}}=\sum_{k=0}^{\infty}\lambda^k\gamma^k\delta_{t+k}=\sum_{l=0}^{\infty}(\gamma\lambda)^l\delta_{t+l}

which is exactly the formula in the main text. Its origin is not “weights pieced together by intuition,” but the fact that “the exponentially weighted average of all nn-step advantages” is mathematically equivalent to “the sum of TD errors decaying by γλ\gamma\lambda.”

Step four: The two endpoints of λ\lambda. When λ=0\lambda=0 only the l=0l=0 term remains, At=δtA_t=\delta_t, i.e., the one-step TD advantage; when λ→1\lambda\to1 the weights do not decay, and the telescoping identity from step two (taking n→∞n\to\infty) gives ∑k=0∞γkδt+k=Gt−V(st)\sum_{k=0}^{\infty}\gamma^k\delta_{t+k}=G_t-V(s_t), i.e., the Monte Carlo advantage. This also shows that λ\lambda is not “a newly invented parameter,” but the decay rate of “an exponential weighting over the distribution of nn-step advantages.”

Step five: The recursive form and the terminal mask. Shifting the weighted sum directly:

At=δt+γλ δt+1+(γλ)2δt+2+⋯=δt+γλAt+1A_t=\delta_t+\gamma\lambda\,\delta_{t+1}+(\gamma\lambda)^2\delta_{t+2}+\cdots=\delta_t+\gamma\lambda A_{t+1}

This is the recursion of 9.4. At a real termination (dt=1d_t=1), At+1A_{t+1} belongs to the next episode and must be cut off, hence the factor (1−dt)(1-d_t); at the same time the bootstrapping term inside δt\delta_t must also be multiplied by (1−dt)(1-d_t). Neither mask can be omitted.

Step six: The effective horizon and the bias–variance trade-off. The weights decay by (γλ)l(\gamma\lambda)^l, so the effective summation length is about 1/(1−γλ)1/(1-\gamma\lambda). With λ=0.95\lambda=0.95 and γ=0.99\gamma=0.99 this is about 67 steps; with λ=0.9\lambda=0.9 it is about 52 steps. The larger λ\lambda is, the more real rewards are used and the smaller the bias, but the more random quantities are accumulated and the larger the variance. So tuning λ\lambda is essentially tuning the “effective horizon,” which is the same thing as tuning the nn-step return, only smoother and continuously adjustable.

9.3 λ\lambda Interpolates Between the Two Ends

  • λ=0\lambda=0: only the first term remains, degenerating to the one-step TD advantage At=δtVA_t=\delta_t^V, with high bias and low variance;
  • λ→1\lambda\to1: the weights barely decay, approaching the Monte Carlo return advantage, with low bias and high variance;
  • λ\lambda between 0.9 and 0.99: usually the best compromise between the two. In practice λ\lambda is often fixed (e.g., 0.95) and rarely tuned.

9.4 Recursive Computation: Pushing Back from the End of the Trajectory

Computing directly from the definition requires an infinite sum, so in practice a recursion is used (AtA_t depends on At+1A_{t+1}, so it must be pushed back from the end):

At=δt+γλ (1−dt) At+1,AT=0A_t = \delta_t + \gamma\lambda\,(1-d_t)\,A_{t+1},\qquad A_T = 0

where dt∈{0,1}d_t\in\{0,1\} is the real termination mask (dt=1d_t=1 means the episode really ended). The computation proceeds backward from the end, doing one multiply-add per step, with complexity O(T)O(T).

Two boundaries that are easy to get wrong:

  • Termination and truncation must be separated: δt\delta_t must also be written as δt=rt+γ(1−dt)V(st+1)−V(st)\delta_t = r_t + \gamma(1-d_t)V(s_{t+1}) - V(s_t). At a real termination the bootstrapping is cut off; at a time truncation (being forcibly interrupted on reaching the step limit) the bootstrapping must be kept and dtd_t recorded as 0, otherwise the value function will fall out of thin air near the time limit, forming a “false cliff.”
  • AT=0A_T=0 holds only for termination: if the trajectory was truncated, the bootstrapping value V(sT)V(s_T) of the truncated state should be passed in at the end, in which case ATA_T degenerates to δT\delta_T rather than 0.

9.5 Pseudocode: Computing GAE

Input: the rewards r_0, …, r_{n−1} of an n-step trajectory, the values V(s_0), …, V(s_n) provided by the Critic,
       done_0, …, done_{n−1} (1 = real termination; time truncation recorded as 0), parameters γ, λ

1. Compute the TD error at each step:
   For t = 0, …, n−1:
       δ_t = r_t + γ (1 − done_t) V(s_{t+1}) − V(s_t)

2. Recursively compute the advantages backward:
   A_n = 0
   For t = n−1 down to 0:
       A_t = δ_t + γλ (1 − done_t) A_{t+1}

3. Generate the value regression targets:
   For t = 0, …, n−1:
       Ret_t = A_t + V(s_t)

Output: the advantage sequence A_0, …, A_{n−1}, and the value targets Ret_0, …, Ret_{n−1}

Three implementation pitfalls:

  1. The mask must be applied twice: step 1 masks the bootstrapping term, and step 2 masks At+1A_{t+1}. If only the first place is changed, the terminal step will pull the advantage of the next episode in, creating cross-episode contamination.
  2. done is not the same as “the episode ended”: the time limit and external interruptions are both truncations, the environment can still continue, and the bootstrapping must be kept. If the environment returns only one boolean, split it into the two fields done and truncated in the wrapper layer, and let GAE use only done.
  3. Ret must use the unnormalized AA: advantage normalization only serves the policy loss; if the normalized AA is added back to VV, the value target is shifted and rescaled as a whole, and the value loss coefficient would have to be retuned before it could converge.

9.6 Why GAE Works Well, and What It Is Not

Why it works well: it uses a single parameter λ\lambda to continuously adjust between “the multi-step return (large variance)” and “the one-step TD (large bias),” and in practice it is usually easier to tune and more stable than a fixed nn-step. It turns “how much real reward to use and how much bootstrapped estimate to use” into an adjustable knob.

Note: GAE needs the Critic to provide V(s)V(s), so it can only be used in an actor-critic architecture with a critic. It is not a complete algorithm itself, but a standard component of A2C, PPO, and TRPO—it can be understood as an “advantage estimator” rather than an “algorithm.”


10. TRPO: Trust Region Policy Optimization

10.1 Background: What to Do When the Policy Collapses

Ordinary policy gradients (REINFORCE, A2C) update the policy by “gradient × step size.” If the step size is too large, the new policy πnew\pi_{\mathrm{new}} will be too far from the old policy πold\pi_{\mathrm{old}}, causing a sudden performance collapse; this phenomenon is called policy collapse.

The idea of TRPO (Trust Region Policy Optimization, Schulman 2015) is: guarantee that after every update the new policy lies within the “trust region” of the old policy—use the Kullback-Leibler divergence (KL divergence, an asymmetric measure of the difference between two probability distributions, abbreviated as KL divergence below) to measure the difference between the old and new policies and make it a hard constraint, thereby guaranteeing that the performance does not decrease monotonically after the update.

The objective (using the probability ratio of the new and old policies as the surrogate objective):

max⁡θ L(θ)=E[πθ(a∣s)πθold(a∣s) A]s.t.E[KL(πθold(⋅∣s) ∥ πθ(⋅∣s))]≤δ\max_\theta\ L(\theta) = \mathbb{E}\left[\frac{\pi_\theta(a\mid s)}{\pi_{\theta_{\mathrm{old}}}(a\mid s)}\,A\right] \quad \text{s.t.}\quad \mathbb{E}\left[\mathrm{KL}\left(\pi_{\theta_{\mathrm{old}}}(\cdot\mid s)\,\|\,\pi_\theta(\cdot\mid s)\right)\right]\le\delta

Three elements:

  • Probability ratio rt(θ)=πθ(a∣s)/πθold(a∣s)r_t(\theta) = \pi_\theta(a\mid s) / \pi_{\theta_{\mathrm{old}}}(a\mid s): the ratio of the probabilities that the new and old policies choose the same action;
  • Objective: maximize rt(θ)r_t(\theta) weighted by the advantage AA, i.e., “make high-advantage actions more probable under the new policy”;
  • Constraint: the average KL divergence between the new and old policies does not exceed the trust radius δ\delta, guaranteeing “a stable walk.”

Why use the probability ratio instead of optimizing the return directly? Because we only have data sampled by the old policy at hand, and cannot directly compute the expected return of the new policy; using importance sampling (estimating the expectation under a new distribution with samples drawn from the old distribution) to rewrite “the expectation of the new policy” as “the expectation of the old policy + probability-ratio weights” lets us reuse the old data. The constraint prevents an excessively large probability ratio from making the importance-sampling variance explode.

Derivation 19: Where the TRPO surrogate objective comes from (the performance difference lemma), why the constraint is KL, and how the step-size formula is solved

Step one: The performance difference lemma. Let dπ(s)d_\pi(s) be the discounted state visitation distribution under policy π\pi; then the performance difference of two policies can be written as

J(π′)−J(π)=11−γ Es∼dπ′[∑aπ′(a∣s) Aπ(s,a)]J(\pi')-J(\pi)=\frac{1}{1-\gamma}\,\mathbb{E}_{s\sim d_{\pi'}}\left[\sum_a\pi'(a\mid s)\,A^\pi(s,a)\right]

The derivation idea: expand the return difference of the two trajectories step by step according to “the state first visited,” where each step’s difference is “comparing the advantages of two actions in the same state” and the weight is the frequency with which that state is visited. The meaning of the lemma is: the performance difference depends only on the expected advantage of the new policy over the states visited by the new policy.

Step two: Replace “the visitation distribution of the new policy” with “the visitation distribution of the old policy.” The dπ′d_{\pi'} in the lemma depends on the new policy being solved for and cannot be estimated from old data. TRPO makes an approximation: replace dπ′d_{\pi'} with dπoldd_{\pi_{\mathrm{old}}}, obtaining the surrogate objective

Lπold(π′)=Es∼dπold,a∼π′[Aπold(s,a)]=Es∼dπold,a∼πold[π′(a∣s)πold(a∣s) Aπold(s,a)]L_{\pi_{\mathrm{old}}}(\pi')=\mathbb{E}_{s\sim d_{\pi_{\mathrm{old}}},a\sim\pi'}\left[A^{\pi_{\mathrm{old}}}(s,a)\right]=\mathbb{E}_{s\sim d_{\pi_{\mathrm{old}}},a\sim\pi_{\mathrm{old}}}\left[\frac{\pi'(a\mid s)}{\pi_{\mathrm{old}}(a\mid s)}\,A^{\pi_{\mathrm{old}}}(s,a)\right]

The second equality is importance sampling: replacing “sampling according to the new policy” with “sampling according to the old policy × the probability ratio.” This is exactly why πθ/πθold\pi_\theta/\pi_{\theta_{\mathrm{old}}} appears in the objective in the main text.

Step three: The approximation error is controlled by the policy difference. The difference between the visitation distributions of the two policies can be controlled by the total variation distance of the policies, with the standard bound

∣J(π′)−Lπold(π′)∣≤4ϵγ(1−γ)2max⁡sDTV(π′∥πold)2\left|J(\pi')-L_{\pi_{\mathrm{old}}}(\pi')\right|\le\frac{4\epsilon\gamma}{(1-\gamma)^2}\max_sD_{\mathrm{TV}}\left(\pi'\|\pi_{\mathrm{old}}\right)^2

where ϵ=max⁡s,a∣Aπ(s,a)∣\epsilon=\max_{s,a}\left|A^\pi(s,a)\right|. As long as the policy difference is made small, the surrogate objective is close enough to the true objective—this is the rigorous origin of the “trust region,” not a heuristic. Then, by Pinsker’s inequality DTV2≤12DKLD_{\mathrm{TV}}^2\le\frac12D_{\mathrm{KL}}, changing the constraint to KL is still safe (slightly conservative).

Step four: Linearize the objective and quadratize the constraint. Expand at θold\theta_{\mathrm{old}} and drop the constant term:

L(θ)≈g⊤(θ−θold),g=∇θL(θold)L(\theta)\approx g^\top\left(\theta-\theta_{\mathrm{old}}\right),\qquad g=\nabla_\theta L(\theta_{\mathrm{old}}) E[KL(πθold∥πθ)]≈12(θ−θold)⊤F(θ−θold)\mathbb{E}\left[\mathrm{KL}\left(\pi_{\theta_{\mathrm{old}}}\|\pi_\theta\right)\right]\approx\frac12\left(\theta-\theta_{\mathrm{old}}\right)^\top F\left(\theta-\theta_{\mathrm{old}}\right)

where FF is the Hessian of the KL, equal to the Fisher information matrix:

F=E[∇θlog⁡πθ(∇θlog⁡πθ)⊤]F=\mathbb{E}\left[\nabla_\theta\log\pi_\theta\left(\nabla_\theta\log\pi_\theta\right)^\top\right]

Step five: Solve the quadratic constrained problem to obtain the natural gradient step. Let s=θ−θolds=\theta-\theta_{\mathrm{old}}; the Lagrangian is

L=g⊤s−μ2(s⊤Fs−2δ)\mathcal{L}=g^\top s-\frac{\mu}{2}\left(s^\top Fs-2\delta\right)

Setting the derivative with respect to ss to zero: g−μFs=0⇒s=1μF−1gg-\mu Fs=0\Rightarrow s=\frac{1}{\mu}F^{-1}g. Substitute back into the constraint and take equality:

12(1μ)2g⊤F−1g=δ⇒1μ=2δg⊤F−1g\frac12\left(\frac{1}{\mu}\right)^2g^\top F^{-1}g=\delta\Rightarrow\frac{1}{\mu}=\sqrt{\frac{2\delta}{g^\top F^{-1}g}}

Hence

θ=θold+2δg⊤F−1g F−1g\theta=\theta_{\mathrm{old}}+\sqrt{\frac{2\delta}{g^\top F^{-1}g}}\,F^{-1}g

F−1gF^{-1}g is called the natural gradient: it replaces the length of the ordinary gradient in parameter space with a length in “distribution space,” so that the same parameter step produces a similar policy change across different parameterizations.

Step six: Why use conjugate gradient instead of matrix inversion. FF is a P×PP\times P matrix (PP is the number of parameters, which can reach millions), and both explicit construction and inversion are O(P3)O(P^3), which is infeasible. Conjugate gradient (CG) only needs the ability to “multiply FF by a vector,” and FvFv can be estimated at O(P)O(P) cost with the Fisher-vector product:

Fv=E[∇θlog⁡πθ((∇θlog⁡πθ)⊤v)]Fv=\mathbb{E}\left[\nabla_\theta\log\pi_\theta\left(\left(\nabla_\theta\log\pi_\theta\right)^\top v\right)\right]

In implementation, one forward-backward pass gives ∇log⁡π\nabla\log\pi, the inner product with vv gives a scalar, and one more backward pass gives FvFv; about 10 iterations are enough to approximately solve for F−1gF^{-1}g.

Step seven: Why the direction of the KL is “old ‖ new.” The expectation in the constraint is taken under πold\pi_{\mathrm{old}}:

Es∼dold[KL(πold∥πθ)]=Es,a∼πold[log⁡πold(a∣s)πθ(a∣s)]\mathbb{E}_{s\sim d_{\mathrm{old}}}\left[\mathrm{KL}\left(\pi_{\mathrm{old}}\|\pi_\theta\right)\right]=\mathbb{E}_{s,a\sim\pi_{\mathrm{old}}}\left[\log\frac{\pi_{\mathrm{old}}(a\mid s)}{\pi_\theta(a\mid s)}\right]

This expectation can be estimated unbiasedly directly from the old-policy samples at hand. If it were written as KL(πθ∥πold)\mathrm{KL}(\pi_\theta\|\pi_{\mathrm{old}}), the expectation would have to be taken under πθ\pi_\theta and could only be estimated by importance sampling, with a much larger variance. So the choice of direction is a technical decision “to make estimation from old data possible,” and it is also consistent with the bound in step three.

Step eight: Line search fixes the error of the quadratic approximation. The quadratic approximation is only trustworthy locally, and the step computed in step five may make the true KL exceed the bound. In practice one backtracks over α=1,12,14,…\alpha=1,\frac12,\frac14,\dots until the sampled estimate of the KL does not exceed δ\delta; if all attempts fail, one falls back to an ordinary policy gradient step. This step repairs “the approximate solution” into “a feasible solution,” and it is the last link in the monotonic-improvement guarantee of TRPO.

Solving the constrained nonlinear optimization directly is very expensive. TRPO makes two approximations:

  1. Linearize the objective at the old parameters (a first-order approximation, giving the gradient);
  2. Quadratize the constraint (using the Fisher information matrix, i.e., the second-order expansion of the KL divergence);
  3. Use conjugate gradient (an iterative solver that relies only on matrix–vector products and does not explicitly construct the matrix) to solve this quadratic constrained problem efficiently;
  4. Then use a line search to ensure that the actual KL does not exceed the constraint.

This avoids inverting a large matrix directly—when the number of parameters reaches millions, explicitly constructing and inverting the Fisher matrix is infeasible.

10.3 Pseudocode: TRPO

Input: policy π_θ, Critic V_w, trust radius δ, GAE parameters λ, γ

Loop (for each iteration):
    1. Interact with the environment using the current policy π_θ to collect a batch of trajectories
    2. Compute the advantages A_t with GAE, and update the Critic parameters w by regression
    3. Compute the probability ratio r_t(θ) = π_θ(a_t|s_t) / π_θ_old(a_t|s_t)
    4. Construct the objective:
           L(θ) = (1/N) Σ_t r_t(θ) · A_t
       Constraint:
           KL_vg = (1/N) Σ_t KL(π_θ_old(·|s_t) ‖ π_θ(·|s_t)) ≤ δ
    5. Use conjugate gradient + line search to maximize L(θ) within the constraint
    6. θ_old ← θ

Line-by-line commentary.

  1. Step 1 samples a whole batch of data that serves only this one update: TRPO, like PPO, is an on-policy algorithm, and importance sampling is reliable only when “the new and old policies are close enough.” The KL constraint is exactly what bounds the radius within which this approximation holds.
  2. The advantage in step 2 must be computed first: in the objective L(θ)L(\theta), AtA_t is a constant weight and must not carry gradients. In practice this step uses GAE (see Section 9); the value network is regressed and updated separately in this step, not mixed into the same backward pass as the policy objective.
  3. The probability ratio in step 3 is the core of the “surrogate objective”: L(θ)=E[rt(θ)At]L(\theta)=\mathbb{E}[r_t(\theta)A_t] is a first-order approximation of the true objective J(θ)J(\theta) (with the same gradient at θ=θold\theta=\theta_{\mathrm{old}}). Precisely because it is only a first-order approximation, a KL constraint is needed to restrict the range in which “the approximation is valid”—this is the fundamental difference between TRPO and an ordinary policy gradient.
  4. The KL direction in step 4 is easy to write backwards: the paper adopts KL(πold∥πθ)\mathrm{KL}(\pi_{\mathrm{old}}\|\pi_\theta). The sampled estimate of this direction is more stable on old-policy data (the expectation is taken under πold\pi_{\mathrm{old}}), and it is consistent with the setting of “evaluating the new policy with old data.” Writing KL(πθ∥πold)\mathrm{KL}(\pi_\theta\|\pi_{\mathrm{old}}) also runs numerically, but the estimate has a larger variance and the theoretical guarantee is different.
  5. What the conjugate gradient in step 5 solves: quadratize the constraint at θold\theta_{\mathrm{old}}, giving 12(θ−θold)TH(θ−θold)≤δ\frac{1}{2}(\theta-\theta_{\mathrm{old}})^TH(\theta-\theta_{\mathrm{old}})\le\delta, where HH is the Hessian of the KL, equivalent to the Fisher information matrix (the second moment of the log-likelihood approximating the curvature). Conjugate gradient needs only “matrix–vector products” and does not have to explicitly construct HH, which suits neural networks with a huge number of parameters.
  6. Why the line search cannot be omitted: the quadratic approximation is only locally trustworthy, and the step computed from the formula may still exceed the true KL constraint. The line search backtracks over α,α/2,α/4,…\alpha, \alpha/2, \alpha/4,\dots until the sampled estimate of the actual KL does not exceed δ\delta; if all attempts fail, one usually falls back to an ordinary policy gradient update to guarantee progress every round.
  7. Step 6 updates the old policy: the next round’s probability ratio uses the new parameters as the denominator, which is a necessary step of the “on-policy + importance sampling” loop.

Implementation pitfall checklist.

SymptomPossible causeFix
The KL estimate deviates greatly from the true valueToo few samples in the mini-batch, too few conjugate gradient iterationsIncrease the batch size, run at least 10 CG iterations, add a damping term
Performance falls off a cliff after the updateThe line search does not take effect, δ\delta is too largeCheck the actual KL strictly, set δ\delta on the order of 0.01
Extremely slow computationThe Fisher matrix is computed for every sampleApproximate with the Fisher-vector product (matrix–vector product), avoid the explicit matrix
The policy barely movesδ\delta too small, damping coefficient too largeIncrease δ\delta appropriately, reduce the damping
The value network does not learnValue loss and policy objective are mixed, the advantage is not detachedOptimize separately, detach the advantage

The value of TRPO lies not in “still using it today,” but in the fact that it was the first to turn “how conservative a policy update should be” into an optimizable mathematical problem. Once you understand its constraint form and then look at PPO’s clipping, you will see that the latter is merely a cheap approximation of the former—this is also the easy-to-miss point in 17.3, “TRPO and PPO are essentially the same.”

10.4 Three Details Explained

What is the probability ratio rt(θ)r_t(\theta)? It measures “whether the new policy is more or less aggressive than the old policy in choosing this action.” r>1r>1 means the new policy has a higher probability of choosing that action; r<1r<1 means lower. The meaning of the objective L=E[r⋅A]L=\mathbb{E}[r\cdot A] is: if A>0A>0, increase the probability of such actions (rr becomes larger); if A<0A<0, decrease it.

Why can the KL constraint prevent collapse? KL(πold∥πnew)\mathrm{KL}(\pi_{\mathrm{old}}\|\pi_{\mathrm{new}}) measures the difference between two distributions. Forcing it to be ≤δ\le\delta is equivalent to “the new policy must not be too far from the old policy,” so the gradient estimate (based on old-policy samples) is still approximately valid and the update is safer.

Why are conjugate gradient and line search needed? Solving the constrained nonlinear optimization directly is very expensive. After TRPO linearizes the objective and quadratizes the constraint, the constrained direction can be solved efficiently with conjugate gradient, and then a line search ensures that the actual KL does not exceed the bound.

10.5 Limitations and Status of TRPO

Limitations: complex to implement (conjugate gradient, Fisher information matrix approximation), computationally expensive, and sensitive to noise. PPO replaces this complicated machinery with a simpler “clipping” approximation.

Status: the original TRPO paper was used together with GAE (the paper titles are “Trust Region Policy Optimization” and “High-Dimensional Continuous Control Using GAE”), with the advantage AtA_t provided by GAE. It was the first systematic answer to the question “how to update the policy safely in large steps,” and it directly gave rise to PPO.


11. PPO: Proximal Policy Optimization

11.1 Principle: Replacing the KL Constraint with Clipping

PPO (Proximal Policy Optimization, Schulman 2017) is one of the most popular and most stable deep reinforcement learning algorithms today. It keeps TRPO’s idea of “don’t walk too far,” but replaces the complicated “KL hard constraint + conjugate gradient” with a simple first-order optimization objective: clipping the probability ratio. It needs only standard gradient descent, is simple to implement, and performs on par with or even better than TRPO.

PPO’s clipped surrogate objective:

LCLIP(θ)=Et[min⁡(rt(θ) At, clip(rt(θ), 1−ε, 1+ε)At)]L^{\mathrm{CLIP}}(\theta) = \mathbb{E}_t\left[\min\left(r_t(\theta)\,A_t,\ \mathrm{clip}\left(r_t(\theta),\,1-\varepsilon,\,1+\varepsilon\right)A_t\right)\right]

where:

  • rt(θ)=πθ(at∣st)/πθold(at∣st)r_t(\theta) = \pi_\theta(a_t\mid s_t) / \pi_{\theta_{\mathrm{old}}}(a_t\mid s_t): the probability ratio of the new and old policies;
  • clip(r,1−ε,1+ε)\mathrm{clip}(r,1-\varepsilon,1+\varepsilon): restricts rr to [1−ε,1+ε][1-\varepsilon,1+\varepsilon] (ε\varepsilon is often taken as 0.2);
  • min⁡\min takes the smaller of the two: when A>0A>0 (worth encouraging), even if rr wants to exceed the upper limit, the gain is not allowed to exceed (1+ε)A(1+\varepsilon)A, preventing over-rewarding; when A<0A<0 (should be suppressed), even if rr wants to go below the lower limit, the loss is not allowed to exceed (1−ε)A(1-\varepsilon)A.

The intuition of clipping: encourage the policy to improve within the “trust region”—when the ratio goes beyond [1−ε,1+ε][1-\varepsilon,1+\varepsilon] the gradient is cut off, thereby limiting the update magnitude to a controllable range and preventing a single step from being too large.

11.2 Why Clipping Can Approximate a “Trust Region”

If A>0A>0: the objective takes min⁡(rA, (1+ε)A)\min(rA,\ (1+\varepsilon)A). Once rr exceeds 1+ε1+\varepsilon, the second term becomes a constant and its gradient with respect to θ\theta is 0—increasing rr further brings no more gain, so there is no incentive to keep increasing it.

If A<0A<0: the objective takes min⁡(rA, (1−ε)A)\min(rA,\ (1-\varepsilon)A). Since AA is negative, the smaller rr is (the further below the lower limit), the more negative the first term; once rr falls below 1−ε1-\varepsilon, the second term becomes a constant and the gradient is likewise 0—decreasing rr further brings no more gain.

Thus, whether encouraging or suppressing, the policy is “softly” restricted near the old policy, with an effect similar to a KL constraint, but requiring only one forward pass, one clipping operation, and one backward pass.

Derivation 20: The piecewise gradient of the PPO clipped objective, why $\min$ is used, and the conversion between $\varepsilon$ and the KL radius

Step one: Combine min⁡\min and clip\mathrm{clip} into a piecewise form. Fix the advantage AA and discuss the relative position of rr:

  • If A>0A>0: when r≤1+εr\le1+\varepsilon, rA≤(1+ε)ArA\le(1+\varepsilon)A and min⁡\min takes rArA; when r>1+εr>1+\varepsilon it takes (1+ε)A(1+\varepsilon)A.
  • If A<0A<0: because dividing by a negative number flips the inequality, min⁡(rA,(1−ϵ)A)\min\left(rA,(1-\epsilon)A\right) is equivalent to max⁡(r,1−ε)A\max\left(r,1-\varepsilon\right)A; when r≥1−εr\ge1-\varepsilon it takes rArA, and when r<1−εr<1-\varepsilon it takes (1−ε)A(1-\varepsilon)A.

Combined into a single branch:

L(r)={min⁡(r, 1+ε)A,A>0max⁡(r, 1−ε)A,A<0L(r)= \begin{cases} \min\left(r,\,1+\varepsilon\right)A, & A>0\\[2pt] \max\left(r,\,1-\varepsilon\right)A, & A<0 \end{cases}

Step two: Take the piecewise derivative with respect to rr.

∂L∂r={A,A>0, r<1+ε0,A>0, r>1+εA,A<0, r>1−ε0,A<0, r<1−ε\frac{\partial L}{\partial r}= \begin{cases} A, & A>0,\ r<1+\varepsilon\\ 0, & A>0,\ r>1+\varepsilon\\ A, & A<0,\ r>1-\varepsilon\\ 0, & A<0,\ r<1-\varepsilon \end{cases}

The key observation: the region where the gradient is zero is exactly the region where the policy has already gone too far in the favorable direction—A>0A>0 and rr exceeds the upper limit, or A<0A<0 and rr falls below the lower limit. If rr moves in the unfavorable direction (rr decreases when A>0A>0, rr increases when A<0A<0), the gradient still exists and pulls the policy back.

Step three: Therefore clip is not “pinning rr inside the interval.” It only cancels “excess reward,” and does not prevent “reverse correction.” This directly determines PPO’s noise resistance: if a batch of data contains wrong positive advantages and the policy is pushed too far, the gradient becomes zero and the error is not amplified indefinitely; but conversely, if the probability of some action is pressed too low, the gradient still exists and can recover. This is the essential difference between “clipping” and “hard projection.”

Step four: Why min⁡\min must be used instead of max⁡\max. If max⁡\max were used, the constant term would also be taken when rr moves away in the unfavorable direction, the gradient would become zero, and the policy would lose its ability to correct errors; moreover, max⁡\max overestimates the objective value (optimistic estimation), which is contrary to the original intention of “conservative improvement.” min⁡\min always gives a lower bound of the unclipped objective, guaranteeing that “the estimated improvement does not exceed the true improvement.”

Step five: The conversion between ε\varepsilon and the KL radius. Make a second-order expansion of the single-point distribution:

KL(πold∥πθ)=Eπold[log⁡πoldπθ]≈12Eπold[(log⁡πθπold)2]≈12E[(r−1)2]\mathrm{KL}\left(\pi_{\mathrm{old}}\|\pi_\theta\right)=\mathbb{E}_{\pi_{\mathrm{old}}}\left[\log\frac{\pi_{\mathrm{old}}}{\pi_\theta}\right]\approx\frac12\mathbb{E}_{\pi_{\mathrm{old}}}\left[\left(\log\frac{\pi_\theta}{\pi_{\mathrm{old}}}\right)^2\right]\approx\frac12\mathbb{E}\left[(r-1)^2\right]

The last step uses log⁡r≈r−1\log r\approx r-1. Therefore ∣r−1∣≤ε|r-1|\le\varepsilon implies

E[KL]≲12ε2\mathbb{E}\left[\mathrm{KL}\right]\lesssim\frac12\varepsilon^2

ε=0.2\varepsilon=0.2 corresponds to a KL upper bound of about 0.02, the same order of magnitude as the δ≈0.01\delta\approx0.01 commonly used in TRPO. This is the quantitative correspondence between “the clipping radius” and “the trust radius”: δ≈ε2/2\delta\approx\varepsilon^2/2.

Step six: Why this correspondence is only approximate. The bound above is per state, whereas TRPO constrains the average KL weighted by the state distribution. PPO does not explicitly constrain the average KL, so when some states are visited frequently and rr reaches the boundary in all of them, the actual average KL can noticeably exceed 12ε2\frac12\varepsilon^2. This is exactly why “reusing the same batch of data for too many of the KK epochs collapses,” and also why in practice one monitors approx_kl and clip_fraction: the former tells whether the policy has walked too far, the latter tells how many samples have been clipped.

11.3 Value Targets: What the Critic Actually Fits

The step in PPO that is easiest to get wrong is not clipping, but the value target. Many people intuitively write “let V(st)V(s_t) regress to the Monte Carlo return GtG_t”; this is not wrong, but it makes training slow, the variance large, and the scale mismatched with the advantage. PPO’s standard form is:

Vttarget=A^tGAE+Vold(st)V^{\mathrm{target}}_t = \hat{A}^{\mathrm{GAE}}_t + V_{\mathrm{old}}(s_t)

that is, “the GAE advantage plus the old value estimate at sampling time.” Four key points:

First, why not GtG_t? GtG_t is a Monte Carlo estimate of the true return of a trajectory, and its variance grows linearly with the trajectory length; whereas A^t+Vold(st)\hat{A}_t + V_{\mathrm{old}}(s_t) uses only the GAE bootstrapped to step TT, so its variance is much smaller. The role of the Critic is to provide a low-variance baseline for the Actor; training it with a high-variance quantity is equivalent to pouring noise into the baseline, and the advantage estimate then shakes along with it.

Second, why add VoldV_{\mathrm{old}} rather than the current VϕV_\phi? Because the advantage was computed under the value function at the moment of sampling: A^t=A^t(γ,λ;Vold)\hat{A}_t = \hat{A}_t(\gamma,\lambda; V_{\mathrm{old}}). Only by using the same VoldV_{\mathrm{old}} to convert it back into “a value quantity” can we guarantee that VttargetV^{\mathrm{target}}_t and A^t\hat{A}_t are in the same coordinate system. If the currently updating Vϕ(st)V_\phi(s_t) were added, the target would change with the parameters at every step, and the Critic would be chasing a moving target it created itself.

Third, what is its relation to QQ? From A=Q−VA=Q-V we know that A+VA+V is exactly QQ in the one-step case; GAE is the λ\lambda-weighted multi-step version, so VttargetV^{\mathrm{target}}_t is “an estimate of the λ\lambda-weighted multi-step QQ,” lying between the one-step TD target and the Monte Carlo return. When λ=0\lambda=0 it degenerates to the one-step TD target; when λ=1\lambda=1 it degenerates to the return of a whole trajectory minus the baseline plus the baseline, approximating GtG_t.

Fourth, it must be detached in implementation. VttargetV^{\mathrm{target}}_t is a “constant target” and must not carry gradients, otherwise the Critic would be optimizing itself (see 11.6). At the same time it must use the VoldV_{\mathrm{old}} saved at sampling time, and must not be recomputed by a forward pass during mini-batch updates—the recomputed value already carries the current parameters, and then the target is no longer a target.

Two things must be stored into the buffer during the sampling phase: log⁡πold(at∣st)\log\pi_{\mathrm{old}}(a_t\mid s_t) and Vold(st)V_{\mathrm{old}}(s_t). This is often overlooked—they are not “just recompute them at update time,” because by then the policy parameters have already changed and what is recomputed is not the old value.

Derivation 21: Why $V^{\mathrm{target}}=\hat{A}^{\mathrm{GAE}}+V_{\mathrm{old}}$ equals the $\lambda$-return, and what the two endpoints degenerate to

Step one: The λ=0\lambda=0 endpoint degenerates to the one-step TD target. When λ=0\lambda=0, GAE reduces to δt\delta_t:

A^t=δt=rt+γVold(st+1)−Vold(st)\hat{A}_t=\delta_t=r_t+\gamma V_{\mathrm{old}}(s_{t+1})-V_{\mathrm{old}}(s_t)

Adding Vold(st)V_{\mathrm{old}}(s_t) to both sides, the two Vold(st)V_{\mathrm{old}}(s_t) terms cancel:

Vttarget=rt+γVold(st+1)V^{\mathrm{target}}_t=r_t+\gamma V_{\mathrm{old}}(s_{t+1})

which is exactly the TD(0) target (see 5.1).

Step two: The λ=1\lambda=1 endpoint degenerates to the Monte Carlo return. By the telescoping identity of the GAE folding, when λ=1\lambda=1

A^t=∑l=0∞γlδt+l=Gt−Vold(st)\hat{A}_t=\sum_{l=0}^{\infty}\gamma^l\delta_{t+l}=G_t-V_{\mathrm{old}}(s_t)

After adding the baseline, Vold(st)V_{\mathrm{old}}(s_t) cancels, giving Vttarget=GtV^{\mathrm{target}}_t=G_t, i.e., the discounted return of the whole trajectory.

Step three: A general λ\lambda gives exactly the λ\lambda-return. Write

Gtλ=Vold(st)+∑l=0∞(γλ)lδt+lG_t^\lambda=V_{\mathrm{old}}(s_t)+\sum_{l=0}^{\infty}(\gamma\lambda)^l\delta_{t+l}

Then by definition Vttarget=A^t+Vold(st)=GtλV^{\mathrm{target}}_t=\hat{A}_t+V_{\mathrm{old}}(s_t)=G_t^\lambda. Expanding δ\delta verifies that it is exactly consistent with “the exponentially weighted average of all nn-step returns”:

Gtλ=(1−λ)∑n=1∞λn−1Gt(n)+λ∞ (the truncation term vanishes at infinite horizon)G_t^\lambda=(1-\lambda)\sum_{n=1}^{\infty}\lambda^{n-1}G_t^{(n)}+\lambda^{\infty}\ \text{(the truncation term vanishes at infinite horizon)}

where Gt(n)=∑k=0n−1γkrt+k+γnVold(st+n)G_t^{(n)}=\sum_{k=0}^{n-1}\gamma^kr_{t+k}+\gamma^nV_{\mathrm{old}}(s_{t+n}). So this target is not “a quantity pieced together arbitrarily,” but a λ\lambda-return with a clear mathematical definition.

Step four: Why its variance is smaller than that of GtG_t. The weights (1−λ)λn−1(1-\lambda)\lambda^{n-1} are nonnegative and sum to 1, so GtλG_t^\lambda is a convex combination of the Gt(n)G_t^{(n)}. Under the assumption of approximate independence:

Var[Gtλ]≤∑n(1−λ)λn−1Var[Gt(n)]≤max⁡nVar[Gt(n)]\mathrm{Var}\left[G_t^\lambda\right]\le\sum_{n}(1-\lambda)\lambda^{n-1}\mathrm{Var}\left[G_t^{(n)}\right]\le\max_n\mathrm{Var}\left[G_t^{(n)}\right]

The variance of the nn-step return grows with nn (step three of 4.1), and the maximum occurs at the MC return with n→∞n\to\infty. λ<1\lambda<1 concentrates the weights on small nn, which is equivalent to suppressing the part with the largest variance. This is the quantitative reason why “training the Critic with the λ\lambda-return converges faster than with GtG_t.”

Step five: Why VoldV_{\mathrm{old}} must be added rather than the current VϕV_\phi. A^t\hat{A}_t is a quantity computed in the coordinate system of VoldV_{\mathrm{old}}: A^t=A^t(γ,λ;Vold)\hat{A}_t=\hat{A}_t(\gamma,\lambda;V_{\mathrm{old}}). Only by adding back the same Vold(st)V_{\mathrm{old}}(s_t) do we get exactly the GtλG_t^\lambda defined in step three. If the current Vϕ(st)V_\phi(s_t) were added, we would get Vϕ+A^oldV_\phi+\hat{A}_{\mathrm{old}}, whose two quantities have different origins; the target would drift with the parameters at every step, and the Critic would be chasing a moving target it created itself.

Step six: The relation to QQ. From A=Q−VA=Q-V we get A+V=QA+V=Q; when λ=0\lambda=0, VtargetV^{\mathrm{target}} is the one-step QQ, and when λ=1\lambda=1 it is the MC return. So the whole λ\lambda range can be understood as “a λ\lambda-weighted multi-step QQ estimate,” which is another way of stating the same thing as Section 9’s ”λ\lambda interpolates between TD and MC.”

11.4 Pseudocode: PPO-Clip (Full Version)

Algorithm: PPO-Clip (actor-critic, single environment; when multiple environments run in parallel, replace T below with N×T)
Input: initialize policy π_θ and value network V_φ
      T      number of sampling steps per iteration (e.g., 2048)
      K      number of reuse epochs over the same batch of data (e.g., 10)
      M      mini-batch size (e.g., 64)
      γ      discount factor, λ GAE coefficient, ε clipping range (e.g., 0.2)
      c_vf   value loss coefficient (e.g., 0.5), c_ent entropy bonus coefficient (e.g., 0.01)
      α      learning rate
Output: the trained θ, φ

Loop (each iteration):
    # ---------- Segment 1: sample, and store the "old values" as well ----------
    Clear the buffer D
    for t = 0 .. T-1:
        s_t ← current observation
        a_t ~ π_θ(·|s_t)                        # sample an action from the current policy
        Execute a_t, obtaining r_t, s_{t+1}, done_t, truncated_t
        logp_old_t ← log π_θ(a_t|s_t)           # old log probability, detach
        v_old_t    ← V_φ(s_t)                   # old value estimate, detach
        Store (s_t, a_t, r_t, done_t, logp_old_t, v_old_t) into D
    If this segment ends due to time truncation: v_boot ← V_φ(s_T)     # used only as a constant, detach
    If this segment ends due to real termination: v_boot ← 0

    # ---------- Segment 2: compute GAE and value targets in reverse order ----------
    A_T ← 0
    for t = T-1 downto 0:
        boot ← 0 if done_t == 1 else (v_{t+1} or v_boot)
        δ_t  ← r_t + γ·boot − v_old_t
        A_t  ← δ_t + γ·λ·(1−done_t)·A_{t+1}
        V_target_t ← A_t + v_old_t              # constant target, detach
    Normalize A over the whole batch: A ← (A − mean(A)) / (std(A) + 1e-8)   # for the Actor only

    # ---------- Segment 3: K rounds of mini-batch updates ----------
    for epoch = 1 .. K:
        for each mini-batch B ⊂ D:
            logp_new_t ← log π_θ(a_t|s_t)       # needs gradients
            v_new_t    ← V_φ(s_t)               # needs gradients
            ratio_t    ← exp(logp_new_t − logp_old_t)      # i.e., r_t(θ)
            L_actor   ← −E[ min(ratio_t·A_t, clip(ratio_t, 1−ε, 1+ε)·A_t) ]
            L_critic  ← E[ (v_new_t − V_target_t)² ]
            L_entropy ← E[ H(π_θ(·|s_t)) ]
            L ← L_actor + c_vf·L_critic − c_ent·L_entropy
            Backpropagate, update θ, φ
            Optional early stop: if E[ratio_t − 1 − log ratio_t] > 1.5·target KL, break out of this iteration
    θ_old ← θ
    D ← ∅                                        # on-policy: discard the data once used

This pseudocode has three parts more than common textbooks, and they are exactly the places where engineering most often goes wrong: old values stored along with the samples, the bootstrap value at the last state separated by termination/truncation, and both the value targets and the advantages treated as constants. Each part is explained below.

11.5 Section-by-Section Explanation of the Pseudocode

Segment 1 ①: Why logp_old and v_old must be stored at sampling time. Segment 3 needs the probability ratio rt(θ)=πθ/πθoldr_t(\theta)=\pi_\theta/\pi_{\theta_{\mathrm{old}}}, and the denominator must be “the policy at sampling time.” By update time the parameters have already changed, and the recomputed log⁡πθ\log\pi_\theta is the new policy, not the old one. For the same reason VoldV_{\mathrm{old}} must also be stored—it is a component of the value target, and recomputing it gives the current value. In engineering, either sample inside torch.no_grad() or explicitly call .detach() on the tensors stored in the buffer.

Segment 1 ②: Why v_boot must distinguish termination from truncation. When a trajectory is truncated exactly at step TT by the time limit, the environment has not ended, and A^T−1\hat{A}_{T-1} should still bootstrap to V(sT)V(s_T); only at a real termination is the bootstrap value set to 0. Using a single done boolean to represent “the episode ended” is a common mistake—it treats truncation as termination and creates a false value cliff near the time limit (see 9.4 for the derivation).

Segment 2 ③: Why it must be computed in reverse order. The recursion A^t=δt+γλ(1−dt)A^t+1\hat{A}_t=\delta_t+\gamma\lambda(1-d_t)\hat{A}_{t+1} depends on the advantage at the next time step, which a forward pass cannot have. One reverse traversal suffices, O(T)O(T); a forward pass would need to repeatedly recompute subsequent terms, degrading to O(T2)O(T^2).

Segment 2 ④: Why the value targets are computed in place inside the loop. Vttarget=A^t+Vold(st)V^{\mathrm{target}}_t=\hat{A}_t+V_{\mathrm{old}}(s_t) uses exactly the A^t\hat{A}_t just computed and the voldv_{\mathrm{old}} in the buffer, both of which are available in the same reverse pass, so no separate round is needed.

Segment 2 ⑤: Why advantage normalization is for the Actor only. Normalization turns the advantage into zero mean and unit variance, decoupling the policy gradient step size from the reward scale, and is a standard practice for stable training. But it changes the numerical scale; if the normalized A^\hat{A} were used to construct the value target, the target would be shifted and rescaled as a whole, the value scale learned by the Critic would be inconsistent with the true return, and subsequent advantage calculations would go wrong as well. Normalization is used only for L_actor; V_target must use the unnormalized A^\hat{A}.

Segment 3 ⑥: exp(logp_new − logp_old) rather than dividing probabilities directly. The two are mathematically equivalent, but taking the exponential of the log difference is far more numerically stable: probabilities may be as small as 10−1010^{-10}, and direct division underflows easily; the log difference is a finite quantity, and the error in rtr_t is also smaller.

Segment 3 ⑦: The gradient behavior on both sides of min. When At>0A_t>0, once rtr_t exceeds 1+ε1+\varepsilon the clip\mathrm{clip} term becomes a constant and the gradient is 0, so the policy has no incentive to keep increasing that action’s probability; when At<0A_t<0, once rtr_t falls below 1−ε1-\varepsilon the gradient is likewise 0. min is used to be “pessimistic”: when the clipped term and the raw term point in different directions, the smaller one is chosen, ensuring the objective is not overestimated and out-of-bounds updates are not encouraged.

Segment 3 ⑧: The K epochs and early stopping. Reusing the same batch of data KK times is the source of PPO’s sample efficiency, and also the reason why importance sampling and clipping are necessary—the data come from the old policy, and repeated use makes “the new policy drift further and further from the old one,” while clipping limits the drift. In practice one adds a safety net: monitor the approximate KL (the k3 estimator E[r−1−log⁡r]\mathbb{E}[r-1-\log r], nonnegative), and stop the round early once it exceeds a threshold (often 1.5 times the target KL), preventing some unusually large batch from pushing the policy past the breaking point.

Segment 3 ⑨: Why the entropy term is subtracted. − c_ent·H in the loss is equivalent to rewarding entropy, encouraging the action distribution to keep some randomness and avoid collapsing prematurely into a deterministic policy. Too large a centc_{\mathrm{ent}} makes the policy keep trying things randomly, while too small a one loses exploration early on.

Segment 3 ⑩: Why the buffer is cleared after the update. PPO is an on-policy algorithm: this batch of data was produced by πθold\pi_{\theta_{\mathrm{old}}}, and once θ\theta is updated the data distribution is out of date. The criterion is not “whether a probability ratio is used,” but “whether the behavior policy keeps following the target policy.” DQN and SAC draw data from any historical policy in the replay buffer, and that is what makes them off-policy; PPO’s KK epochs only increase the number of uses of the same batch and do not change the data source.

11.6 Detach: Which Three Things in PPO Must Not Have Gradients

detach is an operation in PyTorch: keep the tensor’s values but remove it from the computation graph, so that any subsequent operation on it will not back-propagate gradients to the part of the network that produced it. Three things in PPO must be detached, and they are all “old values” or “targets”:

Quantity that must be detachedSourceConsequence of not detaching
logp_old (old log probability)log⁡πθold\log\pi_{\theta_{\mathrm{old}}} at sampling timeAn extra term “back-propagating through the denominator” appears in the policy loss, which is equivalent to optimizing both the new and old policies at once; the semantics of the ratio are broken
A_t (component of the advantage/value target)Computed by GAE with VoldV_{\mathrm{old}}The Actor’s gradient would flow back through VV, the Actor and the Critic would pull against each other, and the policy gradient would no longer be “a derivative with respect to θ\theta only”
V_target (value target)A^+Vold\hat{A}+V_{\mathrm{old}}The Critic’s target carries gradients, so when minimizing (V−Vtarget)2(V-V_{\mathrm{target}})^2 both sides move at once, which is equivalent to chasing a moving target; in extreme cases the gradients cancel each other, producing a degenerate solution where “the loss decreases but the value is not learned”

What the three have in common: they describe “the past” and are constants that this update should approach, not variables to be optimized. The way to tell is simple—ask “should this quantity change after the update?” If the answer is “it should not,” it should be detached.

A concrete wrong example (many reproduction blogs have fallen into this trap):

# Wrong: the old values are not detached, and are recomputed at update time
logp_old = log_prob(pi, s, a)          # carries gradients
v_old = v(s)                           # carries gradients
loss = -(ratio(logp_new, logp_old) * adv).mean() + ((v_new - (adv + v_old)) ** 2).mean()

# Correct: the old values are fixed at the sampling stage
with torch.no_grad():
    logp_old = log_prob(pi, s, a)
    v_old = v(s)
buf.append(logp_old.detach(), v_old.detach())
# At update time, only logp_new / v_new participate in the computation graph

Note the difference between torch.no_grad() and .detach(): the former makes the whole computation build no graph (saving memory and time, suitable for sampling); the latter only cuts off the history of one tensor, and subsequent operations can still build a graph. In the sampling stage it is recommended to wrap the forward pass in no_grad and then detach the tensors to be stored; in the update stage never wrap logp_new and v_new in no_grad, otherwise the entire loss has no gradients.

One more easily confused point: detaching v_old does not affect the numerical correctness of GAE. GAE only uses the numerical value of voldv_{\mathrm{old}} to compute δt\delta_t and A^t\hat{A}_t and does not need to differentiate it; as a target regressed by the Critic, it also does not need differentiation. What really needs gradients is vnewv_{\mathrm{new}}, obtained by the fresh forward pass in the update stage.

11.7 PPO Implementation Pitfall Checklist

Compressing the sections above into a troubleshooting table, sorted by frequency of occurrence:

SymptomPossible causeFix
Collapse early in training, policy becomes deterministicLearning rate too large, K too large, ε too largeLower the learning rate to the order of 3×10−43\times10^{-4}, set K to 3–10, monitor the k3 KL
The value loss will not go downThe target uses GtG_t, the target is not detached, or advantage normalization contaminated the targetUse A^+Vold\hat{A}+V_{\mathrm{old}}; detach the target; normalize only for the Actor
The advantage shows a “cross-episode” anomalydone and truncated are not separated, the mask is applied in only one placeApply the mask in both places (see 9.4, 9.5)
The probability ratio is abnormally large or small for a long timelogp_old is recomputed, or the old value was not storedStore logp_old at sampling time and detach it
The monitored KL becomes negativeE[log⁡πold−log⁡πθ]\mathbb{E}[\log\pi_{\mathrm{old}}-\log\pi_\theta] was usedSwitch to the k3 estimator E[r−1−log⁡r]\mathbb{E}[r-1-\log r]
The value function and the policy shake togetherActor and Critic share the underlying network, loss scales are not balancedSeparate the networks or tune c_vf; when sharing, lower c_vf
The same batch gets better and better while the real machine gets worse and worseNo early stopping, K too large leading to overfitting the old dataAdd KL early stopping, or use adaptive ε/K
Training is unstable but nothing looks wrongReward scale too large, no return normalizationScale the rewards / normalize the returns, and keep GAE and the value target on the same scale

The “shared network” item deserves a separate mention: sharing a visual backbone between Actor and Critic saves parameters and shares features, but the gradients of the two losses interfere with each other, and the scale of the value loss is usually much larger than that of the policy loss. If they are shared, c_vf must be reduced, the value loss must be normalized, and the gradient norm of each branch must be monitored; when it cannot be tuned well, separating into two networks is actually less trouble.

11.8 PPO versus TRPO

DimensionTRPOPPO
Constraint methodHard KL constraintProbability-ratio clipping (soft constraint)
SolverConjugate gradient + line search (second order)Standard gradient descent (first order)
Implementation complexityHighLow
Reuse of each data batchUsually onceMultiple times, over K epochs
StabilityGood, but sensitive to hyperparametersGood, and easier to tune
Practical popularityAcademic baselineEngineering default

Common PPO variants: PPO-Clip (most widely used), PPO-Penalty (adaptive KL penalty coefficient), and the adaptive KL coefficient version.

11.9 Scope of Application

PPO works with both discrete and continuous actions, and is the de facto standard algorithm today in robot control, game AI, and reinforcement learning from human feedback (RLHF, where a reward model is trained on human preferences and then used to fine-tune a language model with reinforcement learning).


12. ACER: Actor-Critic with Experience Replay

ACER (Actor-Critic with Experience Replay, Wang 2016) tries to answer one question: can an actor-critic also use experience replay, thereby improving sample efficiency?

A2C/A3C are on-policy algorithms—they can only use data just sampled by the current policy, the data is discarded once used, and sample efficiency is low. Experience replay can reuse historical data, but feeding old data directly to a policy gradient causes problems: the expectation in the gradient is with respect to “the new policy πθ\pi_\theta,” whereas the data comes from “the old policy β\beta”; the two distributions differ and must be corrected with the importance-sampling ratio ρ\rho. If ρ\rho is too large, the variance explodes.

ACER solves this with a set of four components:

  1. Off-policy + experience replay: reuse historical data to improve sample efficiency;
  2. Truncated importance sampling: truncate ρt\rho_t to a constant cc to control the variance;
  3. Retrace: TD bootstrapping under off-policy accumulates bias (because the VV estimate is inaccurate for old data); Retrace uses importance-sampling weights to “blend” the multi-step return with bootstrapping, balancing bias and variance to obtain a stable QretQ^{\mathrm{ret}};
  4. TRPO-style constraint: impose a KL trust-region constraint on the Actor before updating θ\theta, so that the policy does not walk too far in one step.

Core formulas (the key lines in the pseudocode):

# Off-policy value estimation (Retrace)
For each sample, compute Q^ret_t = r_t + γ[ρ_{t+1}(Q^ret_{t+1} − V(s_{t+1})) + V(s_{t+1})]   # backward recursion

# Compute the advantage
A_t = Q^ret_t − V(s_t)

# Policy gradient (importance sampling + truncation)
Compute the probability ratio ρ_t = π_θ(a_t|s_t) / β(a_t|s_t)
g = min(ρ_t, c) · A_t · ∇log π_θ(a_t|s_t)                     # truncated term
g += (A_t − min(ρ_t, c) A_t) · ∇log π_θ(a_t|s_t)              # residual correction (keeps the expectation unbiased)

# TRPO-style constraint
Update θ after imposing a KL trust-region constraint on the Actor

# Update the Critic
w ← update w by regressing on (Q^ret_t − V_w(s_t))²

The role of the residual correction: truncation introduces bias, and the second line adds back the gradient of “the part that was cut off,” so that the overall expectation remains unbiased. This is ACER’s key improvement over “simple truncation.”

Derivation 22: Why truncated importance sampling is biased, and how the residual correction makes it unbiased again

Step one: Write the unbiased off-policy policy gradient. The policy gradient can be written in “summing over all actions” form (under discrete actions this is an exact equality, not an approximation):

∇θJ(πθ)=Es∼dβ[∑a∇θπθ(a∣s) Qπ(s,a)]\nabla_\theta J(\pi_\theta)=\mathbb{E}_{s\sim d_\beta}\left[\sum_a\nabla_\theta\pi_\theta(a\mid s)\,Q^{\pi}(s,a)\right]

Using the identity ∇θπθ=πθ∇θlog⁡πθ\nabla_\theta\pi_\theta=\pi_\theta\nabla_\theta\log\pi_\theta, then introducing the behavior policy β\beta as the sampling distribution and defining the importance-sampling ratio ρ(a∣s)=πθ(a∣s)/β(a∣s)\rho(a\mid s)=\pi_\theta(a\mid s)/\beta(a\mid s), we obtain

∇θJ=Es∼dβ Ea∼β[ρ(a∣s) ∇θlog⁡πθ(a∣s) Qπ(s,a)]\nabla_\theta J=\mathbb{E}_{s\sim d_\beta}\,\mathbb{E}_{a\sim\beta}\left[\rho(a\mid s)\,\nabla_\theta\log\pi_\theta(a\mid s)\,Q^{\pi}(s,a)\right]

This step is an identity transformation: β\beta appears in the sampling distribution and ρ\rho makes up for it in the numerator; multiplying the two exactly restores πθ\pi_\theta. So as long as ρ\rho is kept as is, the estimate is unbiased, and the only problem is the variance.

Step two: Clipping turns unbiasedness into bias, and the bias can be written explicitly. Replace the coefficient of the sampling term with min⁡(ρ,c)\min(\rho,c):

g^clip=Ea∼β[min⁡(ρ(a∣s),c)∇θlog⁡πθ(a∣s) Qπ(s,a)]\hat g_{\mathrm{clip}}=\mathbb{E}_{a\sim\beta}\left[\min\left(\rho(a\mid s),c\right)\nabla_\theta\log\pi_\theta(a\mid s)\,Q^{\pi}(s,a)\right]

The expectation of its difference from the target (i.e., the bias) is

Bias=Es[∑a(πθ(a∣s)−β(a∣s)min⁡(ρ(a∣s),c))∇θlog⁡πθ(a∣s)Qπ(s,a)]\mathrm{Bias}=\mathbb{E}_{s}\left[\sum_a\left(\pi_\theta(a\mid s)-\beta(a\mid s)\min\left(\rho(a\mid s),c\right)\right)\nabla_\theta\log\pi_\theta(a\mid s)Q^{\pi}(s,a)\right]

Only actions with ρ>c\rho>c are clipped, and those actions originally had the largest weights, so the bias is nonzero and its direction is predictable. Clipping does suppress the variance (ρ\rho is no longer unbounded), but at the cost of a systematic bias—which is exactly why “simple truncation” cannot be used directly.

Step three: The residual correction—make up the bias term with an “exact summation over all actions.” Define the correction term

g^bc=Es[∑a(ρ(a∣s)−min⁡(ρ(a∣s),c))β(a∣s) ∇θlog⁡πθ(a∣s) Qπ(s,a)]\hat g_{\mathrm{bc}}=\mathbb{E}_{s}\left[\sum_a\left(\rho(a\mid s)-\min\left(\rho(a\mid s),c\right)\right)\beta(a\mid s)\,\nabla_\theta\log\pi_\theta(a\mid s)\,Q^{\pi}(s,a)\right]

When the two are added, min⁡(ρ,c)\min(\rho,c) and ρ−min⁡(ρ,c)\rho-\min(\rho,c) merge back into ρ\rho:

g^clip+g^bc=Es Ea∼β[ρ ∇θlog⁡πθ Qπ]=∇θJ\hat g_{\mathrm{clip}}+\hat g_{\mathrm{bc}}=\mathbb{E}_{s}\,\mathbb{E}_{a\sim\beta}\left[\rho\,\nabla_\theta\log\pi_\theta\,Q^{\pi}\right]=\nabla_\theta J

This is the full meaning of “truncation + residual correction = unbiased”: clipping acts only on the “cheap but high-variance” term, and the clipped mass is exactly made up by the other term.

Step four: Why the correction term must be summed analytically and cannot be estimated by sampling. If the correction term were written as sampling over “the actions that were sampled,” it would still contain the untruncated ρ\rho, and its variance would be as large as with no clipping at all—clipping would be pointless. ACER writes the correction term as a sum over all actions: the weight ρ−min⁡(ρ,c)\rho-\min(\rho,c) can be computed directly from the probabilities of πθ\pi_\theta and β\beta, and QQ is looked up from the Critic, so only O(∣A∣)O(|\mathcal{A}|) forward passes are needed and the sampling noise of ρ\rho is no longer brought in. The cost is that the action space must be enumerable—which is exactly the fundamental reason why ACER applies only to discrete or small action spaces and cannot be used directly for high-dimensional continuous actions.

Step five: Two engineering details of ρ\rho. First, when ρ\rho is the running product along a trajectory ∏kπ(ak∣sk)/β(ak∣sk)\prod_{k}\pi(a_k\mid s_k)/\beta(a_k\mid s_k), it overflows or underflows within a few dozen steps, so implementations must accumulate in the log domain and then exponentiate, and clip the overflow separately. Second, cc is an explicit bias–variance knob: a small cc gives low variance but more clipped parts (made up by the correction term), while a large cc approaches no clipping and high variance. The original paper uses c=10c=10 for discrete actions; c=1c=1 means trusting only the weight level at which the behavior policy sampled.

About that line in the pseudocode. The g = min(ρ,c)·A·∇logπ written earlier plus (A − min(ρ,c)A)·∇logπ merge into A∇θlog⁡πA\nabla_\theta\log\pi, throwing away the ρ\rho weight entirely, so it is only a schematic representation of the “truncation + compensation” structure and is not strictly unbiased. The rigorous form is step three of this section: the truncation acts on the sampling term carrying ρ\rho, and the correction term carries ρ−min⁡(ρ,c)\rho-\min(\rho,c) and sums over all actions.

12.1 ACER’s Historical Position and Outcome

ACER is an important academic milestone: it proved that “experience replay + actor-critic” is feasible. But because it is complex to implement and its gains are unstable, it was later replaced in practice by the simpler SAC and PPO. It is more of a stepping stone that “proves the route is feasible” than a mainstream algorithm today.


13. DPG: Deterministic Policy Gradient

13.1 Why a Deterministic Policy Is Needed

The policy gradients of the previous twelve chapters—REINFORCE, A2C, TRPO, PPO, ACER—are all built on a stochastic policy: the network outputs a distribution πθ(a∣s)\pi_\theta(a\mid s), and actions are sampled from that distribution. DPG (Deterministic Policy Gradient, Silver et al., ICML 2014) replaces exactly this assumption: the policy is a deterministic function μθ(s)\mu_\theta(s) that outputs an action directly given a state, with no sampling step.

Why is it worth replacing? Three motivations, ordered by importance:

First, the action integral degenerates into a single evaluation. The expectation of the stochastic policy gradient is a double expectation over “state + action”:

∇θJ(πθ)=Es∼ρπ Ea∼πθ(⋅∣s)[∇θlog⁡πθ(a∣s) Qπ(s,a)]\nabla_\theta J(\pi_\theta)=\mathbb{E}_{s\sim\rho^\pi}\ \mathbb{E}_{a\sim\pi_\theta(\cdot\mid s)}\left[\nabla_\theta\log\pi_\theta(a\mid s)\,Q^\pi(s,a)\right]

The inner expectation must integrate over the entire action space (or approximate it by sampling). The higher the action dimension, the more expensive this integral and the larger the variance. A deterministic policy removes the inner expectation entirely: the action is the single point μθ(s)\mu_\theta(s), requiring one forward and one backward pass.

Second, the cost of high-dimensional continuous actions is linear rather than exponential. If the action space is approximated by discretization with dd dimensions and kk levels per dimension, the total number of actions is kdk^d. A seven-degree-of-freedom manipulator with 21 levels per dimension has 217≈1.8×10921^7\approx1.8\times10^{9} combinations; a deterministic policy needs to output only 7 real numbers. The higher the action dimension, the starker the gap—this is the core motivation of the original DPG paper (control problems with high-dimensional action spaces).

Third, the action trajectory is smoother. A stochastic policy jitters within the distribution at every step, whereas real systems (manipulators, vehicles) prefer actions that are smooth functions of the state. A deterministic policy naturally gives a smooth mapping; noise is injected only during training and can be turned off at deployment.

The costs are equally clear, and each corresponds to an algorithmic patch later: no built-in exploration (noise must be attached externally), QQ must be differentiable with respect to the action (continuous actions only), multimodality cannot be expressed (when “either going around left or right is fine,” it averages into the middle), off-policy + function approximation is inherently unstable (a target network is needed).

13.2 Taking the Limit of the Stochastic Policy Gradient: How the Theorem Comes About

The correct statement of the DPG theorem is:

∇θJ(μθ)=Es∼ρμ[∇θμθ(s)⊤ ∇aQμ(s,a)∣a=μθ(s)]\nabla_\theta J(\mu_\theta)=\mathbb{E}_{s\sim\rho^\mu}\left[\nabla_\theta\mu_\theta(s)^\top\,\nabla_a Q^\mu(s,a)\Big|_{a=\mu_\theta(s)}\right]

Here ρμ\rho^\mu is the state distribution “produced by following the deterministic policy μ\mu,” and QμQ^\mu is the action value under μ\mu. Note the order of the two gradients: first take the gradient of QQ with respect to the action, then take the gradient of the policy with respect to the parameters, and multiply the two. This is not a casually written chain rule, but something derived strictly by taking the limit of the stochastic policy gradient theorem.

Derivation 23: Taking the limit of the stochastic policy gradient theorem to obtain DPG (including three necessary assumptions)

Step one: Embed the deterministic policy in a family of stochastic policies. Take a Gaussian policy with mean μθ(s)\mu_\theta(s):

πθ,σ(a∣s)=1(2πσ)dexp⁡(−∥a−μθ(s)∥22σ2)\pi_{\theta,\sigma}(a\mid s)=\frac{1}{\left(\sqrt{2\pi}\sigma\right)^{d}}\exp\left(-\frac{\left\|a-\mu_\theta(s)\right\|^2}{2\sigma^2}\right)

σ\sigma is an artificially introduced action-noise scale. As σ→0\sigma\to0, this family of policies converges to the deterministic policy μθ\mu_\theta.

Step two: Write the log gradient of this family of policies. Differentiating with respect to θ\theta, only the mean term contains θ\theta:

∇θlog⁡πθ,σ(a∣s)=a−μθ(s)σ2 ∇θμθ(s)\nabla_\theta\log\pi_{\theta,\sigma}(a\mid s)=\frac{a-\mu_\theta(s)}{\sigma^{2}}\,\nabla_\theta\mu_\theta(s)

(The derivative with respect to aa is left for step three.) This step shows that the log gradient of a stochastic policy can be decomposed into two parts, “action deviation × policy parameter gradient,” and the first term a−μθ(s)σ2\frac{a-\mu_\theta(s)}{\sigma^2} becomes a spike concentrated near μθ(s)\mu_\theta(s) as σ→0\sigma\to0.

Step three: Substitute into the stochastic policy gradient theorem and make a first-order Taylor expansion of QQ. The stochastic policy gradient theorem gives

∇θJ=Es∼ρπσEa∼πσ[a−μθ(s)σ2 ∇θμθ(s) Qπσ(s,a)]\nabla_\theta J=\mathbb{E}_{s\sim\rho^{\pi_{\sigma}}}\mathbb{E}_{a\sim\pi_{\sigma}}\left[\frac{a-\mu_\theta(s)}{\sigma^{2}}\,\nabla_\theta\mu_\theta(s)\,Q^{\pi_\sigma}(s,a)\right]

Expand QQ at a=μθ(s)a=\mu_\theta(s): Q(s,a)≈Q(s,μθ(s))+∇aQ(s,μθ(s))⊤(a−μθ(s))Q(s,a)\approx Q(s,\mu_\theta(s))+\nabla_a Q(s,\mu_\theta(s))^\top(a-\mu_\theta(s)). After substitution the first term is an odd function (expectation 0), and the second term is

Ea[(a−μ)(a−μ)⊤σ2]∇aQ=∇aQ(s,μθ(s))\mathbb{E}_{a}\left[\frac{(a-\mu)(a-\mu)^\top}{\sigma^{2}}\right]\nabla_a Q=\nabla_a Q(s,\mu_\theta(s))

because the covariance of the Gaussian is σ2I\sigma^2 I, E[(a−μ)(a−μ)⊤]=σ2I\mathbb{E}\left[(a-\mu)(a-\mu)^\top\right]=\sigma^2I, and σ2\sigma^2 is exactly canceled by the denominator—this is the key step of “variance-term cancellation,” and also why the limit exists and is finite.

Step four: Take σ→0\sigma\to0. At this point πσ→μ\pi_{\sigma}\to\mu, the state distribution ρπσ→ρμ\rho^{\pi_\sigma}\to\rho^{\mu}, Qπσ→QμQ^{\pi_\sigma}\to Q^\mu, and the inner expectation collapses to the value at a=μθ(s)a=\mu_\theta(s):

∇θJ(μθ)=Es∼ρμ[∇θμθ(s)⊤∇aQμ(s,a)∣a=μθ(s)]\nabla_\theta J(\mu_\theta)=\mathbb{E}_{s\sim\rho^\mu}\left[\nabla_\theta\mu_\theta(s)^\top\nabla_a Q^\mu(s,a)\Big|_{a=\mu_\theta(s)}\right]

Step five: Three assumptions that cannot be omitted. For the derivation above to hold, we need: (1) Qμ(s,a)Q^\mu(s,a) is differentiable with respect to aa, and ∇aQ\nabla_a Q is bounded (Lipschitz) in a neighborhood of μθ(s)\mu_\theta(s); (2) ∇θμθ(s)\nabla_\theta\mu_\theta(s) is bounded; (3) the state distribution ρπσ\rho^{\pi_\sigma} varies continuously with σ\sigma (ensuring the limit can be moved inside the expectation). These three are the regularity conditions explicitly listed in the Silver 2014 paper, and in engineering they correspond to three things: the last layer of the Critic must be able to bring the action into the computation graph, the action magnitude must be bounded (use tanh⁡\tanh or explicit scaling), and the state distribution of the environment must not change abruptly due to tiny noise changes.

13.3 Term by Term: What Each of the Three Factors Is Saying

Reading the three factors of the theorem separately makes all of DPG’s engineering requirements clear:

FactorMathematical meaningIntuitionEngineering meaning
ρμ\rho^\muThe state distribution sampled by following μ\mu“On which states you will practice”Only on these states is the Critic’s gradient trustworthy; states outside the distribution must be covered by exploration noise
∇aQμ(s,a)∥a=μθ(s)\nabla_a Q^\mu(s,a)\|_{a=\mu_\theta(s)}The gradient of QQ with respect to the action, evaluated at the current action“Which way to twist this action so that QQ becomes larger”The Critic must concatenate the action at the input; the last layer cannot be “one output per discrete action”
∇θμθ(s)\nabla_\theta\mu_\theta(s)The gradient of the policy output with respect to the parameters“How a change in the action translates into a change in the parameters”The Actor must be a differentiable network; action scaling must avoid saturation

Why has the gradient of the state distribution disappeared? This is where beginners most often get stuck. JJ depends on the policy both through the action selection and through the state distribution (a change in the way of walking changes which states are visited). The reason the stochastic policy gradient theorem can use only ∇θlog⁡π\nabla_\theta\log\pi is that the contribution of the latter term is exactly zero—formally from the identity “the integral of a distribution equals 1, so its gradient is 0.” After taking the limit in the deterministic case, this property still holds, so the theorem contains only the action gradient and no ∇θρμ\nabla_\theta\rho^\mu term. In other words: you do not need to model “how the environment responds to a policy change”; the local gradient of the Critic has already compressed this information. This is also the origin of “model-free.”

Derivation 24: Why exactly the state-distribution term disappears (the trajectory-likelihood view)

Step one: Start from “trajectory probability” and see where θ\theta actually appears. The probability of a trajectory τ=(s0,a0,s1,a1,… )\tau=(s_0,a_0,s_1,a_1,\dots) is

pθ(τ)=ρ0(s0)∏tπθ(at∣st) P(st+1∣st,at)p_\theta(\tau)=\rho_0(s_0)\prod_{t}\pi_\theta(a_t\mid s_t)\,P\left(s_{t+1}\mid s_t,a_t\right)

where the initial distribution ρ0\rho_0 and the transition probability PP are both independent of θ\theta. Take the log derivative with respect to θ\theta:

∇θlog⁡pθ(τ)=∑t∇θlog⁡πθ(at∣st)+∇θlog⁡ρ0(s0)⏟=0+∑t∇θlog⁡P(st+1∣st,at)⏟=0\nabla_\theta\log p_\theta(\tau)=\sum_t\nabla_\theta\log\pi_\theta(a_t\mid s_t)+\underbrace{\nabla_\theta\log\rho_0(s_0)}_{=0}+\underbrace{\sum_t\nabla_\theta\log P\left(s_{t+1}\mid s_t,a_t\right)}_{=0}

This step decomposes “the state distribution changes with the policy”: the states do change because the policy changes, but this change has no independent parameter in the trajectory probability; it is entirely caused by “the probability of choosing an action at each step changed.” So the term ∇θρμ\nabla_\theta\rho^\mu need not appear in the gradient—it has already been absorbed by ∑t∇θlog⁡πθ\sum_t\nabla_\theta\log\pi_\theta.

Step two: Use the log-derivative trick to obtain the trajectory-level gradient.

∇θJ=∇θ Eτ∼pθ[R(τ)]=Eτ∼pθ[R(τ) ∇θlog⁡pθ(τ)]=E[R(τ)∑t∇θlog⁡πθ(at∣st)]\nabla_\theta J=\nabla_\theta\,\mathbb{E}_{\tau\sim p_\theta}\left[R(\tau)\right]=\mathbb{E}_{\tau\sim p_\theta}\left[R(\tau)\,\nabla_\theta\log p_\theta(\tau)\right]=\mathbb{E}\left[R(\tau)\sum_t\nabla_\theta\log\pi_\theta(a_t\mid s_t)\right]

Step three: Split by time step and use causality to isolate “future rewards.” Exchange the sum R(τ)=∑t′rt′R(\tau)=\sum_{t'}r_{t'} with the time index: only rewards after time tt depend on ata_t (rewards before are conditionally independent of ata_t given sts_t):

∇θJ=E[∑t∇θlog⁡πθ(at∣st)⋅Gt]\nabla_\theta J=\mathbb{E}\left[\sum_t\nabla_\theta\log\pi_\theta(a_t\mid s_t)\cdot G_t\right]

And E[Gt∣st,at]=Qπ(st,at)\mathbb{E}[G_t\mid s_t,a_t]=Q^{\pi}(s_t,a_t), so

∇θJ=Es∼ρμEa∼π[∇θlog⁡πθ(a∣s) Qμ(s,a)]\nabla_\theta J=\mathbb{E}_{s\sim\rho^\mu}\mathbb{E}_{a\sim\pi}\left[\nabla_\theta\log\pi_\theta(a\mid s)\,Q^{\mu}(s,a)\right]

Step four: This is exactly consistent with the chain-rule form of 13.3. Taking the limit π→δ(a−μθ(s))\pi\to\delta\left(a-\mu_\theta(s)\right) for the deterministic policy, the expectation over actions collapses to the value at μθ(s)\mu_\theta(s), and the role of ∇θlog⁡π\nabla_\theta\log\pi is replaced by ∇θμθ\nabla_\theta\mu_\theta:

∇θJ=Es∼ρμ[∇θμθ(s)⊤∇aQμ(s,a)∣a=μθ(s)]\nabla_\theta J=\mathbb{E}_{s\sim\rho^\mu}\left[\nabla_\theta\mu_\theta(s)^{\top}\nabla_aQ^{\mu}(s,a)\Big|_{a=\mu_\theta(s)}\right]

The “three factors” then each fall into place: ρμ\rho^\mu determines “which states are weighted,” ∇aQμ\nabla_aQ^\mu determines “which way to twist the action,” and ∇θμθ\nabla_\theta\mu_\theta determines “how this twist translates into a parameter update.” Remove any one of them: without the ρμ\rho^\mu weight, the gradient would reflect “any arbitrary state” rather than the states the policy will actually reach.

About the phrase “the integral of a distribution equals 1, so its gradient is 0.” It is a shorthand that is easy to remember, but used alone it is not enough to reach the conclusion: from ∫dθ(s) ds=1\int d_\theta(s)\,\mathrm{d}s=1 one can only conclude ∫∇θdθ(s) ds=0\int\nabla_\theta d_\theta(s)\,\mathrm{d}s=0, i.e., ∇θdθ\nabla_\theta d_\theta is orthogonal to constant functions, whereas ∫∇θdθ(s)V(s) ds\int\nabla_\theta d_\theta(s)V(s)\,\mathrm{d}s is generally not zero (VV is not constant). The rigorous argument is the trajectory-likelihood method of steps one to three of this section: the change in the state distribution is exactly absorbed by “the change in the action probability at each step,” so dθd_\theta does not need to be differentiated separately. Both statements reach the same conclusion, but only the latter is a verifiable derivation.

Step five: Why the deterministic limit cannot be obtained by differentiating δ\delta directly. When π=δ\pi=\delta, log⁡π\log\pi is undefined and ∇θlog⁡π\nabla_\theta\log\pi is the derivative of a δ\delta function; the likelihood-ratio identity of step one fails. DPG handles this by first writing the gradient of the stochastic policy as an integral over actions, and then letting the variance σ→0\sigma\to0 take the limit (the four steps of 13.2), rather than “doing a likelihood ratio on δ\delta.” This explains why the DPG theorem is stated in the conditional form “the policy variance tends to zero.”

The trap outside the state distribution. The theorem only says it holds “on ρμ\rho^\mu.” If the Actor moves to states not covered by the training data after an update, the Critic has no constraint there, and the gradient of QQ may be arbitrary. This is the common weakness of the DPG family (DDPG, TD3, SAC), mitigated by experience replay + exploration noise, but fundamentally it cannot be cured.

A frequently asked question: why not take the gradient of Q(s,μθ(s))Q(s,\mu_\theta(s)) with respect to θ\theta directly? You can, and that is exactly how it is implemented:

∇θQμ(s,μθ(s))=∇θμθ(s)⊤∇aQ(s,a)∣a=μθ(s)\nabla_\theta Q^\mu\left(s,\mu_\theta(s)\right)=\nabla_\theta\mu_\theta(s)^\top\nabla_aQ(s,a)\Big|_{a=\mu_\theta(s)}

The two writings are completely equivalent. The only difference is implementation: writing it as “differentiating QQ” allows automatic differentiation to be called directly, by writing the Actor’s loss as −Q(s,μθ(s))-Q(s,\mu_\theta(s)) (see 14.3 for details).

13.4 Three Differences from the Stochastic Policy Gradient

This is the key comparison for understanding DPG, and also the most essential dividing line between it and algorithms like PPO (PPO can also handle continuous actions, see 11.9):

DimensionStochastic policy gradient (REINFORCE, PPO, SAC)Deterministic policy gradient (DPG, DDPG, TD3)
Form of the policy outputA distribution πθ(⋅∣s)\pi_\theta(\cdot\mid s), with parameters usually the mean and varianceAn action μθ(s)\mu_\theta(s), with parameters determining only the mean
Object of the expectationState + action (double expectation)State only (single expectation)
Action integral/sumRequires sampling or integrating over actions, expensive in high dimensionsDegenerates into a single evaluation: a=μθ(s)a=\mu_\theta(s)
Source of the gradient∇θlog⁡πθ(a∣s)\nabla_\theta\log\pi_\theta(a\mid s), unrelated to the gradient of QQ∇aQ⋅∇θμ\nabla_aQ\cdot\nabla_\theta\mu, must be back-propagated through the Critic
Exploration mechanismThe distribution itself is random (entropy, variance)Noise must be attached externally (Gaussian noise, or an OU process, see 14.8)
Multimodal actionsCan express a bimodal distributionCan output only a single point; a bimodal case averages into an invalid action
Data sourceUsually on-policy (PPO, TRPO)Naturally off-policy (behavior policy ≠ target policy)
Requirement on QQOnly needs to be able to evaluate Q(s,a)Q(s,a)Must be differentiable with respect to aa, and the gradient must be back-propagatable

The most easily underestimated of the three is the third: the exploration mechanism must be attached externally. Exploration in a stochastic policy is “free”—the distribution itself is jittering; exploration in a deterministic policy is “man-made”: during training execute μθ(s)+Nt\mu_\theta(s)+N_t, at deployment execute μθ(s)\mu_\theta(s). This directly makes the DPG family entirely off-policy algorithms: the behavior policy (with noise) differs from the target policy (without noise), so one must either correct with importance sampling or bypass the correction with a replay buffer + off-policy value learning. DDPG, TD3, and SAC are all built on this structure.

The second most easily underestimated is the difference in the source of the gradient. When PPO updates the Actor it does not need QQ to be differentiable with respect to the action at all: it only needs “what the advantage of this action is,” and then raises or lowers its probability density. DPG is the opposite: it must know “which way to nudge the action to be better,” and this direction can only be read from the action gradient of QQ. So the Critic of the DPG family is not a “scorer” but a “direction pointer”—the implementation requirements of the two are completely different.

13.5 Pseudocode: DPG (Full Version)

The DPG of the original paper is “theory + linear/shallow function approximation,” without a replay buffer or target network. What is given below is the version with engineering stabilization components, which is also the direct predecessor of DDPG; replacing the networks with deep networks gives DDPG.

Algorithm: DPG (deterministic actor-critic, with replay and soft target networks)
Input: deterministic Actor μ_θ(s), Critic Q^w(s,a)
      α_θ, α_w        learning rates
      γ               discount factor
      τ               soft-update coefficient (e.g., 0.005; setting it to 1 degenerates to a hard copy)
      σ               exploration noise scale (e.g., 0.1, scaled by the action range)
      N               mini-batch size, M replay buffer capacity
Output: the trained θ, w

Initialize: randomly initialize θ, w; θ' ← θ, w' ← w; replay buffer D ← ∅

Loop (for each episode):
    s ← initial state of the environment
    For t = 0, 1, 2, … until the episode ends:
        # ---------- Segment 1: sample with the "noisy deterministic policy" ----------
        a_t ← μ_θ(s_t) + N_t                      # N_t ~ N(0, σ²I) or an OU process
        a_t ← clip(a_t, a_min, a_max)             # clip the action
        Execute a_t, observe r_t, s_{t+1}, terminated_t, truncated_t
        Store (s_t, a_t, r_t, s_{t+1}, terminated_t) into D   # what is stored is the noisy action

        # ---------- Segment 2: sample from the replay buffer and update the Critic ----------
        B ← randomly sample N transitions from D
        For each i ∈ B:
            boot_i ← 0 if terminated_i else Q^{w'}(s_{i+1}, μ_{θ'}(s_{i+1}))   # no_grad
            y_i ← r_i + γ·boot_i
        L_critic ← (1/N) Σ_i (y_i − Q^w(s_i, a_i))²
        w ← w − α_w ∇_w L_critic

        # ---------- Segment 3: update the Actor (Critic frozen) ----------
        L_actor ← −(1/N) Σ_i Q^w(s_i, μ_θ(s_i))    # differentiate with respect to θ only
        θ ← θ − α_θ ∇_θ L_actor

        # ---------- Segment 4: soft-update the target networks ----------
        θ' ← τθ + (1−τ)θ'
        w' ← τw + (1−τ)w'

The three numbered segments correspond to three completely different gradient paths, and miswiring any one of them leads to “training appears to be moving, but the metrics do not rise.” Each is unpacked below.

13.6 Section-by-Section Explanation of the Pseudocode

Segment 1 ①: a_t = μ_θ(s_t) + N_t is the behavior policy, and μ_θ is the target policy. A deterministic policy has no randomness; without noise it will forever follow the same trajectory, the replay buffer will be full of duplicate samples, the Critic will have seen only one neighborhood of actions, and the gradient will naturally be untrustworthy. The role of noise is to separate “the policy used for sampling” from “the optimal policy to be learned.” This also explains why DPG is naturally off-policy: the behavior policy μθ+noise\mu_\theta+\text{noise} differs from the target policy μθ\mu_\theta, so off-policy value learning (DQN-style TD updates) is needed rather than on-policy importance sampling.

Segment 1 ②: The “noisy” action a_t must be stored. The Critic learns the value of Qμ(s,a)Q^\mu(s,a) at “the actions actually executed.” If the noise-free μθ(st)\mu_\theta(s_t) were stored, the distribution the Critic learns would be inconsistent with the true behavior distribution: it has seen only an extremely narrow region near the policy output point and cannot estimate accurately for noisy actions; worse, when updating the Actor one needs ∇aQ\nabla_aQ at that point, and the QQ value at that point has never been constrained by data. This is one of the most common mistakes when reproducing the DPG family.

Segment 1 ③: Actions must be explicitly clipped. The theorem requires ∇θμ\nabla_\theta\mu to be bounded and QQ to be differentiable in a neighborhood of the action. After noise is added, the action may exceed the physical limits (joint angles, torque limits), putting QQ outside the training distribution. clip is the lowest-cost protection; a better approach is to scale the network output to [amin⁡,amax⁡][a_{\min},a_{\max}] with tanh⁡\tanh (see the pitfall checklist in 14.7).

Segment 2 ④: The successor action in the target is μθ′(s′)\mu_{\theta'}(s'), not max⁡a′Q(s′,a′)\max_{a'}Q(s',a'). This is where DPG and DQN are most easily confused. DQN learns Q∗Q^*, and the target takes the maximum over the action dimension; DPG learns the value of the current policy QμQ^\mu, the successor action is determined by the current policy, and only the target network delays it. Both are “bootstrapping,” but one bootstraps to the optimum and the other to the current policy. This also means that DPG’s target is not Q∗Q^*; it only guarantees policy improvement, not convergence to the global optimum—the policy improvement theorem (3.4) has only a local version under function approximation.

Segment 2 ⑤: The whole of boot_i is under no_grad. yiy_i is a constant label computed from rir_i (a scalar given by the environment) and the two target networks. If the target networks carried gradients, the Critic would be chasing a target that moves with the parameters, which is equivalent to having no target network at all. In implementation, either put this segment inside torch.no_grad() or explicitly .detach() yiy_i.

Segment 2 ⑥: Termination and truncation must be separated. terminated is a real end in the MDP sense, and the successor value must be set to zero; truncated is an interruption caused by a time limit or step limit, the environment itself has not ended, and bootstrapping must still be done. Treating both as “the end” is another high-frequency bug in the DPG family; the symptom is a systematically low QQ value near the time limit and the policy suddenly becoming conservative at the end of an episode (the same root cause as the masking problems in 9.4 and 9.5).

Segment 3 ⑦: Writing the Actor’s loss as −Q(s,μθ(s))-Q(s,\mu_\theta(s)) is safer than hand-writing the chain rule. Expanding it gives

∇θ[−Qw(s,μθ(s))]=−∇θμθ(s)⊤∇aQw(s,a)∣a=μθ(s)\nabla_\theta\left[-Q^w\left(s,\mu_\theta(s)\right)\right]=-\nabla_\theta\mu_\theta(s)^\top\nabla_aQ^w(s,a)\Big|_{a=\mu_\theta(s)}

Automatic differentiation computes the path of “the action input,” with no need to hand-write dQ/da. But the premise is: ww must be frozen. If the Critic’s parameters are also handed to the same optimizer, the Actor’s objective will simultaneously push ww, the Critic will be pulled toward “making QQ larger at that action” rather than “accurately estimating QQ,” and the value function immediately becomes distorted. The standard approach is to freeze the Critic with requires_grad_(False), or pass only θ\theta to the optimizer; unfreeze after updating the Actor.

Segment 3 ⑧: The Actor and the Critic should not have the same learning rate. The Critic has to fit a continuously changing target, so it usually uses a larger step size (e.g., 10−310^{-3}); the Actor’s action gradient is back-propagated through the Critic and is noisier, so it usually uses a smaller step size (e.g., 10−410^{-4}). This “slow Actor, fast Critic” ratio is one of the most critical tuning items in the DPG family: if the ratio is reversed (the Actor faster than the Critic), the policy will chase a QQ that has not yet been learned accurately, showing up as QQ-value jitter and policy oscillation.

Segment 4 ⑨: The value of the soft-update τ\tau. The original DPG paper has no target network; in engineering the target-network idea of DQN is adopted uniformly. τ\tau is often 0.001–0.005. Too large a τ\tau (e.g., 0.1) means the target is always moving, and the stability benefit disappears; too small (e.g., 10−410^{-4}) means the target lags severely, learning slows down, and on tasks with very short episodes it shows up as “the QQ value is persistently too low.” The criterion: observe the gap between the target QQ and the online QQ; if it deviates monotonically over a long period, suspect τ\tau is too small first.

13.7 Gradient Flow and detach: Which Three Places in DPG Must Be Cut

DPG has only two losses, but its gradient flow is more convoluted than PPO’s, because the Actor’s gradient must pass through the Critic. Let us list the gradient requirements of each quantity clearly:

QuantityNeeds gradients?Explanation
yiy_i (Critic target)NoComputed from rir_i and the two target networks; the whole segment is under no_grad
Qw(si,ai)Q^w(s_i,a_i) (Critic prediction)Yes (with respect to ww)The Critic loss updates only ww
μθ(si)\mu_\theta(s_i) in the Actor lossYes (with respect to θ\theta)The action is the Actor’s output
Qw(si,μθ(si))Q^w(s_i,\mu_\theta(s_i)) in the Actor lossYes for θ\theta, no for wwThe gradient is back-propagated to the Actor only through “the action input”

A concrete wrong/right comparison:

# Wrong: the Critic is not frozen, so the Actor's objective also changes the Critic
loss_actor = -q_critic(s, actor(s)).mean()
opt_theta.step()      # if the optimizer also contains w, the Critic is dragged off by the Actor objective

# Correct: freeze the Critic, letting the gradient only pass through
for p in critic.parameters():
    p.requires_grad_(False)
loss_actor = -critic(s, actor(s)).mean()
opt_theta.step()
for p in critic.parameters():
    p.requires_grad_(True)

The division of labor between torch.no_grad() and .detach() must also be clear: use no_grad for the forward pass in the sampling stage to save memory; .detach() the tensors that go into the buffer or serve as labels; the critic(s, actor(s)) in the Actor loss absolutely must not be wrapped in no_grad, otherwise the Actor has no gradient at all and the loss never moves—this is the prime suspect for “training reports no error but the Actor parameters do not change.”

There is another subtle point: if the Actor and the Critic share a low-level feature extractor (e.g., a shared convolutional backbone), freezing the Critic freezes the shared part as well, and the Actor cannot learn either. In such a structure the shared part must be handled separately, or the two networks simply separated. In practice the DPG family almost always separates the networks, because the inputs of the Actor and the Critic are different anyway (the Critic needs an extra action path).

13.8 DPG Implementation Pitfall Checklist

SymptomPossible causeFix
Actor parameters do not move at allThe Actor loss is wrapped in no_grad, the Critic is frozen and never unfrozen, or the action is detachedCheck whether critic(s, actor(s)) has gradients; print the norm of dQ/da
The QQ value rises monotonically and the policy degeneratesThe target is not under no_grad, yy uses the online network, the termination mask is wrongPut the whole target under no_grad; use terminated in both masks
All actions are the same early in trainingNo noise added, the noise scale is 0, or the replay buffer is too smallScale the noise by the action range, with a buffer of at least 10510^5
Actions jitter and QQ jitters late in trainingThe Actor learning rate is not smaller than the Critic’s, τ\tau is too largeLower the Actor learning rate, τ≤0.005\tau\le0.005
Actions on the real robot exceed the limitsThe network output is not clippedtanh⁡\tanh scaling + explicit clip + another clip in the low-level controller
It only learns in the early part of an episodeTruncation is treated as termination, bootstrapping is zeroedUse terminated alone to control bootstrapping
It collapses when switching tasksObservations are not normalized, reward scales differ greatlyStandardize the observations, scale the rewards, compare with a fixed seed
It cannot learn with high-dimensional actions (>10 dimensions)The gradient scales differ greatly across action dimensions, improper initializationSmall initialization of the output layer, normalize the action range by dimension

The “monotonically rising QQ value” item deserves a separate mention: the QQ value of the DPG family does rise as the policy improves, but if it rises to a magnitude far beyond the true return (for example, a return of 100 with a QQ value of 10⁴), that is overestimation, not successful learning. The criterion is to plot the actual episode return and the mean of QQ on the same graph—the two curves should be roughly of the same order of magnitude. DPG has only one Critic, and the maximization over actions is implicit in its target, so overestimation is almost inevitable; this is exactly the motivation for TD3’s twin critics (see Chapter 15).

13.9 DPG’s Limitations, Scope, and “What Is Still Missing Before DDPG”

Four hard limits:

  1. Continuous actions only. The theorem requires QQ to be differentiable with respect to aa, and no such gradient exists for discrete actions.
  2. The overestimation of a single Critic cannot self-heal. Updating a deterministic policy is equivalent to locally maximizing QQ, and the function-approximation error is systematically amplified upward.
  3. Exploration is strongly coupled to the task. The noise scale must be set according to the physical range of the action, and must be retuned when the task changes; too little noise falls into a local optimum, too much and the Critic cannot learn an effective gradient.
  4. Multimodality cannot be expressed. If two actions are equally good (going around left or right), the gradient of the deterministic output is pulled back and forth by the two modes and finally stops in the middle—an invalid action resembling neither.

Scope of application: continuous, unimodal control tasks with medium-to-high action dimensions (7–30), expensive interaction, or the need to reuse data—manipulator joint control, vehicle steering and throttle, quadruped gait. DPG itself is rarely used directly today; its value has two layers: theoretically, it is a unified view of “policy gradient + value gradient,” treating the stochastic policy gradient as the σ→0\sigma\to0 special case; in engineering, it is the prototype of DDPG and TD3, and once its three gradient paths are understood, the latter two algorithms are merely patches added to these three paths.

Four things are still missing before DDPG, all from DQN’s successful experience (see Chapter 14 for details):

GapDPG’s approachDDPG’s remedy
Data correlationOnline updates, samples discarded after one useExperience replay buffer with random mini-batches
Unstable bootstrappingThe online Critic is used in the targetTarget network + soft updates
Expressive powerLinear / shallow function approximationDeep networks (one each for Actor and Critic)
Inconsistent input scalesManual feature scalingBatch normalization (as in the original paper); today observation standardization is more common

One sentence to remember DPG: take the limit of the stochastic policy’s action integral down to nothing, at the cost that noise must be attached externally, QQ must be differentiable, and overestimation has no one to catch it.


14. DDPG: Deep Deterministic Policy Gradient

14.1 Three bloodlines: DPG’s theorem, DQN’s stabilization, and batch normalization’s input handling

DDPG (Deep Deterministic Policy Gradient, by Lillicrap et al., ICLR 2016) is not a brand-new algorithm; it is a splice of three existing lines of work. Understanding this point is understanding its entire design:

SourceWhat it takesWhich DPG problem it solves
DPG (Silver 2014)The deterministic policy gradient theorem, the two-network Actor-Critic structureThe action-integral problem of high-dimensional continuous actions
DQN (Mnih 2015)Experience replay buffer, target network, off-policy TD learningCorrelated samples, divergent bootstrapping, data used only once
Batch Normalization (Batch Normalization, BN)Standardizing the input of each layerObservations of different physical units (position, velocity, torque) with hugely different scales

Among these three bloodlines, the DQN part is DDPG’s real contribution. DPG’s theorem already existed in 2014, but it assumed that “the Critic can approximate exactly”, and under deep networks that assumption collapses immediately: function-approximation error + bootstrapping + off-policy sampling, all three at once, is the famous “deadly triad”, and training is bound to diverge. DDPG uses two weapons from DQN (replay and the target network) to hold the triad down, and only then does DPG become runnable on deep networks.

14.2 Four components and the network structure

DDPG has four networks (two online/target pairs) plus one buffer:

ComponentNotationInputOutputRole
Actor (online)μθ(s)\mu_\theta(s)State ssAction aa (continuous, dd-dimensional)The target policy; only this one is used at deployment
Critic (online)Qw(s,a)Q^w(s,a)State and action concatenatedScalar Q valuePoints the way for the Actor, and also estimates value
Actor (target)μθ′(s)\mu_{\theta'}(s)State ssAction a′a'Used only to compute the Critic’s target
Critic (target)Qw′(s,a)Q^{w'}(s,a)State and action concatenatedScalar Q valueUsed only to compute the Critic’s target
Replay bufferDD—Transitions (s,a,r,s′,d)(s,a,r,s',d)Breaks sample correlation, reuses data

The Critic’s action must be “concatenated at the input end”, never “attached at the output end”. This is the architectural requirement of the DPG family that is easiest to get wrong in implementation. There are two correct approaches: concat the action vector with the state vector and feed them into the same Multi-Layer Perceptron (Multi-Layer Perceptron, MLP); or, as in DQN, first extract features from the state and then splice the action into the penultimate layer. The wrong approach is “the network outputs the Q value of every discrete action”—that is DQN’s structure, and once the action dimension is not a fixed discrete set, ∇aQ\nabla_aQ cannot be computed at all.

The Actor’s output must be bounded. Physical actions (joint angles, torques) have hard limits. The standard approach is to scale the network output through tanh⁡\tanh to [−1,1][-1,1] and then map it linearly to [amin⁡,amax⁡][a_{\min},a_{\max}]:

a=amax⁡−amin⁡2tanh⁡(uθ(s))+amax⁡+amin⁡2a=\frac{a_{\max}-a_{\min}}{2}\tanh\left(u_\theta(s)\right)+\frac{a_{\max}+a_{\min}}{2}

Note the side effect of tanh⁡\tanh: when ∣u∣|u| is large, tanh⁡\tanh saturates and its derivative tends to 0, so the gradient along the chain ∇aQ⋅∇θμ\nabla_aQ\cdot\nabla_\theta\mu is flattened. Therefore the output layer should use a small initialization (e.g., a uniform distribution on [−3×10−3,3×10−3][-3\times10^{-3},3\times10^{-3}]), and early in training one should monitor whether a large fraction of the tanh⁡\tanh inputs fall into the saturation region.

14.3 Two losses and the soft update

The Critic’s loss (regressing onto a constant label):

yi=ri+γ(1−di)Qw′(si+1,μθ′(si+1))y_i=r_i+\gamma\left(1-d_i\right)Q^{w'}\left(s_{i+1},\mu_{\theta'}(s_{i+1})\right) L(w)=1N∑i=1N(yi−Qw(si,ai))2L(w)=\frac{1}{N}\sum_{i=1}^{N}\left(y_i-Q^w(s_i,a_i)\right)^2

Here di∈{0,1}d_i\in\{0,1\} is the mask of true termination (not truncation). The whole of yiy_i is a constant and must not carry gradient.

The Actor’s objective (maximize the score given by the Critic):

J(θ)=Es∼D[Qw(s,μθ(s))]⟹L(θ)=−1N∑i=1NQw(si,μθ(si))J(\theta)=\mathbb{E}_{s\sim D}\left[Q^w\left(s,\mu_\theta(s)\right)\right]\quad\Longrightarrow\quad L(\theta)=-\frac{1}{N}\sum_{i=1}^{N}Q^w\left(s_i,\mu_\theta(s_i)\right)

The soft update (Polyak averaging):

θ′←τθ+(1−τ)θ′,w′←τw+(1−τ)w′\theta'\leftarrow\tau\theta+(1-\tau)\theta',\qquad w'\leftarrow\tau w+(1-\tau)w'

τ\tau is usually taken as 0.001–0.005.

Why a soft update instead of a hard copy? A hard copy (θ′←θ\theta'\leftarrow\theta every CC steps) makes the target network jump periodically: at every jump, the Critic’s target yy is displaced as a whole, the Critic has to chase it once more, and this shows up as periodic spikes in the Q loss. The soft update spreads that jump over hundreds of steps, so the target follows almost continuously and the evolution of the Q value is much smoother. This is DDPG’s key improvement over DQN’s hard copy, at the cost of storing one extra copy of the parameters and doing one weighted average at every update.

Why can the Actor’s loss be written as −Q-Q? Because automatic differentiation does the chain rule for you:

∇θ[−Qw(s,μθ(s))]=−∇θμθ(s)⊤∇aQw(s,a)∣a=μθ(s)\nabla_\theta\left[-Q^w\left(s,\mu_\theta(s)\right)\right]=-\nabla_\theta\mu_\theta(s)^\top\nabla_aQ^w(s,a)\Big|_{a=\mu_\theta(s)}

The left-hand side is the derivative of the whole composite function, and the right-hand side is exactly the term in the DPG theorem (up to a minus sign, because this is gradient descent). The two writings are equivalent, but in implementation automatic differentiation is more reliable: hand-writing dQ/da easily misses the Jacobian of the action scaling (tanh⁡\tanh and the linear map), which makes the gradient scale off by a constant factor, and then no amount of learning-rate tuning works.

Derivation 25: the gradient of the Critic loss, why the Actor loss is equivalent to the DPG theorem, and why the soft update is an exponential average

Step one: the Critic loss is supervised learning that “regresses onto a constant label”. Differentiate

L(w)=1N∑i=1N(yi−Qw(si,ai))2L(w)=\frac{1}{N}\sum_{i=1}^{N}\left(y_i-Q^w(s_i,a_i)\right)^2

with respect to ww; only the prediction term contains ww:

∇wL(w)=−2N∑i=1N(yi−Qw(si,ai))∇wQw(si,ai)\nabla_w L(w)=-\frac{2}{N}\sum_{i=1}^{N}\left(y_i-Q^w(s_i,a_i)\right)\nabla_w Q^w(s_i,a_i)

Substituting into gradient descent w←w−αw∇wLw\leftarrow w-\alpha_w\nabla_w L gives

w←w+2αwN∑i=1Nδi ∇wQw(si,ai),δi=yi−Qw(si,ai)w\leftarrow w+\frac{2\alpha_w}{N}\sum_{i=1}^{N}\delta_i\,\nabla_w Q^w(s_i,a_i),\qquad \delta_i=y_i-Q^w(s_i,a_i)

That is, every step is “move along the gradient of the prediction with respect to the parameters, pulling the prediction toward the label by the size of the TD error”. This also directly explains why yiy_i must have its gradient cut off: if yiy_i also contained derivatives with respect to ww, the formula above would gain an extra term −∇wyi-\nabla_w y_i, and the sign of the error would be polluted; in the extreme case (target and prediction sharing the same network) y−Q≡0y-Q\equiv0, the gradient is identically zero, and the loss gets stuck.

Step two: the Actor loss is the automatic-differentiation implementation of the DPG theorem. Differentiate

L(θ)=−1N∑i=1NQw(si,μθ(si))L(\theta)=-\frac{1}{N}\sum_{i=1}^{N}Q^w\left(s_i,\mu_\theta(s_i)\right)

treating ww as a constant; only the action-input path remains:

∇θL(θ)=−1N∑i=1N∇θμθ(si)⊤ ∇aQw(s,a)∣a=μθ(si)\nabla_\theta L(\theta)=-\frac{1}{N}\sum_{i=1}^{N}\nabla_\theta\mu_\theta(s_i)^{\top}\,\nabla_a Q^w(s,a)\Big|_{a=\mu_\theta(s_i)}

If the action then passes through tanh⁡\tanh and an affine scaling a=amax⁡−amin⁡2tanh⁡(u)+amax⁡+amin⁡2a=\frac{a_{\max}-a_{\min}}{2}\tanh(u)+\frac{a_{\max}+a_{\min}}{2}, the chain rule must multiply one more diagonal Jacobian:

∇θμθ(s)=diag(amax⁡−amin⁡2(1−tanh⁡2u))∇θu\nabla_\theta\mu_\theta(s)=\mathrm{diag}\left(\frac{a_{\max}-a_{\min}}{2}\left(1-\tanh^2 u\right)\right)\nabla_\theta u

This layer is the one most easily dropped when hand-writing gradients: drop it, and the gradient scale is off by a factor that depends on uu, and that factor itself changes during training (it tends to 0 when tanh⁡\tanh saturates), which shows up as “the Actor learns early on and then stops moving late in training”.

Step three: the soft update is an exponential moving average. Substituting θk′=τθk+(1−τ)θk−1′\theta'_k=\tau\theta_k+(1-\tau)\theta'_{k-1} repeatedly and expanding into an explicit weighted sum:

θk′=τ∑j=0k−1(1−τ)jθk−j+(1−τ)kθ0′\theta'_k=\tau\sum_{j=0}^{k-1}(1-\tau)^{j}\theta_{k-j}+(1-\tau)^{k}\theta'_0

The weights satisfy τ∑j=0k−1(1−τ)j=1−(1−τ)k→1\tau\sum_{j=0}^{k-1}(1-\tau)^j=1-(1-\tau)^k\to1, so it really is “a probability-weighted average over the history of parameters”, with weights decaying exponentially as (1−τ)j(1-\tau)^j and a time constant of about 1/τ1/\tau steps (about 200 steps when τ=0.005\tau=0.005). The difference from a hard copy lies in continuity: the weights of a hard copy are a piecewise constant “equal weight over the most recent CC steps, zero earlier”, and at every refresh the target is first-order discontinuous, so yy jumps as a whole; the soft update spreads that jump into an exponential tail, and the rate of change of yy is limited to about τ∥θ−θ′∥\tau\|\theta-\theta'\| per step.

Step four: why τ\tau is the “stability versus lag” knob. The longer the effective window 1/τ1/\tau, the older the policy reflected by the target, and the deviation from the online policy is about “window length × parameter movement per step”, i.e., proportional to ∥θ−θ′∥/(τ)\|\theta-\theta'\|/(\tau). On one hand this lag suppresses the positive feedback of “the Critic overestimates → the Actor exploits it → the target becomes even higher” described in 15.1 (the target cannot keep up with how fast the Actor exploits); on the other hand it forces the Actor to chase an outdated Q. So τ\tau is not “the smaller the better”: too small and the target hardly moves, learning slows down, and on short-episode tasks the Q value stays too low for a long time.

14.4 Pseudocode: DDPG (complete version)

Algorithm: DDPG (deterministic actor-critic + experience replay + soft target network)
Input: Actor μ_θ, Critic Q^w
       α_θ, α_w          learning rates (typical: Critic 1e-3, Actor 1e-4)
       γ                 discount factor (typical 0.99)
       τ                 soft-update coefficient (typical 0.005)
       N                 mini-batch size (typical 64–256)
       M                 replay buffer capacity (typical 1e6)
       σ                 standard deviation of exploration noise (scaled by the action range)
       T_warm            number of warm-up steps (no updates until the buffer is filled)
Output: θ (only the Actor is used at deployment), w

Initialize: θ, w randomly; θ' ← θ, w' ← w; D ← ∅; noise process N (Gaussian or OU)
            observation normalization statistics (running mean/variance)

Loop (for each episode):
    s ← env.reset()
    for t = 0, 1, 2, … until the episode ends:
        # ---------- Segment 1: sampling ----------
        a_t ← clip(μ_θ(s_t) + N_t, a_min, a_max)      # the behavior policy carries noise
        Execute a_t, observe r_t, s_{t+1}, terminated_t, truncated_t
        D ← D ∪ {(s_t, a_t, r_t, s_{t+1}, terminated_t)}
        s_t ← s_{t+1}

        # ---------- Segment 2: once enough samples are collected, one gradient update per environment step ----------
        if |D| < T_warm: continue
        B ← sample N transitions uniformly from D
        # (a) Critic target: a constant throughout
        with no_grad:
            a'_i ← μ_{θ'}(s'_i)
            q'_i ← min or the single-path Q^{w'}(s'_i, a'_i)        # DDPG uses the single path
            boot_i ← 0 if terminated_i else q'_i
            y_i ← r_i + γ·boot_i
        # (b) Critic update
        L_c ← mean((y_i − Q^w(s_i, a_i))²)                 # or Huber
        w ← w − α_w ∇_w L_c
        # (c) Actor update: the Critic is frozen
        freeze(w)
        L_a ← −mean(Q^w(s_i, μ_θ(s_i)))
        θ ← θ − α_θ ∇_θ L_a
        unfreeze(w)
        # (d) Soft update
        θ' ← τθ + (1−τ)θ'
        w' ← τw + (1−τ)w'

        # ---------- Segment 3: noise decay (optional) ----------
        σ_t ← max(σ_min, σ·(1 − t/T_decay))                # linear decay

Compared with the DPG version in 13.5, this pseudocode adds four things: warm-up (learn only after the replay buffer is filled), mini-batches (each update uses NN transitions), one update per environment step (an update-to-sampling ratio of 1:1, adjustable), and noise decay. All four come from DQN’s experience, and they are the key details that decide whether DDPG can be reproduced successfully.

14.5 Section-by-section commentary on the pseudocode

Segment 1, ①: noise is part of the “behavior policy”, not data augmentation. The purpose of adding noise is to let the sampling distribution cover action regions the Critic has not yet seen, so that the Actor’s gradient is valid at more positions. This is completely different from “adding noise to the observations”—the latter is merely a robustness enhancement and does not change the action distribution. A common mistake is to add noise to the observations, with the result that the Q(s,a)Q(s,a) the Critic learns is misaligned with the true state.

Segment 1, ②: the a_t stored in DD must be the actual action after clipping. If the code first computes a_raw = actor(s) + noise, executes the clipped action, but stores a_raw in the buffer, then the Critic regresses on “an action that was never executed”, which does not match the environment’s real response. The correct order is: add noise → clip → execute → store the clipped value.

Segment 1, ③: the termination mask is multiplied in only one place. DDPG has only one TD target, so the mask is relatively straightforward; but note that terminated and truncated must be kept separate. If the environment library provides only a single done (older Gym), you must split it yourself using TimeLimit.truncated; Gymnasium already separates the two fields, so multiply terminated onto the Qw′Q^{w'} term and leave truncated out of it.

Segment 2, ④: why warm-up is needed. When the replay buffer holds only a few dozen transitions, a random mini-batch consists almost entirely of consecutive fragments of the same trajectory, so the samples are extremely correlated and the Critic overfits to that fragment within a few dozen steps; the Q value first explodes and then collapses. A warm-up of (typically 10310^3–10410^4 steps, or at least 10 times the batch size) gives the buffer enough diverse trajectories. This is also a shared requirement of all off-policy algorithms.

Segment 2, ⑤: the computation of y_i must be inside no_grad, and both target networks must be used. Three points that are easily confused:

  • computing yiy_i with the online networks → the target moves with the parameters, which is equivalent to having no target network;
  • applying .detach() only to yiy_i while still using the online networks → numerically it is still “the current Critic’s estimate”, the target is strongly correlated with the prediction, and the Q value is systematically pulled upward;
  • applying detach only to ai′a'_i while forgetting that Qw′Q^{w'} also needs no gradient → the Critic backpropagates through the target network to w′w', and w′w' is a weighted copy of ww, which amounts to giving the online Critic an implicit gradient path.

Segment 2, ⑥: freeze the Critic during the Actor update, and freeze only the parameters, not the action path. These two requirements are often lumped together. Freeze the parameters with requires_grad_(False); the action path must be preserved, otherwise actor(s) gets no gradient. If torch.no_grad() wraps the whole of critic(s, actor(s)), parameter freezing and gradient cutting happen simultaneously and the Actor cannot learn at all. The correct approach is to freeze the parameters only, letting the forward pass build the graph as usual.

Segment 2, ⑦: the update order of the Actor and the Critic. The standard order is “Critic first, Actor second”. The reason: the Actor’s gradient depends on the ∇aQ\nabla_aQ that the Critic currently provides, so letting the Critic first take one step toward the newest target makes the direction the Actor receives closer to the true direction of improvement. If the order is reversed, the Actor uses the previous step’s Critic and the direction lags by one step; when the Critic’s learning rate is large this noticeably slows convergence. Some implementations put both into the same step() (the wrong practice of sharing one optimizer) or update the Actor first, and no difference is visible in the short run but it is amplified in the long run.

Segment 2, ⑧: the Huber loss is more robust to outliers than MSE. The replay buffer contains poor samples produced by earlier policies as well as reward spikes, and MSE lets these samples dominate the gradient. The Huber loss is equivalent to MSE for small errors and linear for large errors, so the gradient is truncated and training is more stable. The original DDPG paper used MSE, but today’s implementations (including Stable-Baselines3) mostly use Huber or clip the TD error.

Segment 2, ⑨: the soft update is applied to both networks at the same time, and must use the parameters from “before the update”. In implementation, either copy the old parameters out first, or do the weighted update in place exactly as the formula says:

θ′←τθ+(1−τ)θ′\theta'\leftarrow\tau\theta+(1-\tau)\theta'

If it is written as “first θ′←θ\theta'\leftarrow\theta and then θ←τθ+(1−τ)θ′\theta\leftarrow\tau\theta+(1-\tau)\theta'”, it degenerates into a hard copy, which amounts to not doing the soft update at all. This is a pure implementation detail, but it is very hard to see from the curves when debugging—it shows up as periodic spikes in the Q loss, inconsistent with your expectation that “the soft update has already been added”.

Segment 3, ⑩: noise decay is optional but very useful. Early in training large noise is needed to cover the action space; late in training small noise lets the Critic refine around the optimal action. Linear decay (from σ\sigma to σmin⁡\sigma_{\min}, completed within the first 10%–30% of the total steps) is a common choice. Note: decaying to 0 is dangerous—a completely deterministic behavior policy makes the replay buffer lose diversity, the Critic becomes thoroughly inaccurate outside the neighborhood of the optimal action, and the moment the policy drifts slightly it collapses. σmin⁡\sigma_{\min} is usually set to 1%–10% of the initial value.

14.6 Gradient flow and detach: the complete checklist for DDPG

QuantityDoes it need gradient?Which loss it belongs toExplanation
yiy_i (Critic target)NoL(w)L(w)Computed from rir_i, Qw′Q^{w'}, and μθ′\mu_{\theta'}; the whole thing is under no_grad
Qw(si,ai)Q^w(s_i,a_i) (Critic prediction)Yes (with respect to ww)L(w)L(w)Only the online Critic is updated
Qw′(si′,ai′)Q^{w'}(s'_i,a'_i) (target Q)Noyiy_iThe target network is a constant copy
μθ′(si′)\mu_{\theta'}(s'_i) (target action)Noyiy_iSame as above
μθ(si)\mu_\theta(s_i) (Actor output)Yes (with respect to θ\theta)L(θ)L(\theta)The action is the Actor’s output
Qw(si,μθ(si))Q^w(s_i,\mu_\theta(s_i)) (the Q in the Actor loss)Yes for θ\theta, no for wwL(θ)L(\theta)Freeze ww; the gradient only passes through the action input

A side-by-side comparison that can be copied directly:

# ---------- Wrong version: four typical problems ----------
target_q = q_target(s2, actor_target(s2))       # no no_grad: the target carries gradient
y = r + gamma * target_q                         # the termination mask is not multiplied
loss_c = ((y - q(s, a)) ** 2).mean()
loss_a = -q(s, actor(s)).mean()                  # the Critic is not frozen
opt_all.step()                                   # one optimizer manages all parameters

# ---------- Correct version ----------
with torch.no_grad():
    a2 = actor_target(s2)
    boot = q_target(s2, a2) * (1.0 - terminated)
    y = r + gamma * boot

loss_c = F.smooth_l1_loss(q(s, a), y)
opt_c.zero_grad(); loss_c.backward(); opt_c.step()

for p in q.parameters():
    p.requires_grad_(False)
loss_a = -q(s, actor(s)).mean()
opt_a.zero_grad(); loss_a.backward(); opt_a.step()
for p in q.parameters():
    p.requires_grad_(True)

with torch.no_grad():
    for p, p_t in zip(actor.parameters(), actor_target.parameters()):
        p_t.mul_(1 - tau).add_(p, alpha=tau)
    for p, p_t in zip(q.parameters(), q_target.parameters()):
        p_t.mul_(1 - tau).add_(p, alpha=tau)

Three details that are easily confused:

  1. loss_a.backward() accumulates gradients for the Critic’s parameters (even with requires_grad=False the gradients are not written into .grad, but the computation graph is still built). This costs a little extra computation and does not affect correctness; if worried about memory, after freezing you can use the equivalent form q.requires_grad_(False).
  2. The default reduction of smooth_l1_loss is mean, consistent with the 1/N1/N in the pseudocode; when hand-writing (y-q)**2, do not forget .mean().
  3. The soft update must be placed inside no_grad, otherwise every soft update builds a computation graph for the target network, memory grows slowly, and after a few hours of training it overflows. This is one of the hardest memory leaks to diagnose.

14.7 DDPG implementation pitfall checklist

Ordered by frequency of occurrence:

SymptomPossible causeFix
The Q value explodes and the policy degeneratesThe target is not under no_grad, the target uses the online network, the termination mask is missingPut the whole target under no_grad; use the target networks; multiply by terminated
The Actor does not learn and the action hardly changesThe Critic is wrapped in no_grad, or the shared backbone is frozen, or tanh⁡\tanh saturatesCheck the gradient along the action path; separate the networks; small initialization of the output layer
Periodic spikes in the Q lossThe soft update was written as a hard copy, or τ\tau is too largeUpdate in place as θ′←τθ+(1−τ)θ′\theta'\leftarrow\tau\theta+(1-\tau)\theta', with τ≤0.005\tau\le0.005
Completely random early in training, sudden collapse laterInsufficient warm-up, noise decaying too fastWarm up for ≥103\ge 10^3 steps; keep σmin⁡\sigma_{\min} at 1%–10%
Good only within the training distribution, collapses on a new stateThe replay buffer is too small, insufficient explorationBuffer ≥105\ge 10^5; add noise or switch to an OU process
Actions on the real robot exceed the limits and jitterThe output is not clipped, the noise is not clippedtanh⁡\tanh + linear map + clip; another limit in the low-level controller
It collapses when switching tasks, huge differences across seedsObservations are not normalized, reward scales differNormalize observations with running mean/variance; scale rewards; fix 3–5 seeds
Memory keeps growingThe soft update is not under no_grad, or the buffer stores tensors that carry gradientsPut the soft update inside no_grad; .detach() and move to CPU before storing
The Q value is systematically too low at the end of an episodeTruncation is treated as terminationUse only terminated to control bootstrapping
The Critic learns fast but the Actor oscillatesThe Actor learning rate is not smaller than the Critic’s, or the update order is reversedUpdate the Critic first; set αθ\alpha_\theta to 1/5–1/10 of αw\alpha_w

The item “the buffer stores tensors that carry gradients” deserves a separate mention: the data in the replay buffer must be pure numbers unrelated to the computation graph. If you directly D.append((s, a, r, s2, d)) while s comes from a forward pass that carries gradients, the entire computation graph is referenced by the buffer and memory cannot be released. The correct approach is .detach().cpu().numpy() (or at least .detach()).

14.8 Hyperparameters and tuning manual

DDPG is notoriously sensitive to hyperparameters, but the sensitivity is actually concentrated in a few of them. Ordered by importance:

HyperparameterTypical valueSymptom when set wrongDirection of adjustment
Actor learning rate αθ\alpha_\theta1×10−41\times10^{-4}Policy oscillation, Q jitter5–10 times smaller than the Critic’s
Critic learning rate αw\alpha_w1×10−31\times10^{-3}Q does not learn or overshootsTune this one first, then the Actor
Soft update τ\tau0.005Spikes (too large) / lag (too small)0.001–0.005; shorter tasks take smaller values
Batch size NN64–256Too much gradient noise / updates too slowUse 256 when the observation dimension is high
Replay buffer MM10610^6Overfits recent dataAt least 10 times the single-episode length × batch size
Discount γ\gamma0.99Myopia / Q value explodes0.99 for long-horizon tasks; 0.95 is acceptable for very short episodes
Noise σ\sigma10% of the action rangeNo exploration / cannot learnScale by action dimension and physical range
Update-to-sampling ratio1:1Low sample efficiency / overfittingCan be raised to 2:1, but too high overfits
Warm-up steps10310^3–10410^4Early collapseAt least 10× the batch size

How to choose the noise process? Two common choices:

  • Gaussian noise: Nt∼N(0,σ2I)N_t\sim\mathcal{N}(0,\sigma^2I), independent at every step. Simple to implement, no extra state, suitable for tasks with low action dimension and low control frequency.
  • OU process (Ornstein–Uhlenbeck process): Nt+1=Nt+θ(μ−Nt)Δt+σΔt WtN_{t+1}=N_t+\theta(\mu-N_t)\Delta t+\sigma\sqrt{\Delta t}\,\mathcal{W}_t, a mean-reverting continuous stochastic process whose noise is correlated in time. It suits physical systems with inertia: the action noise of two consecutive steps should not be completely independent, otherwise the actuator jitters at high frequency and wears out faster. The original DDPG paper used OU, but a large body of later experiments showed that Gaussian noise is not worse on most tasks and saves one process parameter that needs tuning (θ\theta, μ\mu). Today’s default choice is usually Gaussian plus decay.

Observation normalization matters more than the network structure. The original DDPG paper used batch normalization, but batch normalization becomes inaccurate when the batch is small and the data distribution drifts with the policy (it uses the statistics of the current batch, and the batch comes from policies of different periods). Today’s more common approach is standardization with running mean/variance (maintaining sliding statistics for all observation dimensions) and using the same statistics at inference time. Whether this step is done often decides whether the same hyperparameter configuration “converges” or “completely fails to converge”.

Reward scaling. The magnitude of the reward directly determines the magnitude of Q, which in turn affects the gradient scale. A common practice is to divide the reward by a fixed scale factor (e.g., the standard deviation of the cumulative return, or the mean of the running return), so that the Q value falls in the range of single digits to a few dozen. Note that the scaling must be applied consistently to all losses: the Critic’s target and the Actor’s objective use the same QQ, and scaling changes only the numbers, not the policy, but scaling only one of them breaks consistency.

14.9 DDPG’s position, three pathologies, and scope of application

What it solved: it was the first to land DPG’s theorem on deep networks, proving that “deterministic policy + replay + target network” works for continuous control. Between 2016 and 2018 it was almost the default answer for continuous control, and it is the baseline for every off-policy continuous-control algorithm that came after it.

What it did not solve (three pathologies, which correspond exactly to TD3’s three patches):

PathologyMechanismConsequencePatch (see Chapter 15)
Q overestimationA single Critic, and the target takes “the point given by the policy” over actions; function-approximation error is systematically amplifiedInflated Q values; the policy exploits the errorTwin critics taking the minimum
Actor and Critic updated in syncThe Actor chases a Q that is not yet learned accurately at every stepPolicy oscillation, accumulated varianceDelayed policy updates (once every 2 steps)
The target action is a single pointQ(s′,μθ′(s′))Q(s',\mu_{\theta'}(s')) is evaluated at one point; if Q has a spike there, the target is pollutedUnstable targets, spikes in QTarget policy smoothing (add clipped noise)

How it differs from SAC: DDPG is “deterministic policy + external noise for exploration”, while SAC is “stochastic policy + entropy regularization with built-in exploration”. The former tunes exploration through the noise scale, the latter through a temperature α\alpha that adjusts automatically; the former can express only unimodal actions, the latter can express multimodal ones (see Chapter 16).

Scope of application: continuous-action, unimodal-optimal tasks with medium state dimensions (tens to hundreds of dimensions), where interaction is expensive and data must be reused—manipulator grasping and assembly, vehicle control, quadruped gaits, industrial process control. Not suitable for: discrete actions (use the DQN family), tasks requiring multimodal policies (use SAC), large-scale parallel simulation with a limited tuning budget (use PPO, see 11.9), safety-critical real-robot scenarios (the large exploratory actions during DDPG training are risky and require an extra safety layer).

One sentence to remember DDPG: use DPG’s theorem for the main loop, use DQN’s replay and target network to hold divergence down, and use noise to fill in the exploration that a deterministic policy lacks—get all three right and it runs; miss any one and it fails in one of two ways, “the Q value explodes” or “the Actor does not move”.


15. TD3: Twin Delayed Deep Deterministic Policy Gradient

Twin Delayed Deep Deterministic Policy Gradient (TD3) was proposed by Fujimoto et al. in 2018, and its title is its positioning: “Addressing Function Approximation Error in Actor-Critic Methods”—dealing with function-approximation error in actor-critic methods. It is not a new framework but three patches applied to DDPG: almost every failure of DDPG can be traced to the single source “the Q value is systematically overestimated”, and TD3 uses three changes to cut off, respectively, the generation, the amplification, and the propagation of this error.

The conclusions first, then the breakdown:

PatchNameMechanism in one sentenceWhich disease it treats
OneClipped double Q (clipped double Q)Train two independent Critics and use min⁡\min in the targetThe overestimation of a single Critic
TwoDelayed policy update (delayed policy update)Update the Actor only once every dd Critic updatesThe Actor running after a Q that is not yet learned accurately
ThreeTarget policy smoothing (target policy smoothing)Add clipped noise to the target actionThe single-point QQ value in the target being polluted by spikes

Together the three patches add only one network (the second Critic) and one if check (the delay); the change is minimal, but it raises the stability of continuous control by a notch. This is also why it is still, alongside Soft Actor-Critic (SAC), a default baseline for continuous control.

15.1 Three failure modes: what TD3 is actually fixing

DDPG’s main loop has four steps: sample with noisy actions → update the Critic with y=r+γQw′(s′,μθ′(s′))y=r+\gamma Q^{w'}(s',\mu_{\theta'}(s')) → update the Actor with the ∇aQ\nabla_aQ backpropagated through it → soft-update the target networks. The authors of TD3 split the places where these four steps can go wrong into three classes:

(1) Overestimation. As long as the target contains the semantics of “take the maximum over actions”, the function-approximation error gets picked out and amplified by max⁡\max: actions with positive error are more likely to be selected, so the estimate is systematically too high. DDPG has no explicit max⁡\max, but the Actor’s output μθ(s)\mu_\theta(s) is itself “the action that makes QQ largest”, which amounts to an implicit arg⁡max⁡\arg\max over the continuous action space, and overestimation happens all the same.

(2) Accumulation and propagation. The Critic’s overestimation is chased by the Actor as if it were a real signal (the Actor learns arg⁡max⁡aQw\arg\max_a Q^w), and once the Actor changes, the next round’s target changes too—the error forms positive feedback through “the Critic overestimates → the Actor exploits → the target becomes even higher”. The closer γ\gamma is to 1, the closer the amplification factor of this loop is to 1/(1−γ)1/(1-\gamma).

(3) High variance of the target. Q(s′,μθ′(s′))Q(s',\mu_{\theta'}(s')) is a value taken at one point. If QQ happens to have a spike caused by approximation error near this point, the target is polluted by that spike, and this erroneous target is immediately fed back into the Critic’s regression. A point estimate has no “averaging over neighbors” effect, and is therefore extremely sensitive to spikes.

These three modes are progressive: overestimation creates bias, bootstrapping amplifies the bias, and the point estimate adds variance on top. TD3’s three patches correspond to them one by one.

15.2 Patch one: clipped double Q

The approach: maintain two Critics Qw1Q_{w_1} and Qw2Q_{w_2} with identical structure and independent parameters; both regress onto the same target, but the value inside the target is the smaller of the two:

y=r+γ(1−d)min⁡i∈{1,2}Qwi′(s′,a~′)y = r + \gamma(1-d)\min_{i\in\{1,2\}}Q_{w'_i}(s',\tilde a')

Here dd is the termination flag (1 for true termination, 0 for truncation or non-termination), and a~′\tilde a' is the smoothed target action discussed in the next section. The Actor is updated using only the first Critic: max⁡θQw1(s,μθ(s))\max_\theta Q_{w_1}(s,\mu_\theta(s)).

Derivation 26: why taking $\max$ is necessarily biased upward, and whether taking $\min$ can fix it

Step one: write out the error. Let the true value be Q∗(s,a)Q^*(s,a) and the estimate be Qw(s,a)=Q∗(s,a)+ϵ(s,a)Q_w(s,a)=Q^*(s,a)+\epsilon(s,a), where ϵ\epsilon is a zero-mean approximation error (independent across actions, with variance σ2\sigma^2). Take the maximum over the candidate action set {a1,…,aK}\{a_1,\dots,a_K\}:

E[max⁡kQw(s,ak)]=max⁡kQ∗(s,ak)+E[max⁡kϵ(s,ak)]\mathbb{E}\left[\max_k Q_w(s,a_k)\right]=\max_k Q^*(s,a_k)+\mathbb{E}\left[\max_k \epsilon(s,a_k)\right]

Step two: prove that the second term is non-negative. The max operation is a convex function of the error vector, so by Jensen’s inequality

E[max⁡kϵ(s,ak)] ≥ max⁡kE[ϵ(s,ak)]=0\mathbb{E}\left[\max_k \epsilon(s,a_k)\right]\ \ge\ \max_k\mathbb{E}\left[\epsilon(s,a_k)\right]=0

Equality holds only when the error is constant (no randomness). The more candidates and the larger σ\sigma, the more pronounced the upward bias. In DDPG the “candidates” are the single point the Actor picks in each state, but because it picks on the same noisy QQ, this is equivalent to “taking the peak on a surface polluted by noise”, and the conclusion is the same.

Step three: amplification through bootstrapping. Once a one-step upward bias δ\delta enters the target, it is further overestimated as the baseline for the next step. Expanding Qk+1=r+γ(Qk+δ)Q_{k+1}=r+\gamma(Q_k+\delta) shows that the bias accumulates as ∑kγkδ=δ/(1−γ)\sum_{k}\gamma^k\delta=\delta/(1-\gamma). With γ=0.99\gamma=0.99 this is about a factor of 100—this is why overestimation is especially deadly on long-horizon tasks.

Step four: why min⁡\min works. The min⁡\min of two independent errors ϵ1,ϵ2\epsilon_1,\epsilon_2 satisfies

E[min⁡(ϵ1,ϵ2)] ≤ min⁡(E[ϵ1],E[ϵ2])=0\mathbb{E}\left[\min(\epsilon_1,\epsilon_2)\right]\ \le\ \min\left(\mathbb{E}[\epsilon_1],\mathbb{E}[\epsilon_2]\right)=0

i.e., min⁡\min is biased downward. So TD3’s use of min⁡\min is “replacing an uncontrollable upward bias with a controllable downward bias”: the downward bias makes Q slightly conservative, a conservative policy does not exploit fake high-value regions, and training is therefore stable. The cost is that the true value may be underestimated, but since the goal is “learn a policy that works” rather than “estimate Q∗Q^* exactly”, the trade is worthwhile.

Step five: why the two Critics must be independent. If the two Critics share all parameters, ϵ1=ϵ2\epsilon_1=\epsilon_2, min⁡\min degenerates to a single one, and the patch fails. In practice they can be fully independent, or share only the earlier feature-extraction layers (sharing reduces computation but weakens independence and discounts the suppression of overestimation).

Why not use Double DQN’s “decouple selection from evaluation”? Double DQN’s approach is “use one network to select the action and another network to evaluate that action”, which is unbiased in theory. TD3 tried this route, but in an actor-critic setting “selecting the action” is done by the Actor and both Critics must be trained, so decoupling introduces new instability; in the end the authors chose the simpler and empirically more stable min⁡\min version.

15.3 Patch two: delayed policy updates

The approach: the Critic is updated every step, while the Actor is updated only every dd steps (with d=2d=2 by default), and the target networks are soft-updated together only when the Actor is updated.

Why: the Actor’s gradient is ∇θμθ(s)⊤∇aQw(s,a)\nabla_\theta\mu_\theta(s)^\top\nabla_aQ_w(s,a), which directly depends on the shape of QwQ_w. If QwQ_w is still changing violently (which is almost inevitable early in training), the Actor is chasing a moving target at every batch and pushes its parameters toward the local spikes of QQ—and most of those spikes are approximation error, not real structure. Letting the Actor move only after the Critic has stabilized somewhat amounts to giving the “referee” a little time to learn the rules first.

This is not the same thing as the “target network”. The target network (soft update) solves “jitter in the bootstrapping target”, while the delayed update solves “the mismatch in update frequency between the Actor and the Critic”. The two are often conflated, but removing either causes degeneration: delay without soft updates and the target still jumps; soft updates without delay and the Actor is still chasing noise.

The cost: the number of interaction steps needed for convergence increases slightly (the number of Actor updates is halved), but this cost is far smaller than the cost of “training collapses and you start over”.

Derivation 27: why "chasing a Q that is still changing" causes a mismatch, and what delaying by $d$ steps changes (order-of-magnitude analysis)

Step one: write out the Actor’s update direction and its dependence on Q. At every step the Actor does

θk+1=θk−αθ∇θ[−Qwk(s,μθk(s))]=θk+αθ ∇θμθk(s)⊤∇aQwk(s,a)∣a=μθk(s)\theta_{k+1}=\theta_k-\alpha_\theta\nabla_\theta\left[-Q_{w_k}\left(s,\mu_{\theta_k}(s)\right)\right]=\theta_k+\alpha_\theta\,\nabla_\theta\mu_{\theta_k}(s)^{\top}\nabla_aQ_{w_k}(s,a)\Big|_{a=\mu_{\theta_k}(s)}

The direction is entirely determined by “the gradient of the current Critic along the action dimension”. If QwkQ_{w_k} differs from the true QπQ^{\pi} by Δk=Qwk−Qπ\Delta_k=Q_{w_k}-Q^{\pi}, then the error in the direction is ∇θμ⊤∇aΔk\nabla_\theta\mu^\top\nabla_a\Delta_k—the Actor does not walk along “the true direction of improvement” but along “the true direction plus the gradient of the error”.

Step two: write the two speeds as a ratio. Each Critic update contracts the TD error by a factor (1−αwλ)(1-\alpha_w\lambda) (λ\lambda being a constant related to the feature covariance); each Actor update moves the parameters by αθ∥∇θμ∥∥∇aQ∥\alpha_\theta\|\nabla_\theta\mu\|\|\nabla_aQ\|. When the two share the same update frequency (DDPG), for every step the Actor takes, the shape of Q also changes by a step of the same order, so Δk\Delta_k does not decrease monotonically with kk—the Actor chases a target that moves at its own speed. If the Actor moves only once every dd steps, then between two Actor updates the Critic has already converged d−1d-1 more steps, and the error the Actor faces shrinks to roughly the order of κdΔ\kappa^{d}\Delta (κ<1\kappa<1 being the per-step contraction rate of the Critic’s error).

Step three: this is a frequency allocation of “who should converge first”. The Critic’s error must cover the whole state–action space and needs the most updates; the Actor only needs one reliable gradient direction, and when Q is unstable its updates carry no information and merely accumulate noise into the parameters. Setting the Critic’s update frequency to dd times the Actor’s is essentially writing the dependency “the Critic converges first” into the loop structure, instead of approximating it by lowering the Actor’s learning rate (which also slows down the Actor’s later improvement).

Step four: the cost and the boundary. The number of Actor updates drops to 1/d1/d, so under the “one update per environment step” setting the rate of policy improvement drops by roughly a factor of dd and the number of interaction steps needed for convergence rises; at the same time, the larger dd is, the older the Q the Actor uses (lagging by dd steps) and the more outdated the direction of policy improvement. d=2d=2 is the empirical compromise: it lets the Critic lead by one step without letting the Actor fall noticeably behind. With d=4d=4 or more, the return curve typically shows a markedly longer plateau.

Note: the κd\kappa^{d} in step two is an order-of-magnitude estimate obtained by modeling “geometric contraction of the error”; it is used to explain the mechanism, not as a convergence theorem. The rigorous conclusion depends on the specific function approximation and step-size conditions.

15.4 Patch three: target policy smoothing

The approach: when computing the target, do not use μθ′(s′)\mu_{\theta'}(s') directly; add a small amount of noise around it and clip:

a~′=clip(μθ′(s′)+clip(ϵ,−c,c), amin⁡,amax⁡),ϵ∼N(0,σ2I)\tilde a' = \mathrm{clip}\left(\mu_{\theta'}(s')+\mathrm{clip}(\epsilon,-c,c),\ a_{\min},a_{\max}\right),\qquad \epsilon\sim\mathcal{N}(0,\sigma^2 I)

By default c=0.5c=0.5 and σ=0.2\sigma=0.2 (when the actions are normalized to [−1,1][-1,1]). Note that here there are two layers of clipping: first the noise magnitude is clipped to [−c,c][-c,c], and then the result is clipped back into the physical range of the action.

Why: this is equivalent to replacing “evaluating at one point” with “an approximation of averaging over a neighborhood”. If QQ has a spike caused by error near μθ′(s′)\mu_{\theta'}(s'), then with noise the target samples the lower values beside the spike, and the spike cannot be fed back into the Critic through the target. Mathematically this is equivalent to applying a local smoothing regularizer to QQ, forcing QQ to become flat near the target action—and a flat QQ is exactly the kind of QQ the Actor can exploit stably: when the Actor moves along ∇aQ\nabla_aQ it does not jump onto a spike in one step.

Why must the noise be clipped instead of using an unbounded Gaussian? Unbounded noise pushes the target action into regions far from the current policy, where QQ has no data support at all and its value is purely extrapolated; the larger the noise, the less trustworthy the target. Clipping ensures that the smoothing happens only within a neighborhood that “has data and deserves trust”.

An intuitive analogy: this approach shares its origin with “expected SARSA” and “double Q-learning”—all of them take an expectation or remove a bias from the target, trading a little bias for a clear reduction in variance.

Derivation 28: why taking an expectation over noise is equivalent to locally smoothing $Q$ (Taylor expansion and second moments)

Step one: write “the value after adding noise” as an expectation over the noise. Denote the target action by a=μθ′(s′)a=\mu_{\theta'}(s'); the perturbed target action and the label are

a~′=clip(a+ϵ~, amin⁡,amax⁡),ϵ~=clip(ϵ,−c,c),y=r+γ(1−d) Q(s′,a~′)\tilde a'=\mathrm{clip}\left(a+\tilde\epsilon,\ a_{\min},a_{\max}\right),\qquad \tilde\epsilon=\mathrm{clip}\left(\epsilon,-c,c\right),\qquad y=r+\gamma(1-d)\,Q\left(s',\tilde a'\right)

Ignore for now the outer clipping by the “action range”, and suppose ϵ~\tilde\epsilon is symmetrically distributed on [−c,c][-c,c] with variance σc2\sigma_c^2. Taking the expectation over the noise:

E[y]=r+γ(1−d) Eϵ~[Q(s′,a+ϵ~)]\mathbb{E}[y]=r+\gamma(1-d)\,\mathbb{E}_{\tilde\epsilon}\left[Q(s',a+\tilde\epsilon)\right]

Step two: do a second-order Taylor expansion at aa. Expand Q(s′,a+ϵ~)Q(s',a+\tilde\epsilon) to second order:

Q(s′,a+ϵ~)≈Q(s′,a)+∇aQ⊤ϵ~+12ϵ~⊤∇a2Q ϵ~Q(s',a+\tilde\epsilon)\approx Q(s',a)+\nabla_aQ^{\top}\tilde\epsilon+\frac{1}{2}\tilde\epsilon^{\top}\nabla_a^2Q\,\tilde\epsilon

After taking the expectation, the first-order term vanishes by symmetry E[ϵ~]=0\mathbb{E}[\tilde\epsilon]=0, leaving

E[Q(s′,a+ϵ~)]≈Q(s′,a)+12tr(σc2I⋅∇a2Q)=Q(s′,a)+σc22ΔaQ(s′,a)\mathbb{E}\left[Q(s',a+\tilde\epsilon)\right]\approx Q(s',a)+\frac{1}{2}\mathrm{tr}\left(\sigma_c^2 I\cdot\nabla_a^2Q\right)=Q(s',a)+\frac{\sigma_c^2}{2}\Delta_a Q(s',a)

where Δa\Delta_a is the Laplacian in the action dimensions (the trace of the Hessian). This step shows: adding noise and then taking the expectation ≈ the original value + a curvature term. At a local maximum of QQ (a spike) the Laplacian is negative, and smoothing pushes it down; at a local minimum (a sharp valley) it is positive, and smoothing pushes it up. In other words, target smoothing applies a “curvature penalty” to QQ, forcing it to flatten near the target action.

Step three: why this exactly suppresses “spikes being fed back”. The Critic uses yy as the regression label. If QQ has a narrow spike at aa caused by approximation error, then without smoothing yy samples the high value at the top of the spike directly, that high value becomes the baseline in the next round, and the spike reinforces itself. After smoothing, the label is “the average over a small patch around the peak”, the peak’s high value is diluted by the neighboring low values, and the strength of the feedback drops by an order of magnitude of 1/(1+σc2)1/(1+\sigma_c^2). This divides the labor differently from the min⁡\min in 15.2: min⁡\min suppresses first-order upward bias, while smoothing suppresses the second-order spike variance.

Step four: why the noise must be clipped. Under an unbounded Gaussian, E[ϵ~]=0\mathbb{E}[\tilde\epsilon]=0 still holds, but the second moment grows without bound as σ\sigma increases, and the Taylor expansion fails far away from aa—there QQ is entirely extrapolated, the “curvature” in the expansion is fabricated by the network, smoothing samples meaningless low values, and yy is systematically pulled down. Clipping restricts the integral to a neighborhood that “has data and where QQ is trustworthy”; and symmetric clipping still preserves E[ϵ~]=0\mathbb{E}[\tilde\epsilon]=0, so it introduces no first-order shift, only a controlled second-order term.

Step five: the net effect when combined with “double Q taking the min”. min⁡\min pushes the estimate downward (downward bias), and smoothing further suppresses spikes (reducing variance); together they make QQ slightly conservative with a flatter shape. Conservative plus flat is exactly the terrain the Actor wants when walking along ∇aQ\nabla_aQ: it will not step onto a spike in one step, and it will not exploit fake high-value regions.

15.5 Complete pseudocode (TD3)

Input: state dimension n_s, action dimension n_a, action bounds a_min/a_max
Hyperparameters: γ=0.99, τ=0.005, batch N=256, replay capacity 1e6,
                 exploration noise σ_expl, target smoothing noise σ̃=0.2 and clipping c=0.5,
                 policy delay d=2, warm-up steps T_warm, total steps T_total
Initialize: Actor μ_θ (output scaled through tanh to [a_min, a_max])
            Critics Q_{w1}, Q_{w2} (input concat(s, a), scalar output)
            target networks θ' ← θ, w'_1 ← w_1, w'_2 ← w_2
            replay buffer D ← ∅

for t = 1 … T_total:
    # ① Sample: the behavior policy = current Actor + external noise
    a = clip(μ_θ(s) + ε, a_min, a_max), ε ~ N(0, σ_expl² I)
    Execute a, observe r, s', d (d=1 means true termination)
    Store (s, a, r, s', d) into D

    if t < T_warm: continue          # ② during warm-up, only sample, do not update

    # ③ Draw a batch uniformly from the replay buffer (breaking time correlation)
    Draw N transitions (s_i, a_i, r_i, s'_i, d_i) uniformly from D

    # ④ Build the target (note: no graph is built anywhere in here)
    with no_grad:
        ε̃ ~ N(0, σ̃² I), clipped to [-c, c]
        ã'_i = clip(μ_{θ'}(s'_i) + ε̃, a_min, a_max)
        y_i = r_i + γ (1 - d_i) · min(Q_{w'_1}(s'_i, ã'_i), Q_{w'_2}(s'_i, ã'_i))

    # ⑤ Both Critics regress onto the same y
    L_c = (1/N) Σ_i [ huber(y_i - Q_{w_1}(s_i, a_i)) + huber(y_i - Q_{w_2}(s_i, a_i)) ]
    w_1 ← w_1 - α_c ∇_{w_1} L_c
    w_2 ← w_2 - α_c ∇_{w_2} L_c

    # ⑥ Delayed policy update: the Actor and the target networks move only every d steps
    if t % d == 0:
        Freeze the parameters of Q_{w1} (only borrow its gradient for the Actor; do not change it itself)
        L_a = -(1/N) Σ_i Q_{w_1}(s_i, μ_θ(s_i))
        θ ← θ - α_a ∇_θ L_a
        Unfreeze Q_{w1}
        Soft update: w'_1 ← τ w_1 + (1-τ) w'_1
                     w'_2 ← τ w_2 + (1-τ) w'_2
                     θ'  ← τ θ  + (1-τ) θ'

15.6 Section-by-section commentary

① Sampling uses “Actor + external noise”. TD3’s policy is deterministic, so exploration relies entirely on attached noise, the same as in DDPG. Decaying the noise scale during training is standard practice. What is stored in the replay buffer is the action aa actually executed after clipping, not μθ(s)\mu_\theta(s) before the noise was added—what the Critic must learn is “how much is this action worth”, not “how much is the ideal action worth”, and confusing the two is the most common silent error in DDPG/TD3.

② During warm-up, only sample. When the replay buffer does not yet contain sufficiently diverse data, almost all of the Critic’s regression targets come from itself (bootstrapping onto itself), and divergence is very likely. The warm-up is typically a few thousand to a few tens of thousands of steps, depending on the state dimension of the task.

③ Draw batches uniformly, not in time order. Adjacent transitions are highly correlated, and using them directly makes the Critic fit “the most recent stretch of trajectory” rather than the global value function. The core role of the replay buffer is precisely to break up the time correlation.

④ The target is where “all three changes take effect”. Here appear simultaneously: min⁡\min (patch one), the noise and double clipping of a~′\tilde a' (patch three), and μθ′\mu_{\theta'} rather than μθ\mu_\theta (the target networks). This block must be completed inside no_grad, and the whole of yiy_i must be used as a constant.

⑤ Both Critics use the same yy. Note that the two losses share the same yiy_i; they are not allowed to compute their own yy (e.g., each using its own min⁡\min or its own μ\mu), otherwise the independence of the double Q is destroyed. Also note: in training each regresses its own output, and they do not “also take the min”—the min is taken only when constructing the target.

⑥ The Actor is updated using only Qw1Q_{w_1}. This is the choice of the original paper, for the reason that Qw2Q_{w_2} is already part of the min⁡\min in yy, and making the Actor optimize both Critics at once would weaken the debiasing effect of the min⁡\min. The engineering approximation is “use only the first one”, and empirically confirm that it is stable enough. The freezing in this block is not optional—without freezing, the gradient of LaL_a would run through Qw1Q_{w_1} all the way into the Critic’s parameters, and the Critic would be polluted by the Actor’s loss.

⑦ The delayed update is coupled with the soft update. The tt in t % d == 0 is the environment step count, not the episode count and not the gradient step count. The soft update uses τ=0.005\tau=0.005: the target network moves only 0.5% per step, which amounts to an exponential moving average with a time constant of about 200 steps. When writing the soft update, it must be under no_grad and updated in place (otherwise a new tensor is created instead of moving the parameters).

⑧ The termination mask is multiplied in only one place. On true termination y=ry=r (1−d1-d zeroes the bootstrapping term); on time truncation (e.g., forced reset upon reaching the step limit) d=0d=0 and bootstrapping must still happen. Treating truncation as termination makes the value drop by a chunk out of nowhere near the time boundary; this is a pitfall shared with DQN, SAC, and PPO.

15.7 Gradient flow and detach checklist

TD3’s computation graph has one more edge than DDPG’s (two Critics), but the principle of “which quantities must be cut off” is exactly the same: anything used as a “target” must be treated as a constant.

QuantityAppears inDetach?Consequence of not cutting it off
The whole target yiy_iCritic lossRequired (no_grad)The target moves with the parameters being optimized, the loss is always 0, and the Critic learns nothing
a~′\tilde a' (with noise)Inside yiy_iRequiredThe noise gradient backpropagates into the target networks, and the target networks are driven by noise
μθ′(s′)\mu_{\theta'}(s')Inside a~′\tilde a'Required (the target network itself has no gradient)Same as above
Qw1′,Qw2′Q_{w'_1},Q_{w'_2}Inside yiy_iRequired (target network parameters)The target changes in sync with the online networks and the bootstrapping loop closes
Qw1(s,μθ(s))Q_{w_1}(s,\mu_\theta(s))Actor lossMust not detachThe Actor gets no gradient at all and its parameters never update
The parameters of Qw1Q_{w_1}Actor lossMust be frozen (requires_grad=False)The Critic is directly modified by the objective “maximize Q”, which is equivalent to grading its own exam

Side-by-side correct and wrong versions (PyTorch):

# Correct: first compute the constant target under no_grad, then regress both Critics separately
with torch.no_grad():
    noise = (torch.randn_like(a_next) * sigma_tilde).clamp(-c, c)
    a_tilde = (mu_target(s_next) + noise).clamp(a_min, a_max)
    q1_t = q1_target(s_next, a_tilde)
    q2_t = q2_target(s_next, a_tilde)
    y = r + gamma * (1.0 - d) * torch.min(q1_t, q2_t)

loss_c = F.smooth_l1_loss(q1(s, a), y) + F.smooth_l1_loss(q2(s, a), y)

# Correct: the Actor only borrows the gradient of Q1, with Q1's parameters frozen
for p in q1.parameters():
    p.requires_grad_(False)
loss_a = -q1(s, actor(s)).mean()
loss_a.backward()          # the gradient only reaches the Actor's parameters
for p in q1.parameters():
    p.requires_grad_(True)

# Wrong: the target is not cut off — loss_c will immediately drop to 0 and the Critic learns nothing
y = r + gamma * (1.0 - d) * torch.min(q1(s_next, mu_target(s_next)), q2(s_next, mu_target(s_next)))

# Wrong: the Actor loss is written as "maximize all Qs" and the parameters are not frozen
loss_a = -(q1(s, actor(s)) + q2(s, actor(s))).mean()

Note that q1_t and q2_t use the target networks (q1_target/q2_target), not the online networks; the names are similar, and one wrong line becomes “bootstrapping the online network with the online network”, which is equivalent to turning the target network off.

15.8 Pitfall checklist

PitfallSymptomCorrect practice
The two Critics share all parametersDouble Q degenerates to single Q and overestimation remainsFully independent, or share only the feature layers and accept a discounted effect
Taking min⁡\min also during training before regressingBoth Critics are pulled to the same shape by the same min⁡\min, and independence is lostmin⁡\min is used only to construct yy; in training each regresses its own output
The target smoothing noise is not clippedThe target action runs into regions without data and Q becomes extrapolation noiseClip the noise with cc first, then clip back to amin⁡/amax⁡a_{\min}/a_{\max}
The smoothing noise scale is set too largeThe target is too conservative, learning is extremely slow or does not happen at allStart from σ=0.2\sigma=0.2, c=0.5c=0.5; after action normalization do not exceed 0.3
The delay is judged by “episode count”Episodes have different lengths, so the actual delay in steps is randomUse the environment step count t % d == 0
The Critic is not frozen during the Actor updateThe Critic is directly modified by “maximize Q”Freeze the parameters with requires_grad_(False) and restore them after backward
The soft update forgot no_grad or used a non-in-place formMemory explodes, or the target networks never move at allwith torch.no_grad(): p.mul_(1-tau).add_(p_src, alpha=tau)
The exploration noise is not clipped to the action rangeThe executed action is out of bounds and the environment’s behavior does not match the stored dataClip the sampled action, then execute, then store
Truncation is treated as terminationA spurious dip in value near the time boundaryThe terminated mask is 1 and the truncated mask is 0
The reward magnitude is not scaledThe Q value magnitude is too large, the Huber threshold becomes ineffective, and the gradient scales are mismatchedNormalize the rewards and let all losses use the same scaled Q
Insufficient warm-upEarly in training Q bootstraps onto itself and diverges immediatelyWarm up on the order of 1e4 steps, and fill the replay buffer with a random policy first

15.9 Item-by-item comparison of TD3 and DDPG, hyperparameters, and scope of application

DimensionDDPGTD3
Number of Critics12 (the target takes the min⁡\min)
Target actionμθ′(s′)\mu_{\theta'}(s')μθ′(s′)+\mu_{\theta'}(s')+ clipped noise
Actor update frequencyEvery stepEvery d=2d=2 steps
When the target networks updateSoft update every stepSoft update in sync with the Actor update
Tendency to overestimatePronouncedSuppressed by min⁡\min (slightly underestimated)
Implementation increment—One extra network + one if
Typical behaviorSensitive to hyperparameters, Q values often inflatedMore stable, less sensitive to random seeds

Reference default hyperparameters (continuous control, actions normalized to [−1,1][-1,1]):

HyperparameterCommon valueExplanation
γ\gamma0.99Same as DDPG
τ\tau0.005Soft-update coefficient; the smaller, the more stable the target
Batch size NN256256–1024
Actor / Critic learning rate3×10−43\times10^{-4} / 3×10−43\times10^{-4}Both Adam
Target smoothing noise σ\sigma / clipping cc0.2 / 0.5Values from the original paper
Policy delay dd2Too large (e.g., 4) and the Actor stops learning
Exploration noise0.1 with decayGaussian; OU is generally not used

Scope of application: continuous-action, unimodal-optimal tasks with medium-to-high state dimensions, where interaction is expensive and data must be reused, and where a large tuning budget is not desirable—manipulator assembly, quadruped and biped gaits, vehicle trajectory tracking, industrial process control. Its difference from SAC lies in the exploration mechanism: TD3 relies on attached noise and its target is a deterministic unimodal policy; SAC writes entropy into the objective and can express multimodal policies. This can be remembered in one sentence: want it simple, controllable, and behavior reproducible (remove the noise at deployment and you have a deterministic policy) → TD3; want stronger exploration and greater multimodal expressiveness → SAC (see Chapter 16).

What it did not solve: ① the policy is still deterministic, so on multimodal tasks the two modes are still averaged into one invalid action; ② the exploration noise is set by hand, and when the task is sensitive to the noise scale it still needs tuning; ③ it does not apply to offline data (TD3 itself has no constraint on out-of-distribution actions, and TD3+BC only filled this gap later); ④ it is useless for discrete actions, where the DQN family should be used.

One sentence to remember TD3: make three tiny changes on top of DDPG—take the min of the double Q in the target, let the Actor move two steps slower, and add a bit of clipped noise to the target action—and cut the positive-feedback chain “overestimation → bootstrapping amplification → Actor exploitation” off at its source.


16. SAC: Maximum Entropy Actor-Critic

Soft Actor-Critic (SAC) was proposed by Haarnoja et al. in 2018. It is from the same year as TD3 and belongs to the same “off-policy baseline for continuous control” family, yet it takes a completely different route: TD3 fixes the bias of the value estimate, whereas SAC changes the objective function itself—it adds an entropy term (entropy, a quantity measuring how random the policy is) to the return, so that the policy automatically trades off between “getting a high return” and “staying random”.

The chain reaction of this change is elegant: once the objective changes, the optimal policy changes from “a deterministic single point” to “a Boltzmann distribution”, the value backup changes from max⁡\max to a “soft maximum”, exploration changes from “attached noise” to “built into the policy itself”, and the temperature coefficient α\alpha can adjust automatically. So SAC neither needs manual tuning of the noise scale nor fears multimodal tasks—it is one of the least troublesome default options in continuous control today.

16.1 Why add entropy: three motivations

Motivation one: exploration built in rather than attached. DDPG and TD3 explore by adding Gaussian noise to actions—the noise scale is a hyperparameter that must be retuned whenever the task changes; too little and there is no exploration, too much and the policy is ruined. Entropy regularization writes “randomness” into the objective: the more random the policy, the larger the objective, so the policy keeps a certain amount of randomness by itself, and this randomness converges automatically during training (more exploration is needed early, and it naturally tightens later).

Motivation two: multimodal actions. When there are two optimal actions (go around to the left or around to the right), a deterministic policy averages the gradients of the two modes into one invalid action “right in the middle”. A stochastic policy can output a bimodal distribution, keeping both peaks and choosing either one at execution time—this makes a huge difference on “symmetric environment + obstacle” tasks.

Motivation three: robustness and smoothness. Entropy regularization prefers a policy that “performs well on several nearby actions” over a fragile policy where “only one precise action scores high”. Such a policy is more tolerant of execution error, observation noise, and dynamics perturbation, and is often more stable in simulation-to-reality (sim-to-real) transfer.

The costs must also be stated up front: ① the objective is “return + entropy”, so the final policy is not purely return-optimal; when α\alpha is too large it sacrifices performance for randomness; ② the policy is stochastic, so at deployment one must take the mean (or fix the seed) to be reproducible; ③ compared with TD3 there is one more quantity to tune (α\alpha and its target entropy), although SAC v2 provides an automatic scheme.

16.2 The maximum entropy objective and the soft Bellman equation

The maximum entropy objective (maximum entropy objective):

J(π)=Eτ∼π[∑t=0∞γt(rt+α H(π(⋅∣st)))],H(π(⋅∣s))=−Ea∼π[log⁡π(a∣s)]J(\pi)=\mathbb{E}_{\tau\sim\pi}\left[\sum_{t=0}^{\infty}\gamma^{t}\left(r_t+\alpha\,\mathcal{H}\left(\pi(\cdot\mid s_t)\right)\right)\right],\qquad \mathcal{H}\left(\pi(\cdot\mid s)\right)=-\mathbb{E}_{a\sim\pi}\left[\log\pi(a\mid s)\right]

α>0\alpha>0 is the temperature coefficient (temperature), controlling the weight of “entropy” relative to “reward”: as α→0\alpha\to0 it degenerates to the ordinary return, and as α→∞\alpha\to\infty it becomes a purely random policy. Note that the entropy is discounted by γt\gamma^t together with the reward—this makes “explore more early and less later” mathematically self-consistent, instead of relying on an empirical trick such as noise decay.

Under this objective, the definition of the value function must also change:

Qπ(s,a)=r+γ Es′∼P[Vπ(s′)],Vπ(s)=Ea∼π[Qπ(s,a)−αlog⁡π(a∣s)]Q^{\pi}(s,a)=r+\gamma\,\mathbb{E}_{s'\sim P}\left[V^{\pi}(s')\right],\qquad V^{\pi}(s)=\mathbb{E}_{a\sim\pi}\left[Q^{\pi}(s,a)-\alpha\log\pi(a\mid s)\right]

These two equations together are called the soft Bellman equation (soft Bellman equation). The only difference from the classical Bellman equation is one place: the right-hand side of VV has one extra subtracted term αlog⁡π(a∣s)\alpha\log\pi(a\mid s)—“the entropy cost that must be paid for choosing this action”. The more deterministic the policy (with π\pi close to 1 on some action and log⁡π→0\log\pi\to0), the smaller the cost; the more random the policy, the larger the cost.

Derivation 29: why the soft Bellman backup is a log-sum-exp, and why the optimal policy is a Boltzmann distribution

Step one: write “taking the maximum over actions” as “taking the maximum over policies”. Define the soft value

V(s)=max⁡π∈Δ Ea∼π[Q(s,a)−αlog⁡π(a∣s)]V(s)=\max_{\pi\in\Delta}\ \mathbb{E}_{a\sim\pi}\left[Q(s,a)-\alpha\log\pi(a\mid s)\right]

Here Δ\Delta is the simplex (the set of all valid probability distributions). The max⁡a\max_a in the classical Bellman equation means “you may choose only one action”; now it means “you may choose a distribution, but you must pay the entropy cost”.

Step two: solve this constrained optimization with a Lagrange multiplier. Introduce the constraint ∑aπ(a∣s)=1\sum_a\pi(a\mid s)=1 with the multiplier λ\lambda:

L=∑aπ(a∣s)[Q(s,a)−αlog⁡π(a∣s)]+λ(∑aπ(a∣s)−1)\mathcal{L}=\sum_a \pi(a\mid s)\left[Q(s,a)-\alpha\log\pi(a\mid s)\right]+\lambda\left(\sum_a\pi(a\mid s)-1\right)

Take the variational derivative with respect to π(a∣s)\pi(a\mid s) and set it to zero (note that ∂∂π[πlog⁡π]=log⁡π+1\frac{\partial}{\partial\pi}\left[\pi\log\pi\right]=\log\pi+1):

Q(s,a)−α(log⁡π(a∣s)+1)+λ=0Q(s,a)-\alpha\left(\log\pi(a\mid s)+1\right)+\lambda=0

Rearranging gives

π(a∣s)=exp⁡(Q(s,a)α)exp⁡(−λα−1)\pi(a\mid s)=\exp\left(\frac{Q(s,a)}{\alpha}\right)\exp\left(-\frac{\lambda}{\alpha}-1\right)

The second factor does not depend on aa and is merely a normalization constant. So the optimal policy is proportional to exp⁡(Q(s,a)/α)\exp\left(Q(s,a)/\alpha\right)—this is exactly the Boltzmann distribution (Boltzmann distribution): the higher QQ is, the larger the probability of the action, and the larger α\alpha is, the flatter (more random) the distribution. This is where the name “soft max” comes from.

Step three: substitute back to obtain a closed form for VV. Substituting π∝exp⁡(Q/α)\pi\propto\exp(Q/\alpha) into the definition of VV, with normalization constant ∑aexp⁡(Q(s,a)/α)\sum_{a}\exp(Q(s,a)/\alpha), gives

V(s)=αlog⁡∑aexp⁡(Q(s,a)α)V(s)=\alpha\log\sum_{a}\exp\left(\frac{Q(s,a)}{\alpha}\right)

For continuous actions the sum becomes an integral:

V(s)=αlog⁡∫Aexp⁡(Q(s,a)α)daV(s)=\alpha\log\int_{\mathcal{A}}\exp\left(\frac{Q(s,a)}{\alpha}\right)\mathrm{d}a

This expression is a smooth version of max⁡aQ(s,a)\max_a Q(s,a): as α→0\alpha\to0 it degenerates to max⁡aQ(s,a)\max_a Q(s,a) (a limit property of log-sum-exp), and the larger α\alpha is, the closer it is to “the average”. It is also the basis on which the “soft Q-learning” target in SAC holds—but note that in practice we do not compute this integral (it cannot be integrated over continuous actions); instead we estimate it by sampling from the current policy:

V(s)≈Ea∼π[Q(s,a)−αlog⁡π(a∣s)]V(s)\approx\mathbb{E}_{a\sim\pi}\left[Q(s,a)-\alpha\log\pi(a\mid s)\right]

Step four: why the entropy in the objective must be discounted. Without the γt\gamma^t, the entropy term over an infinite sum diverges (a positive number is added at every step) and the objective does not exist. With discounting, the total weight of the entropy is bounded by 1/(1−γ)1/(1-\gamma), of the same order as the return, so the objective is bounded and coincides with the classical return at α=0\alpha=0.

Step five: convergence of soft policy iteration. Alternating “soft policy evaluation” (repeatedly applying the soft Bellman backup) with “soft policy improvement” (updating the policy to the Boltzmann distribution of the current QQ) gives soft policy iteration (soft policy iteration). It is isomorphic to classical policy iteration: both the contraction property of the evaluation operator and the improvement theorem carry over, so it converges to the optimal policy for the maximum entropy objective. SAC’s engineering version replaces this alternation with “two networks + gradient descent”.

16.3 Three losses: Critic, Actor, and temperature

SAC’s training consists of three losses; none of them can be omitted:

(1) The Critic loss (soft Q-learning). The target is built with the soft Bellman backup, and the two Critics regress separately (double Q taking the min⁡\min, the same idea as TD3):

y=r+γ(1−d)(min⁡j∈{1,2}Qwj′(s′,a~′)−αlog⁡πθ(a~′∣s′)),a~′∼πθ(⋅∣s′)y=r+\gamma(1-d)\left(\min_{j\in\{1,2\}}Q_{w'_j}(s',\tilde a')-\alpha\log\pi_\theta(\tilde a'\mid s')\right),\qquad \tilde a'\sim\pi_\theta(\cdot\mid s') LQ(wi)=E(s,a,r,s′,d)∼D[(Qwi(s,a)−y)2],i=1,2L_Q(w_i)=\mathbb{E}_{(s,a,r,s',d)\sim D}\left[\left(Q_{w_i}(s,a)-y\right)^2\right],\quad i=1,2

Note two details: ① the action a~′\tilde a' in the target is sampled from the current policy πθ\pi_\theta, not from a target policy (SAC v2 removed the policy target network, see 16.6); ② the entropy term subtracted in the target uses the current policy’s log⁡πθ(a~′∣s′)\log\pi_\theta(\tilde a'\mid s'), and the whole thing is computed under no_grad.

(2) The Actor loss (maximizing “Q minus entropy cost”). The Actor maximizes Ea∼πθ[Q(s,a)−αlog⁡πθ(a∣s)]\mathbb{E}_{a\sim\pi_\theta}\left[Q(s,a)-\alpha\log\pi_\theta(a\mid s)\right], written as a minimization:

Lπ(θ)=Es∼D, ϵ∼N(0,I)[αlog⁡πθ(a~∣s)−min⁡j∈{1,2}Qwj(s,a~)],a~=tanh⁡(μθ(s)+σθ(s)⊙ϵ)L_\pi(\theta)=\mathbb{E}_{s\sim D,\ \epsilon\sim\mathcal{N}(0,I)}\left[\alpha\log\pi_\theta(\tilde a\mid s)-\min_{j\in\{1,2\}}Q_{w_j}(s,\tilde a)\right],\qquad \tilde a=\tanh\left(\mu_\theta(s)+\sigma_\theta(s)\odot\epsilon\right)

The directions of the two terms must be distinguished: −min⁡jQ-\min_j Q pushes the action toward high-value regions; +αlog⁡π+\alpha\log\pi penalizes “being too certain” (log⁡π\log\pi close to 0 gives a small penalty, but when the policy shrinks to a single point the entropy is small and the entropy benefit in the objective is also small—the balance point of the two terms is exactly the Boltzmann distribution). Here α\alpha must be treated as a constant during backpropagation (it does not participate in the derivative with respect to θ\theta), otherwise the temperature is dragged along as well.

(3) The temperature loss (automatic adjustment of α\alpha). The target entropy Hˉ\bar{\mathcal{H}} is usually taken as −∣A∣-|\mathcal{A}| (the negative of the action dimension), and the loss is written as

L(α)=Ea∼πθ[−α(log⁡πθ(a∣s)+Hˉ)]L(\alpha)=\mathbb{E}_{a\sim\pi_\theta}\left[-\alpha\left(\log\pi_\theta(a\mid s)+\bar{\mathcal{H}}\right)\right]

Its role is intuitive: writing the policy entropy as Hπ=−E[log⁡πθ]\mathcal{H}_\pi=-\mathbb{E}[\log\pi_\theta], the gradient of L(α)L(\alpha) with respect to α\alpha is Hπ−Hˉ\mathcal{H}_\pi-\bar{\mathcal{H}}. When the policy is more deterministic than the target entropy (Hπ<Hˉ\mathcal{H}_\pi<\bar{\mathcal{H}}), the gradient is negative, α\alpha increases and the policy becomes more random; when it is more random than the target entropy (Hπ>Hˉ\mathcal{H}_\pi>\bar{\mathcal{H}}), the gradient is positive, α\alpha decreases and the policy tightens. So “exploration strength” is no longer tuned by hand; it tracks the target entropy automatically.

Derivation 30: how the gradients of the three losses flow, and why $\alpha$ must be a constant in the Actor term

Step one: the gradient of the Critic loss lies only on the prediction term. The whole target yy has its gradient cut off, so

∇wiLQ(wi)=−2N∑j=1N(yj−Qwi(sj,aj))∇wiQwi(sj,aj),i=1,2\nabla_{w_i}L_Q(w_i)=-\frac{2}{N}\sum_{j=1}^{N}\left(y_j-Q_{w_i}(s_j,a_j)\right)\nabla_{w_i}Q_{w_i}(s_j,a_j),\qquad i=1,2

Note that min⁡j\min_j appears only inside yy and has already been cut off, so it does not affect the shape of the gradient: each of the two Critics is pulled toward the same label yy. This is consistent with the reasoning in 15.2—min⁡\min is a device for “constructing the label”, not a device for “training the two networks”.

Step two: the gradient of the Actor loss has two paths, which must be examined separately. Write the Actor loss as

Lπ(θ)=Es,ϵ[αlog⁡πθ(a~∣s)−min⁡jQwj(s,a~)],a~=tanh⁡(u),u=μθ(s)+σθ(s)⊙ϵL_\pi(\theta)=\mathbb{E}_{s,\epsilon}\left[\alpha\log\pi_\theta(\tilde a\mid s)-\min_{j}Q_{w_j}(s,\tilde a)\right],\qquad \tilde a=\tanh\left(u\right),\quad u=\mu_\theta(s)+\sigma_\theta(s)\odot\epsilon

Differentiating with respect to θ\theta gives

∇θLπ=α E[∇θlog⁡πθ(a~∣s)]⏟entropy term: direct path−E[(∇θa~)⊤∇amin⁡jQwj(s,a)∣a=a~]⏟value term: path through the action\nabla_\theta L_\pi=\underbrace{\alpha\,\mathbb{E}\left[\nabla_\theta\log\pi_\theta(\tilde a\mid s)\right]}_{\text{entropy term: direct path}}-\underbrace{\mathbb{E}\left[\left(\nabla_\theta\tilde a\right)^{\top}\nabla_a\min_jQ_{w_j}(s,a)\big|_{a=\tilde a}\right]}_{\text{value term: path through the action}}

The two paths have different origins:

  • In the entropy term, log⁡πθ(a~∣s)\log\pi_\theta(\tilde a\mid s) explicitly contains θ\theta (the Gaussian density contains μθ,σθ\mu_\theta,\sigma_\theta, plus the Jacobian correction of tanh⁡\tanh), so it is differentiated directly with respect to θ\theta without passing through the action.
  • In the value term, QQ has no explicit dependence on θ\theta and can only pass through a~\tilde a: ∇θa~=diag(1−tanh⁡2u)(∇θμθ+ϵ⊙∇θσθ)\nabla_\theta\tilde a=\mathrm{diag}\left(1-\tanh^2u\right)\left(\nabla_\theta\mu_\theta+\epsilon\odot\nabla_\theta\sigma_\theta\right). This is the “path gradient”, and it is also the source of SAC’s lower variance compared with a likelihood-ratio estimate (ϵ\epsilon is an exogenous random number, and the gradient does not depend on it).

Step three: the direction of the entropy term is “increase the entropy”. αlog⁡π\alpha\log\pi is minimized, and log⁡π\log\pi is a probability density and is usually negative on its support; minimizing αlog⁡π\alpha\log\pi means making log⁡π\log\pi more negative, i.e., lowering the density at the sampled point and spreading the probability mass out, so the entropy rises. The larger α\alpha is, the more dominant this term and the more random the policy—consistent with the intuition that ”α\alpha is the temperature”.

Step four: why α\alpha in the Actor term must be a constant. If α\alpha were also allowed to participate in the derivative with respect to θ\theta, α\alpha would be pushed down along the direction of “minimizing αlog⁡π\alpha\log\pi” (because when log⁡π<0\log\pi<0 the objective decreases as α\alpha increases), and the “temperature” would become an adjustable knob for the Actor’s loss, the entropy constraint would fail, and it would ultimately degenerate to ordinary policy gradient with α→0\alpha\to0. In implementation this is alpha.detach(); at the same time α\alpha in the Critic target is also a constant (the target as a whole is under no_grad), and α\alpha is an optimized variable only in the temperature loss.

Step five: the gradient of the temperature loss with respect to log⁡α\log\alpha. Parameterizing with β=log⁡α\beta=\log\alpha and α=eβ\alpha=e^{\beta} gives

∇βL(α)=∂L∂α⋅∂α∂β=−E[log⁡πθ(a∣s)+Hˉ]⋅eβ=α(Hπ−Hˉ)\nabla_\beta L(\alpha)=\frac{\partial L}{\partial\alpha}\cdot\frac{\partial\alpha}{\partial\beta}=-\mathbb{E}\left[\log\pi_\theta(a\mid s)+\bar{\mathcal{H}}\right]\cdot e^{\beta}=\alpha\left(\mathcal{H}_\pi-\bar{\mathcal{H}}\right)

where log⁡πθ\log\pi_\theta has already been cut off (logp.detach()), so the gradient flows only to α\alpha. The log⁡\log parameterization has three advantages: α>0\alpha>0 is automatically satisfied; the gradient carries a factor α\alpha, which is equivalent to stepping on a “relative change” scale (a large absolute step when α\alpha is large, a small one when it is small), so it does not diverge because of magnitude differences; and α=1\alpha=1 corresponds to β=0\beta=0, a neutral initial value.

Step six: why the magnitudes of the three losses interfere with each other. The Critic term is a squared error (magnitude δ2\delta^2), the Actor term is a linear combination of QQ and αlog⁡π\alpha\log\pi (magnitude ∣Q∣|Q|), and the temperature term is α\alpha multiplied by a logarithm (magnitude ∣αlog⁡π∣|\alpha\log\pi|). The three magnitudes differ, yet they are often given the same learning rate 3×10−43\times10^{-4}—this is the common reason why “SAC trains unstably under some reward scales”. The robust approach is to normalize the rewards first, so that ∣Q∣|Q| and δ\delta fall into comparable ranges, and then use a uniform learning rate.

16.4 The reparameterization trick and the Jacobian correction of tanh

SAC’s policy network outputs the mean and standard deviation of a Gaussian, and the action is obtained by reparameterization (reparameterization):

u=μθ(s)+σθ(s)⊙ϵ,ϵ∼N(0,I);a=tanh⁡(u)u=\mu_\theta(s)+\sigma_\theta(s)\odot\epsilon,\quad \epsilon\sim\mathcal{N}(0,I);\qquad a=\tanh(u)

Why reparameterize? If one sampled directly from N(μ,σ)\mathcal{N}(\mu,\sigma) and then computed the gradient, the sampling operation itself would not be differentiable and the gradient could not be backpropagated to μ,σ\mu,\sigma. Reparameterization “moves” the randomness onto ϵ\epsilon, which is independent of the parameters, so aa becomes a deterministic differentiable function of θ\theta and the gradient can pass through the sampling point. This is the “pathwise gradient” (pathwise gradient), whose variance is far smaller than that of the ∇log⁡π\nabla\log\pi-style likelihood-ratio estimate.

Derivation 31: why $\log\pi(a\mid s)$ must subtract a term $\log\left(1-\tanh^2 u_i\right)$

Step one: the density formula for a change of variables. If u∼pU(u)u\sim p_U(u), a=f(u)a=f(u), and ff is invertible, then

pA(a)=pU(f−1(a))∣det⁡∂f−1(a)∂a∣p_A(a)=p_U\left(f^{-1}(a)\right)\left|\det\frac{\partial f^{-1}(a)}{\partial a}\right|

Taking logarithms:

log⁡pA(a)=log⁡pU(u)−log⁡∣det⁡∂f(u)∂u∣\log p_A(a)=\log p_U(u)-\log\left|\det\frac{\partial f(u)}{\partial u}\right|

Step two: the Jacobian of tanh⁡\tanh is diagonal, dimension by dimension. Since ai=tanh⁡(ui)a_i=\tanh(u_i),

∂ai∂uj=(1−tanh⁡2(ui))δij ⟹ log⁡∣det⁡J∣=∑i=1∣A∣log⁡(1−tanh⁡2(ui))\frac{\partial a_i}{\partial u_j}=\left(1-\tanh^2(u_i)\right)\delta_{ij} \ \Longrightarrow\ \log\left|\det J\right|=\sum_{i=1}^{|\mathcal{A}|}\log\left(1-\tanh^2(u_i)\right)

Therefore

log⁡πθ(a∣s)=log⁡N(u;μθ(s),σθ2(s))−∑i=1∣A∣log⁡(1−tanh⁡2(ui))\log\pi_\theta(a\mid s)=\log\mathcal{N}\left(u;\mu_\theta(s),\sigma_\theta^2(s)\right)-\sum_{i=1}^{|\mathcal{A}|}\log\left(1-\tanh^2(u_i)\right)

That is:

log⁡πθ(a∣s)=−∑i[(ui−μi)22σi2+log⁡σi+12log⁡2π]−∑ilog⁡(1−tanh⁡2(ui))\log\pi_\theta(a\mid s)=-\sum_{i}\left[\frac{\left(u_i-\mu_i\right)^2}{2\sigma_i^2}+\log\sigma_i+\frac{1}{2}\log 2\pi\right]-\sum_{i}\log\left(1-\tanh^2(u_i)\right)

Step three: what happens if this term is not subtracted. tanh⁡\tanh compresses the whole real line into (−1,1)(-1,1), so an action near the boundary corresponds to infinitely many uu, and the probability density is “squeezed”. Not correcting for this is equivalent to using the Gaussian density in uu-space as the density in aa-space: the entropy is systematically overestimated (especially near the boundary), and the Actor mistakenly believes it is “very random” while in fact it has saturated at the boundary—the typical symptom is that the action sticks at ±1\pm1 for a long time and training does not move. In implementation this term is often written in an equivalent numerically stable form (using log1p(-tanh(u)**2) on uu, or directly 2*(log(2) - u - softplus(-2*u))).

16.5 Automatic adjustment of the temperature α\alpha

Why automatic adjustment is needed: hand-tuning α\alpha is extremely sensitive. For tasks with different reward magnitudes, the optimal α\alpha differs by several orders of magnitude; and α\alpha affects both the exploration strength and the final performance. SAC v1 treated it as a fixed hyperparameter; SAC v2 changed to “treat the target entropy as the hyperparameter and let α\alpha solve for itself”.

The line of reasoning: treat α\alpha as an optimization variable as well, and solve the constrained problem

min⁡α Ea∼πθ[−α(log⁡πθ(a∣s)+Hˉ)]\min_{\alpha}\ \mathbb{E}_{a\sim\pi_\theta}\left[-\alpha\left(\log\pi_\theta(a\mid s)+\bar{\mathcal{H}}\right)\right]

Differentiating with respect to α\alpha gives

∂L∂α=−E[log⁡πθ(a∣s)]−Hˉ=Hπ−Hˉ\frac{\partial L}{\partial\alpha}=-\mathbb{E}\left[\log\pi_\theta(a\mid s)\right]-\bar{\mathcal{H}}=\mathcal{H}_\pi-\bar{\mathcal{H}}

The direction of gradient descent is therefore:

  • if the policy entropy Hπ=−E[log⁡π]\mathcal{H}_\pi=-\mathbb{E}[\log\pi] is greater than the target entropy Hˉ\bar{\mathcal{H}} (the policy is too random), the gradient is positive → α\alpha decreases → the weight of the entropy term shrinks → the policy tightens;
  • if Hπ\mathcal{H}_\pi is less than Hˉ\bar{\mathcal{H}} (the policy is too deterministic), the gradient is negative → α\alpha increases → the weight of the entropy term grows → the policy becomes more random.

In other words, α\alpha pulls the policy entropy toward the target entropy Hˉ\bar{\mathcal{H}}. The default Hˉ=−∣A∣\bar{\mathcal{H}}=-|\mathcal{A}| is an empirical rule validated by a large number of experiments (the intuition being that each action dimension contributes about 1 nat of uncertainty). In practice α\alpha is often parameterized as ”log⁡α\log\alpha + exponential mapping” to guarantee it is always positive, and L(α)L(\alpha) is given its own Adam optimizer.

One easy mistake: α\alpha appears in three different identities across the three losses—in the Actor loss it is a constant (detached, not participating in the derivative with respect to θ\theta); in the Critic target it is also a constant; only in the temperature loss is it an optimized variable. Mixing up the three gives α\alpha a pathological dynamics of “racing against itself”.

Derivation 32: which constraint $\alpha$ is solved from (Lagrangian duality and the envelope theorem)

Step one: write “the target entropy” as a constraint, and α\alpha is its multiplier. Maximum entropy policy optimization can be written as a constrained problem:

max⁡π Ea∼π[Q(s,a)]s.t.Ea∼π[−log⁡π(a∣s)]≥Hˉ\max_{\pi}\ \mathbb{E}_{a\sim\pi}\left[Q(s,a)\right]\quad\mathrm{s.t.}\quad\mathbb{E}_{a\sim\pi}\left[-\log\pi(a\mid s)\right]\ge\bar{\mathcal{H}}

The Lagrangian is

L(π,α)=Ea∼π[Q(s,a)]+α(Ea∼π[−log⁡π(a∣s)]−Hˉ),α≥0\mathcal{L}(\pi,\alpha)=\mathbb{E}_{a\sim\pi}\left[Q(s,a)\right]+\alpha\left(\mathbb{E}_{a\sim\pi}\left[-\log\pi(a\mid s)\right]-\bar{\mathcal{H}}\right),\qquad \alpha\ge0

α\alpha is the Lagrange multiplier of this entropy constraint, and its non-negativity comes from the constraint direction being "≥\ge". This step shows that α\alpha is not a weight set by hand but “the price that must be paid to reach the target entropy”.

Step two: optimizing over π\pi gives the Boltzmann distribution, and the stationary point in α\alpha gives “entropy equals target entropy”. The former is the result of step two in 16.2, π(a∣s)∝exp⁡(Q(s,a)/α)\pi(a\mid s)\propto\exp\left(Q(s,a)/\alpha\right). The latter:

∂L∂α=Ea∼π[−log⁡π(a∣s)]−Hˉ=Hπ−Hˉ=0\frac{\partial\mathcal{L}}{\partial\alpha}=\mathbb{E}_{a\sim\pi}\left[-\log\pi(a\mid s)\right]-\bar{\mathcal{H}}=\mathcal{H}_\pi-\bar{\mathcal{H}}=0

So at the optimum we must have Hπ=Hˉ\mathcal{H}_\pi=\bar{\mathcal{H}}—the optimal temperature is by definition the value that makes the policy entropy land exactly on the target entropy, not “some positive number”.

Step three: the dual problem minimizes over α\alpha, and the gradient can be read off directly with the envelope theorem. Define the dual function g(α)=min⁡πL(π,α)g(\alpha)=\min_\pi\mathcal{L}(\pi,\alpha); the dual problem is min⁡α>0g(α)\min_{\alpha>0}g(\alpha). Because the inner layer has already been optimized over π\pi, ∂L/∂π=0\partial\mathcal{L}/\partial\pi=0, hence

dgdα=∂L∂α∣π=πα=Hπα−Hˉ\frac{\mathrm{d}g}{\mathrm{d}\alpha}=\frac{\partial\mathcal{L}}{\partial\alpha}\Big|_{\pi=\pi_\alpha}=\mathcal{H}_{\pi_\alpha}-\bar{\mathcal{H}}

This is the envelope theorem (envelope theorem): when taking the total derivative one need not expand how π\pi changes with α\alpha, because the coefficient of that term is exactly the zero gradient of “the inner layer already optimal”. So the direction of α\alpha‘s gradient descent is entirely determined by “the difference between the current entropy and the target entropy”: if the entropy is too large, α\alpha decreases; if too small, α\alpha increases.

Step four: SAC v2’s loss is exactly this dual function. Expanding L(α)L(\alpha):

L(α)=E[−α(log⁡πθ(a∣s)+Hˉ)]=−α(E[log⁡πθ]+Hˉ)=α(Hπ−Hˉ)=g(α)L(\alpha)=\mathbb{E}\left[-\alpha\left(\log\pi_\theta(a\mid s)+\bar{\mathcal{H}}\right)\right]=-\alpha\left(\mathbb{E}[\log\pi_\theta]+\bar{\mathcal{H}}\right)=\alpha\left(\mathcal{H}_\pi-\bar{\mathcal{H}}\right)=g(\alpha)

So “minimizing L(α)L(\alpha)” and “solving the dual problem” are the same thing. Note that in implementation log⁡πθ\log\pi_\theta must be detached: this precisely removes the term ”π\pi changes with α\alpha”, which is equivalent to enforcing the envelope theorem. With detach, ∇αL=Hπ−Hˉ\nabla_\alpha L=\mathcal{H}_\pi-\bar{\mathcal{H}}; without detach there is an extra term α ∂Hπ/∂α\alpha\,\partial\mathcal{H}_\pi/\partial\alpha, the minimum of L(α)L(\alpha) is no longer “entropy equals target entropy”, and α\alpha converges to a value that deviates from the target.

Step five: the properties of Hˉ=−∣A∣\bar{\mathcal{H}}=-|\mathcal{A}|. This is an empirical rule rather than a derived result: it implicitly assumes “actions are normalized and the reasonable uncertainty of each dimension is of the order of 1 nat”, so the target entropy is taken as “minus one per dimension”, totaling −∣A∣-|\mathcal{A}|. It must be changed when the action dimension changes; and when the reward is rescaled substantially, even if Hˉ\bar{\mathcal{H}} stays fixed the optimal α\alpha changes markedly (because the magnitude of QQ changes, and with it the ratio between the entropy term and the reward term).

Step six: why α\alpha needs its own learning rate, usually smaller than the Critic’s. α\alpha appears in the Critic’s target, so as soon as α\alpha moves, the target shifts as a whole and QQ must chase it again; then as QQ changes the entropy changes again and α\alpha moves again—this is a closed loop. The gain of the loop is proportional to α\alpha‘s learning rate, so it must be small enough (often 3×10−43\times10^{-4} or less), with optimizer state separate from the Actor and Critic, so that momentum does not accumulate into oscillation within the loop.

16.6 Complete pseudocode (SAC v2)

Input: state dimension n_s, action dimension n_a, action range [-1, 1] (physical limits rescaled in an outer layer)
Hyperparameters: γ=0.99, τ=0.005, batch N=256, replay capacity 1e6,
                 learning rates α_Q=3e-4, α_π=3e-4, α_α=3e-4,
                 target entropy H_bar = -n_a, warm-up steps T_warm
Initialize: Actor π_θ (outputs the mean μ and the log standard deviation log σ)
            Critics Q_{w1}, Q_{w2} (input concat(s,a))
            target Critics w'_1 ← w_1, w'_2 ← w_2 (note: there is no policy target network)
            log α ← 0 (i.e., α=1), target entropy H_bar
            replay buffer D ← ∅

for t = 1 … T_total:
    # ① Sample: the action is sampled from the policy itself (exploration built in)
    with no_grad:
        μ, log σ = π_θ(s); u = μ + σ ⊙ ε, ε ~ N(0,I)
        a = tanh(u)
    Execute a (if physical limits are needed, do an affine scaling at the execution layer)
    Observe r, s', d; store (s, a, r, s', d) into D
    if t < T_warm: continue

    # ② Draw a batch
    Draw N transitions (s_i, a_i, r_i, s'_i, d_i) uniformly from D

    # ③ Build the soft target (all under no_grad)
    with no_grad:
        μ', log σ' = π_θ(s'_i); u' = μ' + σ' ⊙ ε'; ã' = tanh(u')
        log π' = log N(u'; μ', σ') - Σ_dim log(1 - tanh²(u'))      # includes the Jacobian correction
        q_min' = min(Q_{w'_1}(s'_i, ã'), Q_{w'_2}(s'_i, ã'))
        y_i = r_i + γ (1 - d_i) · (q_min' - α ⊙ log π')

    # ④ Both Critics regress onto the soft target
    L_Q = Σ_{i=1,2} (1/N) Σ_j (Q_{w_i}(s_j, a_j) - y_j)²
    w_1 ← w_1 - α_Q ∇_{w_1} L_Q ;  w_2 ← w_2 - α_Q ∇_{w_2} L_Q

    # ⑤ Actor: maximize Q minus the entropy cost (α treated as a constant)
    u = μ_θ(s) + σ_θ(s) ⊙ ε; a_tilde = tanh(u)
    log π = log N(u; μ_θ, σ_θ) - Σ_dim log(1 - tanh²(u))
    L_π = (1/N) Σ [ α · log π - min(Q_{w1}(s, a_tilde), Q_{w2}(s, a_tilde)) ]
    θ ← θ - α_π ∇_θ L_π        # freeze the parameters of both Critics; only borrow their gradients

    # ⑥ Automatic temperature adjustment (differentiate with respect to log α, guaranteeing α=exp(log α)>0)
    L_α = (1/N) Σ [ -exp(log α) · (log π.detach() + H_bar) ]
    log α ← log α - α_α ∇_{log α} L_α

    # ⑦ Soft-update the two target Critics
    w'_i ← τ w_i + (1 - τ) w'_i, i = 1,2

16.7 Section-by-section commentary

① Sampling needs no attached noise. What the Actor outputs is itself a distribution, and sampling from it is exploration. This brings a subtle implementation difference: two consecutive steps in the same state may sample different actions, and this is normal and expected; in TD3 the difference in actions comes only from the noise. This is also why the action SAC stores in the replay buffer is “a sample drawn from the policy distribution”, which naturally covers the support of the policy, so the Q the Critic learns is trustworthy for actions near the policy.

② The warm-up period is still recommended. Although the target has no strong upward bias introduced by max⁡\max, early on the Critic is entirely randomly initialized and bootstrapping will diverge just the same. Warm up on the order of 1e4 steps, filling the replay buffer with random actions.

③ The soft target is “Q minus entropy”, not “Q plus entropy”. It is extremely easy to get the sign wrong: in the definition of VV it is Q−αlog⁡πQ-\alpha\log\pi (and since log⁡π<0\log\pi<0, this is adding a positive number). The symptom of the wrong sign is that performance is acceptable early in training and the policy collapses later—the Critic target is systematically pushed down or up, conflicting with the direction the Actor is optimizing.

④ Where the double Q takes the min⁡\min. For the same reason as TD3, to suppress overestimation. Note that the min⁡\min acts only when constructing the target; when training the two Critics, each regresses separately. A common variant uses the min⁡\min only in the Actor loss while the target uses the average; different pairings markedly affect the learning speed.

⑤ The target action a~′\tilde a' should come from the “current” policy. The key simplification of SAC v2: the policy target network is no longer maintained, and both the action and log⁡π\log\pi in the target use the current πθ\pi_\theta. This makes the stability that was provided by “the target policy lagging” compensated by ”α\alpha and the double Q”—the cost is slightly noisier targets, and the benefit is one fewer network that needs soft updates and one fewer set of hyperparameters. SAC v1 kept a policy target network; on most tasks the difference between the two is small.

⑥ The Actor optimizes αlog⁡π−min⁡Q\alpha\log\pi-\min Q, and the two terms are not symmetric. The gradient of −min⁡Q-\min Q is backpropagated through ∂a~/∂θ\partial\tilde a/\partial\theta (the path gradient), while the gradient of αlog⁡π\alpha\log\pi goes directly to θ\theta (because it explicitly depends on μθ,σθ\mu_\theta,\sigma_\theta and the Jacobian term). At the same time the parameters of both Critics must be frozen: without freezing, the Critic would be directly modified by the objective “maximize Q”, which amounts to grading its own exam.

⑦ The temperature is parameterized by log⁡α\log\alpha. Gradient descent directly on α\alpha may overshoot zero in one step and become negative, making “the entropy reward work in reverse”. log⁡α\log\alpha guarantees positivity, at the cost that the learning rate must be reinterpreted on the scale of α\alpha (when α=1\alpha=1, log⁡α=0\log\alpha=0).

⑧ The soft update touches only the two target Critics. SAC v2 has no policy target network, so the soft update involves only the two Critics—this is often written wrong by implementers migrating from TD3/DDPG (either writing an extra theta_target that is never used, or conversely forgetting to update the Critic targets).

⑨ The termination mask is multiplied in only one place. Exactly the same as TD3: on true termination y=ry=r; on truncation, bootstrapping still happens. Note that SAC’s termination mask acts on both “the Q term” and “the entropy term”—both hang on the bootstrapping term, so one (1−d)(1-d) is enough; but if the entropy term is written outside the bootstrapping term (e.g., as (1−d)Qmin⁡−αlog⁡π(1-d)Q_{\min}-\alpha\log\pi), then on truncation the entropy term is wrongly zeroed.

16.8 Gradient flow and detach checklist

SAC’s three losses reference one another, so the gradient flow is easier to get wrong than TD3’s. The principle is: both “someone else’s parameters” and “quantities used as labels” must be cut off; only the Q value itself in the Actor loss must retain its gradient with respect to the action.

QuantityAppears inCut off?Consequence of not cutting it off
yiy_i (including min⁡Q′\min Q' and log⁡π′\log\pi')Critic lossRequired (no_grad)The target drifts with the parameters and the Critic learns nothing
a~′\tilde a', log⁡π′\log\pi'Inside yiy_iRequiredThe target networks/policy are driven backward by the objective
log π (the second factor of the Actor term)Temperature lossMust detachThe gradient of α\alpha would also modify the Actor, and the two pull against each other
α\alphaActor lossTreated as a constant (detach)The temperature is pushed down directly by the “maximize entropy” objective and loses its regulatory meaning
min⁡jQwj(s,a~)\min_j Q_{w_j}(s,\tilde a)Actor lossMust not detach (with respect to a~\tilde a)The Actor gets no gradient at all
The parameters of both CriticsActor lossMust be frozen with requires_grad=FalseThe Critics are polluted by the Actor’s objective

Side-by-side correct and wrong versions (PyTorch):

# Correct: the soft target is built under no_grad, including the tanh Jacobian correction
with torch.no_grad():
    mu_t, log_std_t = actor(s_next)
    u_t = mu_t + log_std_t.exp() * torch.randn_like(mu_t)
    a_t = torch.tanh(u_t)
    logp_t = gaussian_logp(u_t, mu_t, log_std_t) - torch.log(1 - a_t.pow(2) + 1e-6).sum(-1, keepdim=True)
    q_t = torch.min(q1_target(s_next, a_t), q2_target(s_next, a_t))
    y = r + gamma * (1.0 - d) * (q_t - alpha * logp_t)

loss_q = F.mse_loss(q1(s, a), y) + F.mse_loss(q2(s, a), y)

# Correct: the Actor loss uses the path gradient; α is a constant; the Critic parameters are frozen
mu, log_std = actor(s)
u = mu + log_std.exp() * torch.randn_like(mu)
a_tilde = torch.tanh(u)
logp = gaussian_logp(u, mu, log_std) - torch.log(1 - a_tilde.pow(2) + 1e-6).sum(-1, keepdim=True)
for p in list(q1.parameters()) + list(q2.parameters()):
    p.requires_grad_(False)
loss_pi = (alpha.detach() * logp - torch.min(q1(s, a_tilde), q2(s, a_tilde))).mean()
loss_pi.backward()
for p in list(q1.parameters()) + list(q2.parameters()):
    p.requires_grad_(True)

# Correct: the temperature loss cuts off logp
loss_alpha = -(log_alpha.exp() * (logp.detach() + target_entropy)).mean()

# Wrong: the Gaussian density forgot the Jacobian term → the entropy is overestimated and the action sticks to the boundary
logp = gaussian_logp(u, mu, log_std)     # missing -log(1 - tanh²u)

# Wrong: the sign of the entropy term in the soft target is reversed (it should be Q - α log π)
y = r + gamma * (1.0 - d) * (q_t + alpha * logp_t)

16.9 Pitfall checklist

PitfallSymptomCorrect practice
Forgetting the tanh Jacobian correctionEntropy overestimated, action stuck at ±1\pm1 for a long time, learning stallsSubtract ∑log⁡(1−tanh⁡2u)\sum\log(1-\tanh^2u) in log⁡π\log\pi
The sign of the entropy term in the soft target is reversedThe policy collapses late in training, performance rises and then collapsesThe target is Qmin⁡−αlog⁡πQ_{\min}-\alpha\log\pi
α\alpha enters the Actor loss without detachα\alpha is pulled toward 0 by “maximize entropy” and loses its regulationalpha.detach() in the Actor loss
log π is not cut off in the temperature lossα\alpha and the Actor pull against each other and the entropy runs out of controllogp.detach() in the temperature loss
α\alpha is parameterized linearlyA negative temperature appears during training and the entropy term works in reverseUse log_alpha + exp
The target entropy is set too large (e.g., $-2\mathcal{A}$)
The Critic uses the average instead of the min⁡\min (or the two are mixed)Overestimation reappears, or learning is too slowTake the min⁡\min in the target and regress separately in training
The action in the Critic input is not “the current action”Q learns “the state value” and the Actor gradient becomes invalidThe Critic must take the concatenation (s,a)(s,a)
Forgetting to freeze the Critic parametersThe Critic is directly modified by the Actor’s objective and Q divergesFreeze the parameters, borrow only the gradient
Computing log⁡π\log\pi after tanh when sampling from the policyThe density conventions are inconsistent and the entropy estimate is biasedCompute the Gaussian density uniformly in uu-space, then apply the Jacobian correction
Still sampling from the policy at deploymentThe action jitters in the same state and is not reproducibleDeploy with tanh⁡(μ)\tanh(\mu) (the mean action), or fix the random seed
Treating truncation as terminationA dip in value appears at the time boundaryterminated=1, truncated=0 (same as TD3)

16.10 Comparison with PPO / DDPG / TD3 and scope of application

DimensionPPODDPGTD3SAC
Data sourceOn-policy (large parallel batches)Off-policy + replayOff-policy + replayOff-policy + replay
Policy formStochastic (Gaussian/categorical)Deterministic + attached noiseDeterministic + attached noiseStochastic (Gaussian compressed through tanh)
Exploration sourcePolicy distribution + multiple environmentsNoise scale (hand-tuned)Noise scale (hand-tuned)Entropy regularization + automatic α\alpha
Multimodal actionsSupportedNot supportedNot supportedSupported
Suppression of overestimationNot explicitly handledNoneDouble Q taking the min⁡\minDouble Q taking the min⁡\min
ObjectiveClipped returnPure returnPure returnReturn + entropy
Main hyperparameter risksε\varepsilon, number of epochs, KL early stoppingNoise scale, learning-rate ratioSmoothing noise, delay stepsTarget entropy, α\alpha learning rate
Deployment determinismTake the meanNaturally deterministicNaturally deterministicTake the mean
Sample efficiencyLowHighHighHigh
Typical failureToo large a step collapses the policyQ inflated, Actor does not moveSmoothing noise too large, no learningJacobian/sign written wrong, α\alpha out of control

Choose by constraint:

  • Simulation can be parallelized, tasks are diverse, and the goal is “it runs with little tuning” → PPO (see Chapter 11). It needs no replay buffer and is naturally suited to large-scale parallel sampling.
  • Interaction is expensive, data must be reused, the task is unimodal, and the simplest implementation is wanted → TD3 (see Chapter 15). Three patches, one piece of pseudocode, and a deterministic policy at deployment.
  • Interaction is expensive, the task is multimodal or has symmetry ambiguity, automatic adjustment of exploration is desired, and robustness matters → SAC. It is the most stable default answer in continuous control today, at the cost that the three losses and one Jacobian correction must be written correctly.
  • Discrete actions with offline training → the DQN family; the discrete version of SAC (SAC-Discrete) also works, but its benefit is less pronounced than in continuous settings.

Scope of application (SAC): manipulator grasping and fine assembly, multi-finger control of dexterous hands, quadruped gaits, continuous control of vehicles and drones, and robotic tasks that need sim-to-real—whenever “the action is continuous, the environment is stochastic, interaction is expensive, and the optimal action may not be unique”, SAC is usually the least troublesome starting point. Not suitable for: very large-scale parallelism, cases requiring extremely low-latency inference at every step (where PPO + a small network is more cost-effective), and cases that must be strictly deterministic for safety (where a deterministic policy or an extra safety layer should be used instead).

One sentence to remember SAC: write entropy into the objective, and the optimal policy changes from “a point” to “a Boltzmann distribution”, so exploration is built in, multimodality is expressible, and the temperature adjusts itself—it is not a patch on DDPG but a change of the objective function.

The relationship between TD3 and SAC, compressed into one table:

TD3: min⁡iQwi′(s′,a~′) ∣ update the Actor every d stepsSAC: min⁡iQwi′(s′,a~′)−αlog⁡π(a~′∣s′) ∣ update the Actor every step\text{TD3:}\ \min_{i}Q_{w'_i}(s',\tilde a')\ \Big|\ \text{update the Actor every } d \text{ steps} \qquad\text{SAC:}\ \min_{i}Q_{w'_i}(s',\tilde a')-\alpha\log\pi(\tilde a'\mid s')\ \Big|\ \text{update the Actor every step}

The two share “double Q taking the min⁡\min + soft updates + replay”, and diverge only on “whether the target contains entropy” and “whether the policy is stochastic”. The criterion can therefore be extremely simple: if the task’s optimal action is unique and smooth → TD3; if it may not be unique, or automatic exploration is needed → SAC.


17. Algorithm lineage and comparison of key characteristics

17.1 How the methods relate to one another

The algorithm genealogy that takes the Bellman equation as its theoretical foundation can be drawn like this:

Bellman equation (theoretical foundation)
├── DP: model-based, traverses all states, exact solution
├── MC: model-free, episodic, approximates the expectation with the mean of complete returns G_t (first-visit / every-visit)
├── TD: model-free, online, bootstrapping (one-step reward + successor estimate), larger bias, smaller variance
│   ├── Q-learning: TD + off-policy + max, learns a Q table
│   └── DQN: Q-learning + neural network + experience replay + target network (discrete actions)
├── Policy gradient (directly optimizes the policy π_θ)
│   ├── REINFORCE: Monte Carlo style policy gradient (large variance)
│   └── Actor-Critic: policy gradient + value baseline (low variance)
│       ├── A2C: synchronous advantage actor-critic
│       ├── A3C: asynchronous version
│       ├── GAE: advantage estimator (not a standalone algorithm)
│       ├── TRPO: trust region with a hard KL constraint
│       ├── PPO: clipping that approximates the trust region (simple, most commonly used)
│       └── ACER: off-policy + experience replay + Retrace + truncated importance sampling
└── Deterministic policy
    ├── DPG: deterministic policy gradient theorem (theory)
    └── DDPG: DPG + deep network + replay + soft target network (continuous actions)
        ├── TD3: twin critics taking the min + delayed updates + target smoothing (fixes overestimation)
        └── SAC: maximum-entropy objective + double Q + reparameterization + automatic temperature (changes the objective function)

The key to reading this diagram is: horizontally it separates “model-free” from “model-based”, and vertically it separates “value-based methods” from “policy-based methods”. Once you hold the root of the Bellman equation, and then understand the stabilization mechanism of “experience replay + target network”, every algorithm that follows is an addition or subtraction on these two trunks.

17.2 Comparison table of key characteristics

AlgorithmTypeDoes it need a model?
Dynamic programming (DP)Model-based planningYes
Monte Carlo (MC)Value predictionNo
Temporal difference TD(0)Value predictionNo
Q-learningValue controlNo
DQNValue controlNo
REINFORCEPolicy gradientNo
A2CActor-CriticNo
A3CActor-CriticNo
GAEAdvantage estimatorNo
TRPOActor-CriticNo
PPOActor-CriticNo
ACERActor-CriticNo
DPGDeterministic policy gradientNo
DDPGDeterministic policy gradient + deep networkNo
TD3Stability upgrade of DDPG (twin critics, delayed updates, target smoothing)No
SACObjective-function upgrade of DDPG (maximum entropy)No

Note: this table distinguishes the five roles of “value prediction / value control / policy gradient / Actor-Critic / advantage estimator”, and whether the method depends on an environment model. DP is the only method that needs a complete model; everything else belongs to model-free methods.

17.3 Quick selection guide and three frequent pitfalls

Choosing an algorithm by scenario (the fuller six-dimensional comparison and the decision chain are in 19.1 and 19.3 of Chapter 19):

ScenarioFirst choiceReason
Discrete actions, observable states, offline reuse of dataThe DQN family (Double / Dueling / prioritized replay)Off-policy, simple to implement, and samples can be reused repeatedly
Continuous actions (joint angles, torques, velocity commands)SAC or TD3The policy outputs the action directly, so no arg⁡max⁡\arg\max over continuous actions is needed
Large-scale parallel simulation, limited tuning budgetPPOOn-policy + parallelizable sampling + clipped bounds, and the default hyperparameters are already stable enough
A monotonic-improvement guarantee is required for every stepTRPOHard KL constraint + line search, at the price of a second-order solve
The cost of trial and error on real hardware is extremely highModel-based reinforcement learning / world models“Imagine” trial and error inside a learned model; not expanded on in this article

Three frequent pitfalls:

  1. Every place that takes a max⁡\max over an estimate suffers from maximization bias. It is not only DQN: TD3 taking the smaller of two critics, and Double DQN separating “choosing the action” from “estimating the value” with two sets of networks, are both essentially de-biasing the max⁡\max. Whenever you see “take the maximum”, ask: will the estimation noise here be amplified?
  2. Termination and truncation in GAE must be kept separate. True termination must cut off bootstrapping; time-limit truncation must keep bootstrapping; both the δt\delta_t mask and the At+1A_{t+1} mask must be written. Missing the first produces a spurious cliff near the time limit; missing the second lets advantages bleed across episodes (details in 9.4 and 9.5).
  3. The difference between TRPO and PPO is not a choice between “KL” and “clipping”. Both optimize the same trust-region objective: TRPO explicitly solves the hard KL constraint (second-order approximation + conjugate gradient + line search), while PPO approximates it with a first-order objective. PPO’s clipping is a soft constraint and can still be violated in extreme cases, so in practice one should monitor both the approximate KL and the clip fraction, and stop that epoch early when necessary.

18. Summary of key formulas and loop strategies

This section collects the three elements discussed earlier—the “objective policy (what is learned)”, the “core update formula (how it is updated)”, and the “main loop strategy (how to sample and how to iterate)“—for quick lookup. Notation is the same as before: α\alpha learning rate, γ\gamma discount factor, RR reward, VV state value, QQ action value, AA advantage, πθ\pi_\theta stochastic policy, μθ\mu_\theta deterministic policy.

18.1 Value-based methods

AlgorithmObjective policy (what is learned)Core update formula
DP (policy evaluation)State value VπV_\pi of a given policy π\piVk+1(s)=∑aπ(a∣s)∑s′P(s′∣s,a)[R(s,a,s′)+γVk(s′)]V_{k+1}(s)=\sum_a\pi(a\mid s)\sum_{s'}P(s'\mid s,a)[R(s,a,s')+\gamma V_k(s')]
DP (value iteration)Optimal state value V∗V^* (implies the optimal policy π∗\pi^*)Vk+1(s)=max⁡a∑s′P(s′∣s,a)[R(s,a,s′)+γVk(s′)]V_{k+1}(s)=\max_a\sum_{s'}P(s'\mid s,a)[R(s,a,s')+\gamma V_k(s')]
MC (first-visit / every-visit)State value VπV_\pi (approximated by the mean of sampled returns)V(St)←average(Returns(St))V(S_t)\leftarrow\text{average}(\text{Returns}(S_t)), where Returns collects the return GtG_t of each visit
TD(0)State value VπV_\pi (online bootstrapped estimate)V(St)←V(St)+α[Rt+1+γV(St+1)−V(St)]V(S_t)\leftarrow V(S_t)+\alpha[R_{t+1}+\gamma V(S_{t+1})-V(S_t)]
Q-learningOptimal action value Q∗Q^* (the policy takes arg⁡max⁡aQ\arg\max_a Q)Q(S,A)←Q(S,A)+α[R+γmax⁡a′Q(S′,a′)−Q(S,A)]Q(S,A)\leftarrow Q(S,A)+\alpha[R+\gamma\max_{a'}Q(S',a')-Q(S,A)]
DQNOptimal action value Q(s,a;θ)Q(s,a;\theta) (approximated by a neural network)L(θ)=E[(yj−Q(sj,aj;θ))2]L(\theta)=\mathbb{E}[(y_j-Q(s_j,a_j;\theta))^2], yj=rj+γmax⁡a′Q(sj+1,a′;θ−)y_j=r_j+\gamma\max_{a'}Q(s_{j+1},a';\theta^-)

Common loop of the value-based methods: interact and sample → compute the TD target → update the estimate toward the target → (deep version) replay + target network to stabilize training.

18.2 Policy-gradient methods

AlgorithmObjective policy (what is learned)Core update formula
REINFORCEStochastic policy πθ\pi_\theta (maximize the expected return J(θ)J(\theta))θ←θ+αGt∇θlog⁡πθ(at∣st)\theta\leftarrow\theta+\alpha G_t\nabla_\theta\log\pi_\theta(a_t\mid s_t)
A2CStochastic policy + value baselineθ←θ+αAt∇θlog⁡πθ(at∣st)\theta\leftarrow\theta+\alpha A_t\nabla_\theta\log\pi_\theta(a_t\mid s_t), where AtA_t is the nn-step advantage
TRPOStochastic policy (KL trust-region constraint)max⁡θE[rt(θ)At]\max_\theta\mathbb{E}[r_t(\theta)A_t], s.t. E[KL(πold∥πθ)]≤δ\mathbb{E}[\mathrm{KL}(\pi_{\mathrm{old}}\|\pi_\theta)]\le\delta
PPOStochastic policy (clipped surrogate objective that limits the update magnitude)LCLIP=Et[min⁡(rt(θ)At,clip(rt(θ),1−ε,1+ε)At)]L^{\mathrm{CLIP}}=\mathbb{E}_t[\min(r_t(\theta)A_t,\mathrm{clip}(r_t(\theta),1-\varepsilon,1+\varepsilon)A_t)]
ACERStochastic policy (off-policy, truncated importance sampling + Retrace)g=min⁡(ρt,c)At∇log⁡π+(At−min⁡(ρt,c)At)∇log⁡πg=\min(\rho_t,c)A_t\nabla\log\pi+(A_t-\min(\rho_t,c)A_t)\nabla\log\pi; Retrace computes Qtret=rt+γ[ρt+1(Qt+1ret−V(st+1))+V(st+1)]Q^{\mathrm{ret}}_t=r_t+\gamma[\rho_{t+1}(Q^{\mathrm{ret}}_{t+1}-V(s_{t+1}))+V(s_{t+1})]

Common loop of the policy-gradient methods: policy sampling (on-policy) or replay sampling (off-policy) → estimate the return or advantage (GAE as standard equipment) → gradient ascent with ∇log⁡π\nabla\log\pi weighted by the advantage → limit the update magnitude with a trust region (KL / clipping).

18.3 Deterministic-policy methods

AlgorithmObjective policy (what is learned)Core update formula
DPGDeterministic policy μθ\mu_\theta + critic QwQ^wActor: $\theta\leftarrow\theta+\alpha_\theta\nabla_\theta\mu_\theta(s)\cdot\left.\nabla_aQ^w(s,a)\right
DDPGDeterministic policy + target networks + replayy=r+γQw′(s′,μθ′(s′))y=r+\gamma Q^{w'}(s',\mu_{\theta'}(s')); θ′←τθ+(1−τ)θ′\theta'\leftarrow\tau\theta+(1-\tau)\theta', w′←τw+(1−τ)w′w'\leftarrow\tau w+(1-\tau)w'
TD3DDPG + twin critics + delayed updates + target smoothingy=r+γ(1−d)min⁡i=1,2Qwi′(s′,a~′)y=r+\gamma(1-d)\min_{i=1,2}Q^{w'_i}(s',\tilde a'), a~′=clip(μθ′(s′)+clip(ϵ,−c,c),amin⁡,amax⁡)\tilde a'=\mathrm{clip}(\mu_{\theta'}(s')+\mathrm{clip}(\epsilon,-c,c),a_{\min},a_{\max}); the Actor is updated once every d=2d=2 steps
SACMaximum-entropy stochastic policy (double Q + reparameterization + automatic temperature)y=r+γ(1−d)(min⁡i=1,2Qwi′(s′,a~′)−αlog⁡πθ(a~′∣s′))y=r+\gamma(1-d)\left(\min_{i=1,2}Q^{w'_i}(s',\tilde a')-\alpha\log\pi_\theta(\tilde a'\mid s')\right); Lπ=E[αlog⁡πθ(a~∣s)−min⁡iQwi(s,a~)]L_\pi=\mathbb{E}[\alpha\log\pi_\theta(\tilde a\mid s)-\min_i Q^{w_i}(s,\tilde a)], a~=tanh⁡(μθ+σθ⊙ϵ)\tilde a=\tanh(\mu_\theta+\sigma_\theta\odot\epsilon)

18.4 What the three loops have in common

Compress the tables into one sentence each:

  • Value-based: interact and sample → compute the TD target → update toward the target → (deep version) replay + target network;
  • Policy-gradient: sample trajectories → estimate the advantage → gradient ascent → limit the step size with KL / clipping;
  • Deterministic-policy: sample with exploration noise → update the Critic with TD → update the Actor along the action gradient of QQ → softly update the target networks.

Every algorithm answers three questions: what is learned (VV, QQ, the policy, or the advantage), how it is updated (toward which target, with which loss), and how it is sampled (on-policy or off-policy, with or without exploration noise). Answer these three questions clearly and the structure of any new algorithm becomes immediately readable.


19. Summary: Core differences among the algorithms and when to use them

The previous sixteen chapters took each algorithm apart on its own; this chapter presses them back into one table, and then strings them together again along six key divergences and one selection decision chain. If you only have five minutes, read the one-page cheat sheet in 19.5; if you are picking an algorithm for a specific task, start from the decision chain in 19.3.

19.1 One table that makes the differences among all algorithms visible

AlgorithmWhat is learnedData sourceAction spaceKey stabilization meansMain weaknessTypical use case
Dynamic programming (DP)VπV_\pi or V∗V^*Known model, no sampling neededDiscreteNone (exact iteration)Requires the full PP and RR, and states must be enumerablePlanning problems with few states and known transitions (board games, queueing, inventory)
Monte Carlo (MC)VπV_\piOn-policy, requires complete episodesDiscrete or continuousSample mean, first-visitMust wait for the episode to end; large varianceValue prediction with short episodes and controllable return variance
Temporal difference TD(0)VπV_\piOn-policy, online single stepDiscrete or continuousBootstrapping + step sizeLarge bias, sensitive to initializationValue prediction for continuing tasks without termination
Q-learningQ∗Q^*Off-policy, any behavior policyDiscretemax⁡\max target + step sizeTabular dimensionality explosion, maximization biasSmall-scale discrete control, teaching demonstrations
DQNQ∗Q^*Off-policy, experience replayDiscreteExperience replay + target network + termination maskSupports discrete actions only; Q-value overestimationAtari-style discrete control, scheduling and recommendation
REINFORCEπθ\pi_\thetaOn-policy, complete trajectoriesDiscrete or continuousBaseline subtraction (optional)Extremely large variance, lowest sample efficiencyTeaching, minimal continuous-control prototypes
A2C / A3Cπθ\pi_\theta and VϕV_\phiOn-policy, parallel samplingDiscrete or continuousAdvantage baseline + parallel environmentsSensitive to step size; data used only onceParallel simulation environments, quick algorithm validation
GAE (a component, not a standalone algorithm)Advantage estimate A^t\hat{A}_tFollows the host algorithm (usually on-policy)Not involvedλ\lambda trades off bias and varianceTermination and truncation masks are easy to get wrongAdvantage estimation for every Actor-Critic style algorithm
TRPOπθ\pi_\thetaOn-policyDiscrete or continuousHard KL constraint + conjugate gradient + line searchSecond-order solve is expensive; complex implementationSmall and medium networks that need a “no degradation at every step” guarantee
PPOπθ\pi_\theta and VϕV_\phiOn-policy (the same batch is reused for several rounds)Discrete or continuousClipping + GAE + advantage normalization + KL early stoppingThe soft constraint can still be violated; the approximate KL must be monitoredLarge-scale parallel simulation, RLHF (Reinforcement Learning from Human Feedback), robot control
ACERπθ\pi_\theta and QQOff-policy + experience replayDiscrete or continuousRetrace value estimation + truncated importance samplingThe most complex implementation, the most hyperparametersReal hardware or expensive environments where old data must be reused
DPGDeterministic policy μθ\mu_\theta and QwQ^wOff-policyContinuousDeterministic policy + the Critic passing the action gradient backInsufficient exploration, deviates from policy-based methodsAlgorithm prototypes and theoretical validation for continuous control
DDPGμθ\mu_\theta and QwQ^wOff-policy + experience replayContinuousTarget networks + soft updates + action-noise explorationSensitive to hyperparameters, Critic overestimationSingle-task continuous control with moderate state dimension
TD3 (see Chapter 15)Deterministic policy μθ\mu_\theta and Qw1,Qw2Q^{w_1},Q^{w_2}Off-policy + experience replayContinuousTwin critics taking the min⁡\min + delayed policy updates + target policy smoothingExploration still needs external noise; cannot express multimodalitySingle-task continuous control, real-hardware manipulation, scenarios requiring deterministic deployment
SAC (see Chapter 16)Maximum-entropy stochastic policy and Qw1,Qw2Q^{w_1},Q^{w_2}Off-policy + experience replayContinuousTwin critics + entropy regularization + reparameterization + automatic tuning of α\alphaThe three losses and the tanh Jacobian are easy to get wrong; the target entropy must be tunedReal-hardware grasping, assembly, dexterous hands, multimodal continuous control

Three things to notice when reading this table:

  1. “What is learned” determines the applicable action space. Whenever the objective contains an arg⁡max⁡\arg\max over actions (Q-learning, DQN), the actions must be enumerable, so the method is inherently suited only to discrete actions; for continuous actions one must either use a deterministic policy (DPG, DDPG, TD3) or a policy that can be sampled (PPO, SAC).
  2. “Data source” determines sample efficiency. Off-policy methods (Q-learning, DQN, ACER, DDPG, TD3, SAC) can use one piece of data repeatedly and are sample-efficient; on-policy methods (MC, TD, REINFORCE, A2C, TRPO, PPO) essentially use each piece of data once and make up the volume with parallel sampling. PPO’s “multiple epochs” merely reuse the same batch for several gradient steps—the data itself is not kept across iterations—so it is still on-policy.
  3. The “key stabilization means” column is where the real engineering differences among the algorithms lie. The objective functions differ only in a few places; almost all of the remaining implementation complexity is spent on “how to keep training from diverging”: replay buffers decorrelate data, target networks cut the bootstrapping loop, clipping and KL limit the step size, advantage normalization unifies the scale, and twin critics suppress overestimation. When looking at a new algorithm, first find what it added in this column.

19.2 Six key divergences: where exactly do the algorithms differ

(1) Learn the value, or learn the policy

Value-based methods first learn “how many points each action is worth” and then take the arg⁡max⁡\arg\max; policy-based methods output the action distribution directly and rewrite the probabilities by gradient ascent.

Point of divergenceValue-based (Q-learning, DQN)Policy-based (REINFORCE, PPO)
Action selectionExplicit arg⁡max⁡aQ(s,a)\arg\max_a Q(s,a)Sample from πθ(a∣s)\pi_\theta(a\mid s)
Continuous actionsRequires the global maximum over the action space, which is costlyThe network outputs the mean and variance directly, so it is naturally supported
StochasticityThe policy itself can be a deterministic greedy ruleThe policy is stochastic by construction, so exploration is more natural
Data efficiencyCan be off-policy and can replayUsually on-policy, with low data utilization
Convergence propertiesThe target is fixed (Q∗Q^*), but it suffers from maximization biasThe target drifts with the policy and the gradient variance is large

Criterion: if actions can be enumerated and you need to reuse old data, go value-based; if actions are continuous, or you need a naturally stochastic policy, go policy-based.

(2) On-policy, or off-policy

On-policy requires the behavior policy to be the same as the target policy; off-policy allows data collected by another policy to be used to evaluate the target policy.

  • The benefit of off-policy is sample reuse: one transition can go into the replay buffer and be sampled repeatedly, improving sample efficiency by an order of magnitude; the price is distribution shift, which must be corrected with importance sampling, and the variance of the importance-sampling ratio grows exponentially with trajectory length—this is exactly why ACER needs Retrace and truncation.
  • On-policy has no distribution-shift problem, but each piece of data can be used only once (PPO’s multiple epochs are “several gradient steps on the same batch”, not reuse across iterations); the price is low sample efficiency, which must be compensated by large-scale parallel environments.

Criterion: if real hardware or simulation is expensive → off-policy; if simulation is cheap and thousands of environments can run in parallel → on-policy (PPO is the default answer).

(3) Stochastic policy, or deterministic policy

DimensionStochastic policy πθ(a∣s)\pi_\theta(a\mid s)Deterministic policy μθ(s)\mu_\theta(s)
Source of explorationThe policy distribution itself (entropy, sampling)Action noise must be attached externally (DDPG uses Ornstein–Uhlenbeck or Gaussian noise)
Multimodal actionsCan express a bimodal distribution such as “either left or right”A single-point output; when faced with two peaks it averages them into an invalid action “right in the middle”
Gradient pathTake the gradient with respect to log⁡π\log\pi, independent of the action valueTake the gradient of the Critic with respect to the action, which requires QQ to be differentiable in aa
Typical algorithmsREINFORCE, A2C, PPO, SACDPG, DDPG, TD3

Criterion: if the task has several equally good but completely different solutions (for example, going around to the left or to the right) → stochastic policy; if the task’s actions are smooth and unimodal and extreme sample efficiency is required → deterministic policy.

(4) First-order approximation, or second-order constraint

TRPO and PPO optimize the same trust-region objective; the difference is in how they solve it:

  • TRPO explicitly constructs the KL constraint E[KL(πold∥πθ)]≤δ\mathbb{E}\left[\mathrm{KL}(\pi_{\mathrm{old}}\|\pi_\theta)\right]\le\delta, turns the constraint into a quadratic form with a second-order approximation of the Fisher information matrix, then solves the “matrix–vector product” with conjugate gradient and guarantees that each step really decreases the objective with a line search. What it provides is a verifiable guarantee of monotonic improvement, at the price that every step must compute a Fisher vector product, which becomes more expensive as the network grows.
  • PPO uses clipping to keep the ratio rt(θ)=πθ/πθoldr_t(\theta)=\pi_\theta/\pi_{\theta_{\mathrm{old}}} inside [1−ε,1+ε]\left[1-\varepsilon,1+\varepsilon\right], performs only first-order optimization, and can run several epochs on one batch of samples. It has no theoretical guarantee, but it is cheap to implement, has few hyperparameters, and behaves stably under large-scale parallelism.

Criterion: if you need a theoretical guarantee, the network is not large, and you are willing to pay the second-order price → TRPO; if you need engineering stability, compute is limited, and environments can be parallelized → PPO. Note that PPO’s clipping is a soft constraint, so in practice you should still monitor the approximate KL and the clip fraction, and end that epoch early once a threshold is exceeded.

(5) One-step bootstrapping, or multi-step returns

This is the bias–variance axis, and every “multi-step” trick is a point chosen on this axis:

TD(0): Rt+1+γV(St+1)⟶MC: Gt=∑k=0∞γkRt+k+1\text{TD(0)}:\ R_{t+1}+\gamma V(S_{t+1}) \quad\longrightarrow\quad \text{MC}:\ G_t=\sum_{k=0}^{\infty}\gamma^k R_{t+k+1}
Estimation methodBiasVarianceWhen it is biased
One-step TD targetLarge (depends on the estimation error of the current VV)SmallWhen the value function is already fairly accurate
nn-step returnMediumMediumWhen a compromise is needed and episodes have a definite length
Complete return GtG_tNoneLargeWhen episodes are short and rewards are dense
GAE (λ\lambda interpolation)Continuously adjustable through λ\lambdaContinuously adjustable through λ\lambdaThe standard practice for Actor-Critic style algorithms

The interpolation formula of GAE:

A^tGAE=∑l=0∞(γλ)l δt+l,δt=rt+γ(1−dt)V(st+1)−V(st)\hat{A}^{\mathrm{GAE}}_t=\sum_{l=0}^{\infty}(\gamma\lambda)^l\,\delta_{t+l},\qquad \delta_t=r_t+\gamma(1-d_t)V(s_{t+1})-V(s_t)

Criterion: λ→0\lambda\to 0 trusts bootstrapping more (stable but biased); λ→1\lambda\to 1 trusts the true return more (accurate but noisy). Continuous control commonly uses λ=0.95\lambda=0.95; it can be raised when episodes are very short or rewards are extremely dense.

(6) Model-free, or model-based

Model-free methods leave “how the environment changes” to be learned implicitly through sampling; model-based methods first learn a transition model and then plan inside it or generate virtual samples. All the algorithms covered in this article are model-free; model-based methods (the DreamerV3, TD-MPC2 family) belong to another line.

DimensionModel-freeModel-based
Sample efficiencyLow (especially on-policy)High; one real interaction can be reused repeatedly by “imagining”
Asymptotic performanceHigh, not limited by model errorLimited by model error; long-horizon predictions become distorted
Implementation difficultyMediumHigh (the model and the policy must be trained together, and model bias must be handled)
Applicable scenarioSimulation is cheap and can be parallelized at scaleReal hardware is expensive and the number of interactions is limited

Criterion: if interaction is cheap, go model-free and simply pile on samples; if interaction is expensive, learn a model first and then try things out inside the model.

19.3 The selection decision chain: filtering downward from the constraints

Compress the divergences above into a decision flow that can be followed directly (at each step ask “does this constraint hold?”, and if it does, go down the corresponding branch):

Is there an exact transition model P and reward R, and are the states enumerable?
├── Yes → dynamic programming (policy evaluation / policy iteration / value iteration)
└── No (model-free) → is the action space discrete or continuous?
    ├── Discrete → do you need to reuse old data and allow offline training?
    │   ├── Yes → the DQN family (Double / Dueling / prioritized replay), mind the termination mask and overestimation
    │   └── No → Q-learning (tabular), or go straight to PPO (for large-scale parallelism)
    └── Continuous → what are the interaction budget and the parallel capability?
        ├── Simulation can run thousands of environments in parallel, and the tuning budget is limited
        │   └── PPO (with GAE λ≈0.95, advantage normalization, KL early stopping)
        ├── Real hardware or simulation is expensive, and data must be reused
        │   ├── The task is unimodal and the actions are smooth → DDPG → TD3 (twin critics taking the min + delayed updates + target smoothing)
        │   └── The task is multimodal and needs entropy-driven exploration → SAC (double Q + entropy regularization + automatic temperature)
        ├── A no-degradation guarantee is needed for every update
        │   └── TRPO (small and medium networks; prefer PPO for large networks)
        └── Only demonstrations are available, with no reward that can be designed
            └── Out of scope for this article: switch to behavioral cloning / imitation learning

The accompanying “three budget tiers” comparison:

Budget constraintFirst choiceAlternativeWhat not to choose
Ample compute, parallelizable environments, stable reproduction desiredPPOA2C (lighter)TRPO (the second-order solve is not worth it on large networks)
Interaction samples are extremely expensive (real hardware, clinical trials, industrial production lines)SAC / TD3 (off-policy + replay)ACER (more thorough data reuse but harder to implement), model-based methodsREINFORCE, A2C (on-policy, lowest sample utilization)
Limited tuning manpower, few hyperparameters requiredPPODQN (for discrete tasks)ACER, TRPO (high hyperparameter and implementation complexity)

19.4 The four easiest combinations to get wrong

These are not theoretical taboos but mismatches that recur in practice, and each of them corresponds to a specific mechanism from an earlier section:

  1. Using PPO to train on an offline dataset. PPO is an on-policy algorithm; it assumes that the data come from near the current policy. The distribution of offline data is far from the current policy, the importance-sampling ratio oscillates violently, and clipping cannot save it. Offline data should go through off-policy methods (DQN, SAC) or dedicated offline reinforcement learning algorithms.
  2. Using DQN for continuous actions. The DQN target contains max⁡a′Q(s′,a′)\max_{a'}Q(s',a'), and over a continuous action space this maximum cannot be enumerated; it can only be found by optimization, so every sample requires solving an inner optimization, an unacceptable cost. For continuous actions one should switch to a deterministic policy (DDPG/TD3) or a policy that can be sampled (SAC/PPO).
  3. Using a deterministic policy for a multimodal task. When there are two optimal actions (for example, an obstacle can be bypassed on either the left or the right), a deterministic policy can output only one point; during training it is pulled back and forth by the gradients of the two modes and eventually converges to an invalid action in between. Such tasks should use a stochastic policy, so that the distribution retains both peaks.
  4. Using TRPO to stack a huge network. TRPO must compute the product of the Fisher information matrix with a vector at every step, and the cost grows with the number of parameters; on a vision-backbone-level network, the cost of a single update far exceeds the benefit. In that case PPO’s clipping approximation is the correct choice.

19.5 One-page cheat sheet: one sentence per algorithm

  • DP: the exact solution when the model is known; applies the Bellman equation repeatedly as an iteration formula and needs no sampling.
  • MC: wait for the episode to end, then estimate the value with the sample mean of the true returns—unbiased but with large variance.
  • TD(0): update after a single step, bootstrapping with “one-step reward + successor estimate”—small variance but large bias.
  • Q-learning: TD plus a max⁡\max, approximating Q∗Q^* directly, which is why it can be off-policy and can reuse any data.
  • DQN: the deep version of Q-learning, relying on experience replay to decorrelate data and on a target network to cut the bootstrapping loop.
  • REINFORCE: the most bare-bones policy gradient, weighting log⁡π\log\pi by the return of the whole trajectory; a baseline is mandatory for it to be usable.
  • A2C / A3C: add a Critic as a baseline and replace “return” with “advantage”, which greatly reduces the variance; A3C uses asynchronous parallelism, A2C uses synchronous batches.
  • GAE: not an algorithm but an advantage estimator, interpolating continuously between the one-step TD target and the complete return via λ\lambda—standard equipment for all AC-style algorithms.
  • TRPO: writes “how conservative the policy update must be” as a hard KL constraint, and uses a second-order approximation + conjugate gradient + line search to guarantee monotonic improvement.
  • PPO: a first-order approximation that replaces the KL constraint with clipping—cheap, stable, few hyperparameters, and the default baseline for continuous control and large-scale parallelism.
  • ACER: an off-policy Actor-Critic that estimates values with Retrace and controls variance with truncated importance sampling—high sample efficiency but the heaviest implementation.
  • DPG: the deterministic policy gradient theorem, which lets the gradient of continuous actions be passed back through the Critic; it is the theoretical prototype of DDPG.
  • DDPG: DPG plus deep networks, a replay buffer, target networks, and soft updates—the first generation of practical algorithms for continuous control.
  • TD3: three patches on DDPG—twin critics taking the min⁡\min to suppress overestimation, the Actor updated only every two steps, and clipped noise added to the target action for smoothing—cutting off the positive feedback of “overestimation → amplified by bootstrapping → exploited by the Actor” with a minimal change.
  • SAC: writes entropy into the objective, so the optimal policy changes from “a point” to “a Boltzmann distribution”—exploration is built in, multimodality is expressible, and the temperature α\alpha automatically tracks the target entropy.

19.6 Three general principles worth taking away

First, the objective function of every algorithm is the same expected return; the only difference is “what is used to estimate it”. Value-based methods estimate it with the Bellman recursion of QQ or VV, policy-based methods estimate it with log⁡π\log\pi and an advantage estimate, and deterministic-policy methods estimate it with the gradient of the Critic with respect to the action. When you see a new algorithm, first ask: what it replaced is the estimator, the update rule, or the sampling scheme?

Second, there are only three kinds of training stabilization. Every engineering trick that appeared earlier can be sorted into these three kinds:

Problem to solveMeansWhere it appears
A single update step is too large and the policy collapsesLimit the step size: hard KL constraint, soft clipping constraint, trust region, line searchTRPO, PPO, ACER
The gradient variance is too large to learnReduce the variance: baseline, advantage, GAE, return normalization, entropy regularizationREINFORCE, A2C, PPO, SAC
The data are highly correlated and training is unstableDecouple the correlation: experience replay, target networks, soft updates, parallel samplingDQN, DDPG, TD3, SAC, A2C/A3C

Third, every hyperparameter lies on the same three trade-off axes, and tuning is choosing points on these three axes.

Trade-off axisLeaning leftLeaning rightKnobs
Bias ↔ varianceOne-step TD, small λ\lambda, small ε\varepsilonComplete return, large λ\lambda, large ε\varepsilonGAE’s λ\lambda, PPO’s ε\varepsilon, the nn of nn-step returns
Sample efficiency ↔ stabilityOn-policy, each piece of data used onceOff-policy, replay reuse, importance-sampling correctionReplay buffer size, the number of epochs each batch is reused for
Exploration ↔ exploitationStrong entropy regularization, large noise, large ε\varepsilonWeak entropy regularization, small noise, greedySAC’s α\alpha, DDPG’s noise scale, the ε\varepsilon of ε\varepsilon-greedy

Remembering these three axes is more useful than remembering the default hyperparameters of any particular algorithm: when the task changes, the defaults must be retuned, but the directions of these three axes never change.


20. References

  • Sutton & Barto, Reinforcement Learning: An Introduction, 2nd Edition.
  • Mnih et al., Human-level control through deep reinforcement learning (DQN, Nature 2015).
  • Silver et al., Deterministic Policy Gradient Algorithms (DPG, 2014).
  • Lillicrap et al., Continuous control with deep reinforcement learning (DDPG, 2016).
  • Fujimoto et al., Addressing Function Approximation Error in Actor-Critic Methods (TD3, 2018).
  • Haarnoja et al., Soft Actor-Critic: Off-Policy Maximum Entropy Deep Reinforcement Learning with a Stochastic Actor (SAC, 2018).
  • Haarnoja et al., Soft Actor-Critic Algorithms and Applications (SAC v2, target entropy and automatic tuning of α\alpha, 2018).
  • Schulman et al., Trust Region Policy Optimization (TRPO, 2015).
  • Schulman et al., High-Dimensional Continuous Control Using Generalized Advantage Estimation (GAE, 2016).
  • Schulman et al., Proximal Policy Optimization Algorithms (PPO, 2017).
  • Wang et al., Sample Efficient Actor-Critic with Experience Replay (ACER, 2016).
  • Mnih et al., Asynchronous Methods for Deep Reinforcement Learning (A3C, 2016).
  • OpenAI Spinning Up documentation: https://spinningup.openai.com/en/latest/
  • Conversation material consulted when the original note was compiled: https://chat.deepseek.com/share/moph3hs5qjjr5wzwvz

Appendix: Glossary of Abbreviations

AbbreviationFull name in EnglishExplanation
ACActor-CriticActor-Critic (a policy network plus a value network)
ACERActor-Critic with Experience ReplayActor-Critic with experience replay
A2CAdvantage Actor-CriticAdvantage Actor-Critic (synchronous version)
A3CAsynchronous Advantage Actor-CriticAsynchronous Advantage Actor-Critic
BNBatch NormalizationBatch normalization (standardizing the input of each layer)
DDPGDeep Deterministic Policy GradientDeep Deterministic Policy Gradient
DPDynamic ProgrammingDynamic programming
DPGDeterministic Policy GradientDeterministic policy gradient
DQNDeep Q-NetworkDeep Q-Network
DRLDeep Reinforcement LearningDeep reinforcement learning
GAEGeneralized Advantage EstimationGeneralized advantage estimation
i.i.d.independent and identically distributedIndependent and identically distributed
KLKullback-Leibler divergenceKL divergence (a measure of the difference between two probability distributions)
MCMonte CarloMonte Carlo
MDPMarkov Decision ProcessMarkov decision process
OUOrnstein–Uhlenbeck processOrnstein–Uhlenbeck process (a continuous-time noise process with mean reversion)
PGPolicy GradientPolicy gradient
PPOProximal Policy OptimizationProximal policy optimization
RLHFReinforcement Learning from Human FeedbackReinforcement learning from human feedback
SACSoft Actor-CriticSoft Actor-Critic (the maximum-entropy version)
TDTemporal DifferenceTemporal difference
TD3Twin Delayed DDPGTwin Delayed Deep Deterministic Policy Gradient
TRPOTrust Region Policy OptimizationTrust region policy optimization

On the origin and language of this article: this article was compiled from a phone screen recording of a Chinese note on deep reinforcement learning and rearranged along the logic of the knowledge. The Chinese original is a single-language version without an English counterpart; this page is the English edition translated with the same chapter structure.

Comments

Loading comments…

    ← Back to home