Contents
- 0. Origin and How to Read This Note
- 1. Return, Value Functions, and Optimal Policies
- 1.1 Return: discounting future rewards back to the present
- 1.2 State value and action value
- 1.3 Optimal value functions and optimal policies
- 1.4 The two technical routes
- 2. The Bellman Equation: Folding the Future Back into the Present
- 2.1 Expectation form
- 2.2 Optimal form
- 2.3 Why using max\maxmax in the target yields an “off-policy” algorithm
- 3. Dynamic Programming: Policy Evaluation and Policy Iteration
- 3.1 Policy evaluation
- 3.2 Pseudocode: policy evaluation
- 3.3 Pseudocode: policy iteration
- 3.4 The policy improvement theorem
- 4. Monte Carlo: Using the True Return of Complete Episodes
- 4.1 Basic idea
- 4.2 First-visit and every-visit variants
- 4.3 Computing backwards: obtaining the return of any time step in O(1)O(1)O(1)
- 4.4 Why the first-visit variant is more common
- 4.5 Pseudocode: every-visit MC
- 4.6 What “append GGG to Returns” actually does
- 5. Temporal Difference TD(0): Update After a Single Step
- 5.1 Taking half from DP and half from MC
- 5.2 The TD(0) update rule
- 5.3 Why the expectation of the TD error is 0
- 5.4 Pseudocode: TD(0)
- 5.5 The bias-variance trade-off between MC and TD
- 6. Q-learning and DQN
- 6.1 Q-learning: learning the optimal action value directly
- 6.2 The limitations of the tabular approach
- 6.3 The two key techniques of DQN
- 6.4 The core idea and pseudocode of DQN
- 6.5 Six common questions about DQN
- 6.6 The limitations of DQN
- 7. Policy Gradient and REINFORCE
- 7.1 Why policy gradients are needed
- 7.2 The policy gradient theorem
- 7.3 REINFORCE: the most naive policy gradient
- 8. Actor-Critic and A2C/A3C
- 8.1 Why a baseline is subtracted
- 8.2 Division of labor between the actor and the critic
- 8.3 A2C: synchronous advantage actor-critic
- 8.4 The difference between A3C and A2C
- 8.5 Pseudocode: A2C
- 9. GAE: Generalized Advantage Estimation
- 9.1 An Unavoidable Question: How Should the Advantage Be Estimated
- 9.2 The GAE Formula
- 9.3 λ\lambdaλ Interpolates Between the Two Ends
- 9.4 Recursive Computation: Pushing Back from the End of the Trajectory
- 9.5 Pseudocode: Computing GAE
- 9.6 Why GAE Works Well, and What It Is Not
- 10. TRPO: Trust Region Policy Optimization
- 10.1 Background: What to Do When the Policy Collapses
- 10.2 Practical Solution: Conjugate Gradient + Line Search
- 10.3 Pseudocode: TRPO
- 10.4 Three Details Explained
- 10.5 Limitations and Status of TRPO
- 11. PPO: Proximal Policy Optimization
- 11.1 Principle: Replacing the KL Constraint with Clipping
- 11.2 Why Clipping Can Approximate a “Trust Region”
- 11.3 Value Targets: What the Critic Actually Fits
- 11.4 Pseudocode: PPO-Clip (Full Version)
- 11.5 Section-by-Section Explanation of the Pseudocode
- 11.6 Detach: Which Three Things in PPO Must Not Have Gradients
- 11.7 PPO Implementation Pitfall Checklist
- 11.8 PPO versus TRPO
- 11.9 Scope of Application
- 12. ACER: Actor-Critic with Experience Replay
- 12.1 ACER’s Historical Position and Outcome
- 13. DPG: Deterministic Policy Gradient
- 13.1 Why a Deterministic Policy Is Needed
- 13.2 Taking the Limit of the Stochastic Policy Gradient: How the Theorem Comes About
- 13.3 Term by Term: What Each of the Three Factors Is Saying
- 13.4 Three Differences from the Stochastic Policy Gradient
- 13.5 Pseudocode: DPG (Full Version)
- 13.6 Section-by-Section Explanation of the Pseudocode
- 13.7 Gradient Flow and detach: Which Three Places in DPG Must Be Cut
- 13.8 DPG Implementation Pitfall Checklist
- 13.9 DPG’s Limitations, Scope, and “What Is Still Missing Before DDPG”
- 14. DDPG: Deep Deterministic Policy Gradient
- 14.1 Three bloodlines: DPG’s theorem, DQN’s stabilization, and batch normalization’s input handling
- 14.2 Four components and the network structure
- 14.3 Two losses and the soft update
- 14.4 Pseudocode: DDPG (complete version)
- 14.5 Section-by-section commentary on the pseudocode
- 14.6 Gradient flow and detach: the complete checklist for DDPG
- 14.7 DDPG implementation pitfall checklist
- 14.8 Hyperparameters and tuning manual
- 14.9 DDPG’s position, three pathologies, and scope of application
- 15. TD3: Twin Delayed Deep Deterministic Policy Gradient
- 15.1 Three failure modes: what TD3 is actually fixing
- 15.2 Patch one: clipped double Q
- 15.3 Patch two: delayed policy updates
- 15.4 Patch three: target policy smoothing
- 15.5 Complete pseudocode (TD3)
- 15.6 Section-by-section commentary
- 15.7 Gradient flow and detach checklist
- 15.8 Pitfall checklist
- 15.9 Item-by-item comparison of TD3 and DDPG, hyperparameters, and scope of application
- 16. SAC: Maximum Entropy Actor-Critic
- 16.1 Why add entropy: three motivations
- 16.2 The maximum entropy objective and the soft Bellman equation
- 16.3 Three losses: Critic, Actor, and temperature
- 16.4 The reparameterization trick and the Jacobian correction of tanh
- 16.5 Automatic adjustment of the temperature α\alphaα
- 16.6 Complete pseudocode (SAC v2)
- 16.7 Section-by-section commentary
- 16.8 Gradient flow and detach checklist
- 16.9 Pitfall checklist
- 16.10 Comparison with PPO / DDPG / TD3 and scope of application
- 17. Algorithm lineage and comparison of key characteristics
- 17.1 How the methods relate to one another
- 17.2 Comparison table of key characteristics
- 17.3 Quick selection guide and three frequent pitfalls
- 18. Summary of key formulas and loop strategies
- 18.1 Value-based methods
- 18.2 Policy-gradient methods
- 18.3 Deterministic-policy methods
- 18.4 What the three loops have in common
- 19. Summary: Core differences among the algorithms and when to use them
- 19.1 One table that makes the differences among all algorithms visible
- 19.2 Six key divergences: where exactly do the algorithms differ
- 19.3 The selection decision chain: filtering downward from the constraints
- 19.4 The four easiest combinations to get wrong
- 19.5 One-page cheat sheet: one sentence per algorithm
- 19.6 Three general principles worth taking away
- 20. References
- Appendix: Glossary of Abbreviations
Deep Reinforcement Learning Core Algorithm Notes: From the Bellman Equation and DQN to GAE, PPO, and 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):
| Symbol | Meaning |
|---|---|
| State (state), action (action), reward (reward), and the next state after executing the action | |
| Policy (policy), the probability of choosing action in state | |
| A parameterized policy controlled by parameters (usually a neural network) | |
| A deterministic policy that directly outputs one deterministic action | |
| State value (state value), the expected return when starting from state and acting according to policy | |
| Action value (action value), the expected return when starting from state , first executing action , and afterwards acting according to | |
| Discount factor, ; rewards further in the future carry less weight | |
| Learning rate (step size), controlling the magnitude of each parameter update | |
| Exploration rate, or the clipping range in PPO | |
| The parameter in GAE that controls the trade-off between bias and variance | |
| Experience replay buffer | |
| or | 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 , the agent receives a sequence of rewards . Accumulating this sequence with the discount factor gives the return:
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 :
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, ; then
For the geometric series converges and the return is bounded. If , the upper bound degenerates to 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: controls both “weight” and “horizon”. The weight of a reward steps later is , and the number of steps needed for the weight to decay to one half is . With this is about 69 steps; with , about 6.6 steps. So tuning changes the “effective horizon length” and the “order-of-magnitude upper bound of the return” at the same time, which is why 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 and thereafter always acting according to policy ”:
The action value is the expectation of the return when “standing in state , first executing action , and thereafter acting according to ”:
The relation between the two is a weighted average by the policy probabilities:
This sentence is worth remembering: is “if I have already decided to follow the policy, how much do I get on average”, while is “if I first execute a particular action and then follow the policy, how much do I get on average”. is the weighted average of 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 , treat the first action as an extra conditioning variable:
The first equality is the definition of ; 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 .
Step two: recognize that the inner term is exactly . The inner conditional expectation is word-for-word the definition of , hence
Step three: why the reverse equality does not exist. In the action “has already been fixed”, so it carries action information; whereas 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 cannot be recovered from . Only in the degenerate case where one additionally knows that “the policy at is deterministic” does hold.
Step four: this explains the difference between the two technical routes. Learning yields a policy directly through , so the value-based control methods (Q-learning, DQN, DDPG) all learn ; learning can only evaluate “the current policy”, and improving the policy then requires knowing the environment’s transition probabilities (dynamic programming) or learning an additional (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”:
Once has been obtained, the optimal policy is simply
That is, once 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 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 or , 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 and directly optimize the policy with parameters so that the expected return 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 into the first reward and the remainder:
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:
Expanding it into a double sum over actions and over next states:
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 ”:
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.
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:
Step three: the second term is the key one, and this is where the Markov property enters. Refine the conditioning step by step:
Then, by the Markov property, “given , the earlier history has no influence on the conditional distribution of the future”, so
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.
Pulling outside the inner sum is legitimate because depends on neither nor .
Step five: the action-value version. The action is already fixed, so the outer level is no longer weighted by ; but the randomness of “afterwards still acting according to ” remains, so the actions of the next state must be weighted by :
Replacing the innermost level with the definition of (1.2) gives a form structurally identical to the version:
Step six: division of roles between the two equations. The equation hands “action selection” to the policy , so it suits policy evaluation; the equation fixes the action on the left-hand side, so it suits control (because taking over already improves the policy). Dynamic programming uses both versions at once: policy evaluation uses the version, policy improvement uses the 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:
The Q-learning update is a sampled approximation of this optimality equation: one real transition replaces the sum over , 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 , for any policy,
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 ”. Hence, for each fixed state, the optimal policy is simply the , and
Step two: take the maximum over policies of the Bellman expectation equation for . In the expression for , the dependence on appears only in the inner term . Taking the maximum over amounts to taking, independently for each next state , the maximum over actions:
Being able to push the inside the sum relies on two facts: the weights are nonnegative and independent of ; and the maximization over each can be carried out independently (one and the same may choose a different greedy action in different states, which is not a conflict). Hence
Step three: substitute to obtain the version. Note that must stay outside the sum:
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
is 1-Lipschitz (), and together with the weighted average over transition probabilities this yields
that is, is also a -contraction. By the Banach fixed-point theorem it has a unique fixed point , and iterating from an arbitrary initial value converges—which is precisely the basis on which value iteration (3.4) rests.
2.3 Why using in the target yields an “off-policy” algorithm
The target of Q-learning is to converge to the optimal action value , so the target uses 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 -greedy (-greedy, choosing the current best action with probability and a random action with probability ) 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 , find . The method is to apply the Bellman expectation equation repeatedly, substituting the old value estimate to compute a new value estimate:
This iteration is called iterative policy evaluation (iterative policy evaluation). It has two important points:
- Synchronous update: the -th round uses the entire value table of the -th round and must not overwrite values while computing them; otherwise the convergence analysis becomes more complicated.
- Each round takes 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 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 :
Policy evaluation is simply repeatedly doing .
Step two: prove that it is a -contraction in the infinity norm. Take any two value tables ; for each state :
The first inequality is the triangle inequality; the second uses , , and the fact that each absolute value is at most . Taking the maximum over all gives
Step three: the contraction property directly yields a geometric convergence rate. Since is a fixed point of (it satisfies the Bellman equation), substituting repeatedly into the contraction inequality:
So the error shrinks by at least a factor of every round; the convergence rate does not depend on the initial value and is determined only by .
Step four: the necessary condition for convergence and its engineering meaning. The contraction property requires ; the closer is to 1, the slower the convergence (with it takes about rounds to push the error down to order ). 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 ; value iteration inserts the and the contraction property still holds (see step four of 2.2), but the fixed point becomes .
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 records the largest change of the value table in this round, and 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
then for every state , . 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 ; then by the – relation of 1.2:
The meaning is: under the same , the greedy action chosen from has a value no lower than the weighted average value of the original policy. Equality holds if and only if at places probability only on the action with the largest .
Step two: unroll this inequality step by step along the trajectory. Unroll once in TD form:
Note that the expectation subscript has already changed to (actions are sampled from the new policy), but the value being compared is still the old policy’s —this step compares the two policies’ values at the same state, rather than substituting in advance. Then apply the lemma of step one to (the “new policy” is still the same ):
Continuing the unrolling for steps, using the same inequality once per step:
Step three: let to obtain the conclusion. By the boundedness of 1.1, , the tail term , hence
Step four: why “every state must be greedy”. Every step of the unrolling chain requires 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 , then , 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 is the optimal policy. If at least one state is strictly unequal, then 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 within finitely many steps.
Value iteration (value iteration) merges evaluation and improvement into one step:
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 , define the greedy policy and its action value:
Perform only one round of policy evaluation for :
Step two: rewrite “summing under the greedy policy” as a . Because is a deterministic policy, the outer sum over leaves only a single action, so
This is an identity, not an approximation: the action selected by is exactly . The value iteration formula in the main text follows.
Step three: if the iteration converges, the limit must satisfy the optimality equation. Suppose ; take the limit of both sides of the equation above:
The right-hand side is exactly the result of applying the Bellman optimality operator , so is a fixed point of ; by the contraction property and uniqueness in step four of 2.2, .
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 as a whole is still a -contraction: every round guarantees that the error shrinks by a factor of , 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 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 ( and ), 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:
That is: collect all the returns that were actually obtained after state in history, take the average, and use it as the estimate of . 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 return samples are collected for state ; they are mutually independent and each satisfies (because the sampling process of every episode is identically distributed). By the linearity of expectation:
This shows that the estimate is unbiased, regardless of how large is—even a single episode is correct in expectation.
Step two: the variance decreases as . Independence makes every covariance term zero:
The standard deviation is therefore : 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 , if the rewards at each step are independent with common variance :
With 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
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 is visited at , , and , with corresponding returns , , and .
- First-visit:
Returns(s) = [4], so ; - Every-visit:
Returns(s) = [4, 8, 6], so .
Both converge to the same target (both ); the difference lies in how the samples are used.
4.3 Computing backwards: obtaining the return of any time step in
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
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 ; computing backwards is .
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 one sums directly by definition:
then the -th time step requires computing terms, and the total amount of computation is
Step two: backward recursion needs only one multiply-add. From the recursion , starting at the end:
Each step backwards performs only “one multiplication and one addition”, for operations in total, i.e., .
Step three: the base case of the recursion must be . The episode terminates at time and there are no rewards afterwards, so ; substituting into the recursion gives , consistent with the definition. If the base case were written as something else (for example bootstrapping with ), 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 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:
- 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.
- 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 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 . Each time an episode is completed, the return corresponding to each state visited in that episode is appended.Append G to Returns(S_t)is exactly sample collection. is “the true discounted return obtained from 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 ), should 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):
Here 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:
What the TD target does is to replace the unknown remainder by its expected estimate :
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:
The right-hand side is exactly the Bellman operator applied to . It equals precisely only when ; otherwise the bias is
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:
whereas by step three of 4.1 the variance of is . Take : the former is about times 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 -step return interpolates between the two. Define the -step return
is TD(0), and (beyond the episode length) is MC. The larger is, the smaller the bias and the larger the variance. GAE (chapter 9) writes this interpolation as an exponentially weighted average over all , thereby tuning bias and variance continuously with a single parameter .
5.2 The TD(0) update rule
Three important points:
- is the learning rate (step size), controlling the magnitude of each update;
- the bracket contains the TD error , measuring the gap between “the actual value (one-step reward plus successor estimate)” and “the current estimate”;
- when , the current estimate is too low and is adjusted upward; when , it is adjusted downward.
5.3 Why the expectation of the TD error is 0
For a fixed policy , if already equals the true , then
because the expectation inside the bracket is exactly “the expression for ” on the right-hand side of the Bellman equation, and subtracting 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 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.
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 , hence
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 , its expected increment is ; at this term is zero, so 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
When differentiating with respect to , the inside also depends on the parameters, and a rigorous derivative must carry this term; the TD update deliberately drops it and differentiates only the “subtracted ”:
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 , i.e., “the expectation under the current policy”. The target of Q-learning is , 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:
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 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:
| Dimension | Monte Carlo | Temporal difference TD(0) |
|---|---|---|
| Needs an environment model | No | No |
| Must wait for the episode to end | Yes | No, updates at every step |
| Update target | The true return | One-step reward plus successor estimate |
| Bias | Unbiased ( is the true return) | Biased (depends on the current estimate ) |
| Variance | Large (the return accumulates the randomness of the whole trajectory) | Small (uses only one random reward) |
| Convergence speed | Slow, and only for episodes that terminate | Fast, can be used for continuing tasks |
| Sensitivity to initial values | Insensitive | Sensitive (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 in the target, so it approximates directly:
Two details:
- Why the target uses : Q-learning must converge to the optimal , so it uses rather than weighting by the policy probabilities. This also makes it an off-policy algorithm—sampling may use -greedy while the learning target is always the optimum.
- When is a terminal state: by convention , and the update degenerates to , 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 . From step two of 2.2:
Step two: replace the expectation with one real transition. When sampling, only one can be observed, so the weighted sum over is replaced by a single sample:
The sampling of itself is unbiased (), but the inside the bracket is the current estimate rather than , so the whole expression is still biased with respect to —this bias comes from bootstrapping, not from sampling.
Step three: write the fixed-point iteration in incremental form. With step size , update only the visited pair :
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 . In the tabular case, if (1) every is visited infinitely often; (2) the step sizes satisfy the Robbins–Monro conditions , ; (3) , then this is a stochastic approximation of a contraction operator and almost surely. Intuitively, the per-step error satisfies
The first term shrinks the error of the pair itself by , the second introduces the neighbours’ error scaled by , 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 and is completely independent of “which policy produced the data”; the expression also contains no importance weights such as . Therefore, as long as the behavior policy (behavior policy, the policy actually used for sampling) can visit all , whether it is -greedy, random, or human demonstrations, what is learned is the same . This is the precise definition of “off-policy”: the target policy is decoupled from the behavior policy.
Step six: why -greedy is part of the convergence conditions. If the behavior policy never tries a certain action, the corresponding value can never be corrected and the first condition “visited infinitely often” fails. guarantees that every action has a positive probability of being tried; 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 pair. As soon as the number of states grows, this explodes:
- with image input (for instance the 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 , 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 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 produced by interaction are stored in a replay buffer (Replay Buffer, ), 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 is maintained and used to compute the TD target ; the online network’s parameters are copied over only every 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 , the online network outputs the Q values of all actions, and the output corresponding to the target action should regress toward the target value :
The loss function (mean squared error):
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
Its derivative with respect to is . So "" is exactly a gradient-descent step of size on (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
Note the minus sign: gradient descent moves along , which pulls the prediction toward the target .
Step two: why must be treated as a constant (detach). If the target’s were replaced by a form differentiable with respect to , the gradient would acquire an extra term
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 at every step, the labels of adjacent mini-batches remain highly correlated and the gradient direction jitters a lot. Using and synchronizing every steps is equivalent to fixing the target within a time window , approximating “non-stationary regression” by “piecewise stationary regression”. If is too small it degenerates to no target network; if 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, and are nearly identical, the gradients are highly correlated, and the effective sample size is far smaller than the batch size . Drawing uniformly at random from makes the samples approximately independent and reduces the gradient variance roughly as —the same reasoning as the in step two of 4.1.
Step five: how large is the overestimation bias caused by . Suppose the estimate of each action carries independent zero-mean noise :
because 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 , 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:
The action is chosen by the online network and the value is given by the target network . The noises of the two networks are approximately independent, so the selection bias of and the estimation bias of 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.
- 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. - 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. - Why
φ_trather than the raws_tis stored inD: 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. - 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.
- The two branches of
y_jare 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”. - 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 ”. In implementation,
gatheris 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. - Hard copying every
Csteps 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.
| Symptom | Possible cause | Fix |
|---|---|---|
| Q values keep inflating while the return does not change | No target network, or the target is not detached, or max is used without Double | Fix θ⁻, detach the target, switch to Double DQN |
| Q values abnormally low near the time limit | Truncation treated as termination | Split done/truncated; truncation should still bootstrap |
| Performance suddenly collapses late in training | ε decays too fast, learning rate too large | Slow down the ε decay, lower the learning rate, add gradient clipping |
| Cannot learn when return scales differ widely | Rewards not scaled | Clip rewards to or apply running normalization |
| The replay buffer contains only similar samples | Buffer too small, sampling strategy too narrow | Enlarge the buffer, increase early exploration |
| Performance degrades immediately after target-network sync | Hard copy period too short | Increase C (commonly 1000–10000 steps) |
6.5 Six common questions about DQN
Question one: what are and respectively?
is the Q-value prediction given by the online network for “the action actually executed in the sample, ”; it is the “prediction” to be optimized. is the regression target computed from “the actual reward 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 moving toward the prediction.
Question two: what is ?
is the set of learnable parameters of a neural network (the weights and the biases ). 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 (or the preprocessed , 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 gives . 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 inside the target 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 at (synchronized only every steps), providing a stable regression target for the optimization.
Question five: why use rather than averaging over the policy?
Because DQN inherits Q-learning and its target is , so the maximum must be taken. Sampling can still use -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 —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 into a state value and an advantage ;
- 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 can simply pick among finitely many values. When actions are continuous (for example robot joint angles), 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 directly with a neural network parameterized by and maximize the expected return by gradient ascent, with no 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 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 ( switches action suddenly when Q values are close).
7.2 The policy gradient theorem
The gradient of the expected return with respect to can be written as:
where denotes a trajectory (trajectory). Reading this formula intuitively:
- for a trajectory , if the return it brings is high, the “probability of this trajectory” is adjusted upward (the gradient direction is weighted by ); if the return is low, it is adjusted downward.
- the gradient of 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
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 , whose probability is
The objective is , where 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 :
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:
When differentiating with respect to , the initial state distribution and the transition probabilities do not depend on , so their derivatives vanish:
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 into the part before and the part after . Given , the rewards before are independent of , and
so the expectation of “the earlier rewards” times is zero and the whole block can be deleted. What remains are only the rewards at and afterwards, i.e., . Hence
(In the rigorous form there is still a 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: is the random sum of a whole trajectory, large in magnitude and volatile; and the norm of grows sharply when the policy approaches determinism (as , 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 . If the data were collected by an old policy , using them directly yields a biased gradient; the correct approach is to multiply by the importance ratio
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 of a complete episode as the weight:
It is unbiased but has very large variance: 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.
- The whole trajectory must be sampled first: the weight of REINFORCE is , and 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.
logp_tis computed at sampling time andG_tis computed backwards: the two are separated for different reasons.logp_tmust be computed under “the version of the policy at that time”, otherwise it is not the true log-probability of this trajectory;G_tmust be accumulated backwards so that a single pass yields the returns of all time steps (forward order would need ).- The order of
G ← γ·G + rcannot be reversed: the correct form is “multiply the discount first, then add the current step’s reward”, i.e., . WritingG ← G + γ·rmisaligns the discount exponent, and earlier rewards end up with smaller weights instead. - The minus sign in
L: deep learning frameworks minimize by default, whereas the policy gradient must maximize , so the loss is negated. An equivalent form isloss = -(logp * G).mean(). - 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
logpof earlier time steps would be stale. - Both
G_tandlogp_tmust be detached: they are weights and labels, not variables to be optimized. IfG_tcarried 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 is , whose magnitude varies with the reward scale of the task (it may be tens or hundreds), and the of adjacent time steps within one trajectory are highly correlated. Subtracting a baseline 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:
Taking , the weight becomes the advantage ; in practice 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
Deep learning frameworks minimize by default, so define
Its gradient is , which matches the expression above after taking the negative sign. Note that is a scalar coefficient inside 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:
So it is an unbiased Monte Carlo estimate of , 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 that depends only on the state:
The inner expectation is zero because . So after subtracting 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 , write ; then
The second term equals and does not depend on . Differentiate the first term with respect to and set it to zero:
Solving gives the minimum-variance baseline
It is the return average weighted by “the squared norm of the gradient”. When and are approximately independent, it degenerates to . This explains why 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 determines the size of the update, and the sign of 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.
| Symptom | Possible cause | Fix |
|---|---|---|
| Gradient noise extremely large, hardly converging | No baseline, no return normalization | Subtract a baseline; apply running normalization to |
| The policy suddenly collapses mid-training | Learning rate too large, single-episode update step too aggressive | Lower the learning rate, add gradient clipping, or switch to PPO |
| No improvement for a long time | Episode too long, discount too strong so the signal vanishes | Shorten the episode, increase , switch to -step returns |
| Enormous variance in continuous control tasks | No constraint on the action-distribution variance | Put a lower bound on the policy’s , or switch to SAC |
| Results vary hugely between runs | Single-trajectory estimates, sensitive to random seeds | Run 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, is large in absolute value and large in variance. If a baseline that depends only on the state is subtracted from the weight, the gradient expectation is unchanged (because ), but the variance drops markedly:
The most natural baseline is the state value . The quantity left after subtracting it,
is called the advantage (advantage): it measures “how much better taking action in state is than average”. means the action is better than average and deserves encouragement; 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.
Step two: is its unbiased single sample. By definition and ; subtracting the two:
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 is a weighted average of :
This step gives the geometric meaning of the baseline: subtracting shifts 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 is better than subtracting a constant. A constant baseline removes only the “global offset”; the differences between states remain. 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 , 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 rather than . Using directly requires additionally estimating values along the action dimension; is already an unbiased single sample of , and subtracting a 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 , updated with the advantage as the weight, raising the probability of high-advantage actions;
- Critic (Critic): the value , trained with temporal-difference or multi-step returns as regression labels, approximating “the expected return starting from ”;
- 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 is large in absolute value and large in variance; after the 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 -step returns:
The overall objective is the sum of three losses:
- 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 approach the true return;
- the third term: entropy regularization (entropy regularization). is the policy entropy, measuring how random the policy is; a large entropy means a more uniform action distribution and more exploration. Subtracting (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
the gradient treats as a constant (detach):
Gradient descent then moves along , exactly the ascent direction of the policy gradient: the probability of actions is raised and that of actions lowered. The minus sign only translates “ascent” into the framework’s “minimization”.
Step two: the gradient and sign of the value term. For
the gradient is . After the update , if then decreases, and if it increases, i.e., it moves toward the target . Note that 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
Differentiating with respect to the parameters (using ):
Under a softmax parameterization this can be written further as ” minus its -weighted mean”, whose geometric meaning is pushing the distribution toward greater uniformity. Taking in the loss means the descent direction is , i.e., increasing the entropy. Note that when some action probability approaches 0 or 1, 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 and the entropy coefficient in practice are exactly what brings the three back to the same order of magnitude.
Step five: the bias-variance trade-off of -step returns. A2C uses
Its bias comes from the bootstrapping at the last step, of order times the value estimation error; its variance comes from accumulating the rewards of the first steps, roughly . Hence:
- : the largest bias (almost entirely bootstrapped) and the smallest variance, degenerating to pure TD;
- : the smallest bias and the largest variance, degenerating to pure MC;
- between 5 and 32: the compromise point commonly used in engineering.
This limitation—“a fixed allows only one compromise point”—is exactly what GAE solves: GAE does not compromise on a single but takes an exponentially weighted average over all and tunes it continuously with one parameter .
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.
- Why open 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.
- What the -step return is: the target of each time step is not waiting for the episode to end, but “the real rewards of steps plus the value estimate at the -th step”. It lies between one-step TD and Monte Carlo: too small an gives a large bias (much bootstrapping), too large an gives a large variance (much accumulation). The common choices are , 16, or 32, or simply replacing the fixed number of steps with GAE.
- The difference between the advantage and the value target: the advantage is for the Actor; the value target is just , for the Critic to regress. The two share the same -step return, but one is “a relative quantity after subtracting the baseline” and the other “an absolute quantity”; they must not be mixed up.
- Why the three losses are combined this way: the policy loss drives up the probability of good actions; the value loss trains the baseline; the entropy term 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.
- One update with all samples together: unlike REINFORCE’s “one trajectory, one update”, A2C aggregates 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 : 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.
| Symptom | Possible cause | Fix |
|---|---|---|
| Policy and value oscillate together | Shared network with too large a value loss | Separate the networks, or reduce the value coefficient |
| The advantage is systematically too large or too small | The -step return is not handled with the terminal mask | Do not bootstrap at terminal steps; truncated steps still bootstrap |
| Exploration is lost early | Entropy coefficient too small, or the policy’s has no lower bound | Raise the entropy coefficient, put a lower bound on the variance |
| The value loss decreases but the return does not rise | The advantage uses a value that was not detached, or the sign is flipped | Detach the advantage, check the sign of -logp*adv |
| The learning rate must be retuned for different tasks | Reward scales differ, the advantage is not normalized | Normalize 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
It measures “how much better than average it is to take action in state .” 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: . This has large bias and small variance—only in the expression is a real signal, everything else relies on bootstrapping from the estimated value , so when 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: , then subtracting . 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 to unify the bias–variance trade-off.
9.2 The GAE Formula
First define the -step TD error
The GAE advantage is the exponentially weighted sum of these TD errors:
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 . The parameter 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 -step advantage. Use the -step return minus the baseline:
Step two: Rewrite the -step return as an accumulation of TD errors (telescoping sum). Note that
Expanding the sum, the intermediate terms cancel in pairs:
The right-hand side is exactly . So we obtain an important identity:
Step three: Take an exponentially weighted average over all . The definition of GAE is “the weighted average of the -step advantages of all lengths, with weights ”:
Swap the order of the two sums. The term appears only when , and its total weight is
Therefore
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 -step advantages” is mathematically equivalent to “the sum of TD errors decaying by .”
Step four: The two endpoints of . When only the term remains, , i.e., the one-step TD advantage; when the weights do not decay, and the telescoping identity from step two (taking ) gives , i.e., the Monte Carlo advantage. This also shows that is not “a newly invented parameter,” but the decay rate of “an exponential weighting over the distribution of -step advantages.”
Step five: The recursive form and the terminal mask. Shifting the weighted sum directly:
This is the recursion of 9.4. At a real termination (), belongs to the next episode and must be cut off, hence the factor ; at the same time the bootstrapping term inside must also be multiplied by . Neither mask can be omitted.
Step six: The effective horizon and the bias–variance trade-off. The weights decay by , so the effective summation length is about . With and this is about 67 steps; with it is about 52 steps. The larger 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 is essentially tuning the “effective horizon,” which is the same thing as tuning the -step return, only smoother and continuously adjustable.
9.3 Interpolates Between the Two Ends
- : only the first term remains, degenerating to the one-step TD advantage , with high bias and low variance;
- : the weights barely decay, approaching the Monte Carlo return advantage, with low bias and high variance;
- between 0.9 and 0.99: usually the best compromise between the two. In practice 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 ( depends on , so it must be pushed back from the end):
where is the real termination mask ( means the episode really ended). The computation proceeds backward from the end, doing one multiply-add per step, with complexity .
Two boundaries that are easy to get wrong:
- Termination and truncation must be separated: must also be written as . 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 recorded as 0, otherwise the value function will fall out of thin air near the time limit, forming a “false cliff.”
- holds only for termination: if the trajectory was truncated, the bootstrapping value of the truncated state should be passed in at the end, in which case degenerates to 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:
- The mask must be applied twice: step 1 masks the bootstrapping term, and step 2 masks . If only the first place is changed, the terminal step will pull the advantage of the next episode in, creating cross-episode contamination.
doneis 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 fieldsdoneandtruncatedin the wrapper layer, and let GAE use onlydone.Retmust use the unnormalized : advantage normalization only serves the policy loss; if the normalized is added back to , 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 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 -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 , 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 will be too far from the old policy , 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):
Three elements:
- Probability ratio : the ratio of the probabilities that the new and old policies choose the same action;
- Objective: maximize weighted by the advantage , 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 , 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 be the discounted state visitation distribution under policy ; then the performance difference of two policies can be written as
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 in the lemma depends on the new policy being solved for and cannot be estimated from old data. TRPO makes an approximation: replace with , obtaining the surrogate objective
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 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
where . 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 , changing the constraint to KL is still safe (slightly conservative).
Step four: Linearize the objective and quadratize the constraint. Expand at and drop the constant term:
where is the Hessian of the KL, equal to the Fisher information matrix:
Step five: Solve the quadratic constrained problem to obtain the natural gradient step. Let ; the Lagrangian is
Setting the derivative with respect to to zero: . Substitute back into the constraint and take equality:
Hence
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. is a matrix ( is the number of parameters, which can reach millions), and both explicit construction and inversion are , which is infeasible. Conjugate gradient (CG) only needs the ability to “multiply by a vector,” and can be estimated at cost with the Fisher-vector product:
In implementation, one forward-backward pass gives , the inner product with gives a scalar, and one more backward pass gives ; about 10 iterations are enough to approximately solve for .
Step seven: Why the direction of the KL is “old ‖ new.” The expectation in the constraint is taken under :
This expectation can be estimated unbiasedly directly from the old-policy samples at hand. If it were written as , the expectation would have to be taken under 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 until the sampled estimate of the KL does not exceed ; 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.
10.2 Practical Solution: Conjugate Gradient + Line Search
Solving the constrained nonlinear optimization directly is very expensive. TRPO makes two approximations:
- Linearize the objective at the old parameters (a first-order approximation, giving the gradient);
- Quadratize the constraint (using the Fisher information matrix, i.e., the second-order expansion of the KL divergence);
- 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;
- 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.
- 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.
- The advantage in step 2 must be computed first: in the objective , 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.
- The probability ratio in step 3 is the core of the “surrogate objective”: is a first-order approximation of the true objective (with the same gradient at ). 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.
- The KL direction in step 4 is easy to write backwards: the paper adopts . The sampled estimate of this direction is more stable on old-policy data (the expectation is taken under ), and it is consistent with the setting of “evaluating the new policy with old data.” Writing also runs numerically, but the estimate has a larger variance and the theoretical guarantee is different.
- What the conjugate gradient in step 5 solves: quadratize the constraint at , giving , where 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 , which suits neural networks with a huge number of parameters.
- 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 until the sampled estimate of the actual KL does not exceed ; if all attempts fail, one usually falls back to an ordinary policy gradient update to guarantee progress every round.
- 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.
| Symptom | Possible cause | Fix |
|---|---|---|
| The KL estimate deviates greatly from the true value | Too few samples in the mini-batch, too few conjugate gradient iterations | Increase the batch size, run at least 10 CG iterations, add a damping term |
| Performance falls off a cliff after the update | The line search does not take effect, is too large | Check the actual KL strictly, set on the order of 0.01 |
| Extremely slow computation | The Fisher matrix is computed for every sample | Approximate with the Fisher-vector product (matrix–vector product), avoid the explicit matrix |
| The policy barely moves | too small, damping coefficient too large | Increase appropriately, reduce the damping |
| The value network does not learn | Value loss and policy objective are mixed, the advantage is not detached | Optimize 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 ? It measures “whether the new policy is more or less aggressive than the old policy in choosing this action.” means the new policy has a higher probability of choosing that action; means lower. The meaning of the objective is: if , increase the probability of such actions ( becomes larger); if , decrease it.
Why can the KL constraint prevent collapse? measures the difference between two distributions. Forcing it to be 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 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:
where:
- : the probability ratio of the new and old policies;
- : restricts to ( is often taken as 0.2);
- takes the smaller of the two: when (worth encouraging), even if wants to exceed the upper limit, the gain is not allowed to exceed , preventing over-rewarding; when (should be suppressed), even if wants to go below the lower limit, the loss is not allowed to exceed .
The intuition of clipping: encourage the policy to improve within the “trust region”—when the ratio goes beyond 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 : the objective takes . Once exceeds , the second term becomes a constant and its gradient with respect to is 0—increasing further brings no more gain, so there is no incentive to keep increasing it.
If : the objective takes . Since is negative, the smaller is (the further below the lower limit), the more negative the first term; once falls below , the second term becomes a constant and the gradient is likewise 0—decreasing 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 and into a piecewise form. Fix the advantage and discuss the relative position of :
- If : when , and takes ; when it takes .
- If : because dividing by a negative number flips the inequality, is equivalent to ; when it takes , and when it takes .
Combined into a single branch:
Step two: Take the piecewise derivative with respect to .
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— and exceeds the upper limit, or and falls below the lower limit. If moves in the unfavorable direction ( decreases when , increases when ), the gradient still exists and pulls the policy back.
Step three: Therefore clip is not “pinning 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 must be used instead of . If were used, the constant term would also be taken when moves away in the unfavorable direction, the gradient would become zero, and the policy would lose its ability to correct errors; moreover, overestimates the objective value (optimistic estimation), which is contrary to the original intention of “conservative improvement.” 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 and the KL radius. Make a second-order expansion of the single-point distribution:
The last step uses . Therefore implies
corresponds to a KL upper bound of about 0.02, the same order of magnitude as the commonly used in TRPO. This is the quantitative correspondence between “the clipping radius” and “the trust radius”: .
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 reaches the boundary in all of them, the actual average KL can noticeably exceed . This is exactly why “reusing the same batch of data for too many of the 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 regress to the Monte Carlo return ”; this is not wrong, but it makes training slow, the variance large, and the scale mismatched with the advantage. PPO’s standard form is:
that is, “the GAE advantage plus the old value estimate at sampling time.” Four key points:
First, why not ? is a Monte Carlo estimate of the true return of a trajectory, and its variance grows linearly with the trajectory length; whereas uses only the GAE bootstrapped to step , 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 rather than the current ? Because the advantage was computed under the value function at the moment of sampling: . Only by using the same to convert it back into “a value quantity” can we guarantee that and are in the same coordinate system. If the currently updating 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 ? From we know that is exactly in the one-step case; GAE is the -weighted multi-step version, so is “an estimate of the -weighted multi-step ,” lying between the one-step TD target and the Monte Carlo return. When it degenerates to the one-step TD target; when it degenerates to the return of a whole trajectory minus the baseline plus the baseline, approximating .
Fourth, it must be detached in implementation. 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 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: and . 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 endpoint degenerates to the one-step TD target. When , GAE reduces to :
Adding to both sides, the two terms cancel:
which is exactly the TD(0) target (see 5.1).
Step two: The endpoint degenerates to the Monte Carlo return. By the telescoping identity of the GAE folding, when
After adding the baseline, cancels, giving , i.e., the discounted return of the whole trajectory.
Step three: A general gives exactly the -return. Write
Then by definition . Expanding verifies that it is exactly consistent with “the exponentially weighted average of all -step returns”:
where . So this target is not “a quantity pieced together arbitrarily,” but a -return with a clear mathematical definition.
Step four: Why its variance is smaller than that of . The weights are nonnegative and sum to 1, so is a convex combination of the . Under the assumption of approximate independence:
The variance of the -step return grows with (step three of 4.1), and the maximum occurs at the MC return with . concentrates the weights on small , which is equivalent to suppressing the part with the largest variance. This is the quantitative reason why “training the Critic with the -return converges faster than with .”
Step five: Why must be added rather than the current . is a quantity computed in the coordinate system of : . Only by adding back the same do we get exactly the defined in step three. If the current were added, we would get , 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 . From we get ; when , is the one-step , and when it is the MC return. So the whole range can be understood as “a -weighted multi-step estimate,” which is another way of stating the same thing as Section 9’s ” 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 , and the denominator must be “the policy at sampling time.” By update time the parameters have already changed, and the recomputed is the new policy, not the old one. For the same reason 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 by the time limit, the environment has not ended, and should still bootstrap to ; 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 depends on the advantage at the next time step, which a forward pass cannot have. One reverse traversal suffices, ; a forward pass would need to repeatedly recompute subsequent terms, degrading to .
Segment 2 ④: Why the value targets are computed in place inside the loop. uses exactly the just computed and the 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 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 .
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 , and direct division underflows easily; the log difference is a finite quantity, and the error in is also smaller.
Segment 3 ⑦: The gradient behavior on both sides of min. When , once exceeds the term becomes a constant and the gradient is 0, so the policy has no incentive to keep increasing that action’s probability; when , once falls below 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 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 , 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 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 , and once 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 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 detached | Source | Consequence of not detaching |
|---|---|---|
logp_old (old log probability) | at sampling time | An 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 | The Actor’s gradient would flow back through , the Actor and the Critic would pull against each other, and the policy gradient would no longer be “a derivative with respect to only” |
V_target (value target) | The Critic’s target carries gradients, so when minimizing 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 to compute and 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 , 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:
| Symptom | Possible cause | Fix |
|---|---|---|
| Collapse early in training, policy becomes deterministic | Learning rate too large, K too large, ε too large | Lower the learning rate to the order of , set K to 3–10, monitor the k3 KL |
| The value loss will not go down | The target uses , the target is not detached, or advantage normalization contaminated the target | Use ; detach the target; normalize only for the Actor |
| The advantage shows a “cross-episode” anomaly | done and truncated are not separated, the mask is applied in only one place | Apply the mask in both places (see 9.4, 9.5) |
| The probability ratio is abnormally large or small for a long time | logp_old is recomputed, or the old value was not stored | Store logp_old at sampling time and detach it |
| The monitored KL becomes negative | was used | Switch to the k3 estimator |
| The value function and the policy shake together | Actor and Critic share the underlying network, loss scales are not balanced | Separate 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 worse | No early stopping, K too large leading to overfitting the old data | Add KL early stopping, or use adaptive ε/K |
| Training is unstable but nothing looks wrong | Reward scale too large, no return normalization | Scale 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
| Dimension | TRPO | PPO |
|---|---|---|
| Constraint method | Hard KL constraint | Probability-ratio clipping (soft constraint) |
| Solver | Conjugate gradient + line search (second order) | Standard gradient descent (first order) |
| Implementation complexity | High | Low |
| Reuse of each data batch | Usually once | Multiple times, over K epochs |
| Stability | Good, but sensitive to hyperparameters | Good, and easier to tune |
| Practical popularity | Academic baseline | Engineering 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 ,” whereas the data comes from “the old policy ”; the two distributions differ and must be corrected with the importance-sampling ratio . If is too large, the variance explodes.
ACER solves this with a set of four components:
- Off-policy + experience replay: reuse historical data to improve sample efficiency;
- Truncated importance sampling: truncate to a constant to control the variance;
- Retrace: TD bootstrapping under off-policy accumulates bias (because the 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 ;
- TRPO-style constraint: impose a KL trust-region constraint on the Actor before updating , 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):
Using the identity , then introducing the behavior policy as the sampling distribution and defining the importance-sampling ratio , we obtain
This step is an identity transformation: appears in the sampling distribution and makes up for it in the numerator; multiplying the two exactly restores . So as long as 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 :
The expectation of its difference from the target (i.e., the bias) is
Only actions with 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 ( 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
When the two are added, and merge back into :
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 , 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 can be computed directly from the probabilities of and , and is looked up from the Critic, so only forward passes are needed and the sampling noise of 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 . First, when is the running product along a trajectory , 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, is an explicit bias–variance knob: a small gives low variance but more clipped parts (made up by the correction term), while a large approaches no clipping and high variance. The original paper uses for discrete actions; 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 , throwing away the 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 , and the correction term carries 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 , 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 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”:
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 , 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 dimensions and levels per dimension, the total number of actions is . A seven-degree-of-freedom manipulator with 21 levels per dimension has 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), 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:
Here is the state distribution “produced by following the deterministic policy ,” and is the action value under . Note the order of the two gradients: first take the gradient of 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 :
is an artificially introduced action-noise scale. As , this family of policies converges to the deterministic policy .
Step two: Write the log gradient of this family of policies. Differentiating with respect to , only the mean term contains :
(The derivative with respect to 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 becomes a spike concentrated near as .
Step three: Substitute into the stochastic policy gradient theorem and make a first-order Taylor expansion of . The stochastic policy gradient theorem gives
Expand at : . After substitution the first term is an odd function (expectation 0), and the second term is
because the covariance of the Gaussian is , , and 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 . At this point , the state distribution , , and the inner expectation collapses to the value at :
Step five: Three assumptions that cannot be omitted. For the derivation above to hold, we need: (1) is differentiable with respect to , and is bounded (Lipschitz) in a neighborhood of ; (2) is bounded; (3) the state distribution varies continuously with (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 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:
| Factor | Mathematical meaning | Intuition | Engineering meaning |
|---|---|---|---|
| The state distribution sampled by following | “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 | |
| The gradient of with respect to the action, evaluated at the current action | “Which way to twist this action so that becomes larger” | The Critic must concatenate the action at the input; the last layer cannot be “one output per discrete action” | |
| 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. 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 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 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 actually appears. The probability of a trajectory is
where the initial distribution and the transition probability are both independent of . Take the log derivative with respect to :
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 need not appear in the gradient—it has already been absorbed by .
Step two: Use the log-derivative trick to obtain the trajectory-level gradient.
Step three: Split by time step and use causality to isolate “future rewards.” Exchange the sum with the time index: only rewards after time depend on (rewards before are conditionally independent of given ):
And , so
Step four: This is exactly consistent with the chain-rule form of 13.3. Taking the limit for the deterministic policy, the expectation over actions collapses to the value at , and the role of is replaced by :
The “three factors” then each fall into place: determines “which states are weighted,” determines “which way to twist the action,” and determines “how this twist translates into a parameter update.” Remove any one of them: without the 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 one can only conclude , i.e., is orthogonal to constant functions, whereas is generally not zero ( 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 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 directly. When , is undefined and is the derivative of a 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 take the limit (the four steps of 13.2), rather than “doing a likelihood ratio on .” 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 .” 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 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 with respect to directly? You can, and that is exactly how it is implemented:
The two writings are completely equivalent. The only difference is implementation: writing it as “differentiating ” allows automatic differentiation to be called directly, by writing the Actor’s loss as (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):
| Dimension | Stochastic policy gradient (REINFORCE, PPO, SAC) | Deterministic policy gradient (DPG, DDPG, TD3) |
|---|---|---|
| Form of the policy output | A distribution , with parameters usually the mean and variance | An action , with parameters determining only the mean |
| Object of the expectation | State + action (double expectation) | State only (single expectation) |
| Action integral/sum | Requires sampling or integrating over actions, expensive in high dimensions | Degenerates into a single evaluation: |
| Source of the gradient | , unrelated to the gradient of | , must be back-propagated through the Critic |
| Exploration mechanism | The distribution itself is random (entropy, variance) | Noise must be attached externally (Gaussian noise, or an OU process, see 14.8) |
| Multimodal actions | Can express a bimodal distribution | Can output only a single point; a bimodal case averages into an invalid action |
| Data source | Usually on-policy (PPO, TRPO) | Naturally off-policy (behavior policy ≠ target policy) |
| Requirement on | Only needs to be able to evaluate | Must be differentiable with respect to , 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 , at deployment execute . 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 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 . 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 differs from the target policy , 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 at “the actions actually executed.” If the noise-free 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 at that point, and the 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 to be bounded and 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 outside the training distribution. clip is the lowest-cost protection; a better approach is to scale the network output to with (see the pitfall checklist in 14.7).
Segment 2 ④: The successor action in the target is , not . This is where DPG and DQN are most easily confused. DQN learns , and the target takes the maximum over the action dimension; DPG learns the value of the current policy , 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 ; 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. is a constant label computed from (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() .
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 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 is safer than hand-writing the chain rule. Expanding it gives
Automatic differentiation computes the path of “the action input,” with no need to hand-write dQ/da. But the premise is: must be frozen. If the Critic’s parameters are also handed to the same optimizer, the Actor’s objective will simultaneously push , the Critic will be pulled toward “making larger at that action” rather than “accurately estimating ,” and the value function immediately becomes distorted. The standard approach is to freeze the Critic with requires_grad_(False), or pass only 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., ); the Actor’s action gradient is back-propagated through the Critic and is noisier, so it usually uses a smaller step size (e.g., ). 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 that has not yet been learned accurately, showing up as -value jitter and policy oscillation.
Segment 4 ⑨: The value of the soft-update . The original DPG paper has no target network; in engineering the target-network idea of DQN is adopted uniformly. is often 0.001–0.005. Too large a (e.g., 0.1) means the target is always moving, and the stability benefit disappears; too small (e.g., ) means the target lags severely, learning slows down, and on tasks with very short episodes it shows up as “the value is persistently too low.” The criterion: observe the gap between the target and the online ; if it deviates monotonically over a long period, suspect 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:
| Quantity | Needs gradients? | Explanation |
|---|---|---|
| (Critic target) | No | Computed from and the two target networks; the whole segment is under no_grad |
| (Critic prediction) | Yes (with respect to ) | The Critic loss updates only |
| in the Actor loss | Yes (with respect to ) | The action is the Actor’s output |
| in the Actor loss | Yes for , no for | The 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
| Symptom | Possible cause | Fix |
|---|---|---|
| Actor parameters do not move at all | The Actor loss is wrapped in no_grad, the Critic is frozen and never unfrozen, or the action is detached | Check whether critic(s, actor(s)) has gradients; print the norm of dQ/da |
| The value rises monotonically and the policy degenerates | The target is not under no_grad, uses the online network, the termination mask is wrong | Put the whole target under no_grad; use terminated in both masks |
| All actions are the same early in training | No noise added, the noise scale is 0, or the replay buffer is too small | Scale the noise by the action range, with a buffer of at least |
| Actions jitter and jitters late in training | The Actor learning rate is not smaller than the Critic’s, is too large | Lower the Actor learning rate, |
| Actions on the real robot exceed the limits | The network output is not clipped | scaling + explicit clip + another clip in the low-level controller |
| It only learns in the early part of an episode | Truncation is treated as termination, bootstrapping is zeroed | Use terminated alone to control bootstrapping |
| It collapses when switching tasks | Observations are not normalized, reward scales differ greatly | Standardize 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 initialization | Small initialization of the output layer, normalize the action range by dimension |
The “monotonically rising value” item deserves a separate mention: the 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 value of 10⁴), that is overestimation, not successful learning. The criterion is to plot the actual episode return and the mean of 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:
- Continuous actions only. The theorem requires to be differentiable with respect to , and no such gradient exists for discrete actions.
- The overestimation of a single Critic cannot self-heal. Updating a deterministic policy is equivalent to locally maximizing , and the function-approximation error is systematically amplified upward.
- 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.
- 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 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):
| Gap | DPG’s approach | DDPG’s remedy |
|---|---|---|
| Data correlation | Online updates, samples discarded after one use | Experience replay buffer with random mini-batches |
| Unstable bootstrapping | The online Critic is used in the target | Target network + soft updates |
| Expressive power | Linear / shallow function approximation | Deep networks (one each for Actor and Critic) |
| Inconsistent input scales | Manual feature scaling | Batch 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, 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:
| Source | What it takes | Which DPG problem it solves |
|---|---|---|
| DPG (Silver 2014) | The deterministic policy gradient theorem, the two-network Actor-Critic structure | The action-integral problem of high-dimensional continuous actions |
| DQN (Mnih 2015) | Experience replay buffer, target network, off-policy TD learning | Correlated samples, divergent bootstrapping, data used only once |
| Batch Normalization (Batch Normalization, BN) | Standardizing the input of each layer | Observations 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:
| Component | Notation | Input | Output | Role |
|---|---|---|---|---|
| Actor (online) | State | Action (continuous, -dimensional) | The target policy; only this one is used at deployment | |
| Critic (online) | State and action concatenated | Scalar Q value | Points the way for the Actor, and also estimates value | |
| Actor (target) | State | Action | Used only to compute the Critic’s target | |
| Critic (target) | State and action concatenated | Scalar Q value | Used only to compute the Critic’s target | |
| Replay buffer | — | Transitions | 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, 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 to and then map it linearly to :
Note the side effect of : when is large, saturates and its derivative tends to 0, so the gradient along the chain is flattened. Therefore the output layer should use a small initialization (e.g., a uniform distribution on ), and early in training one should monitor whether a large fraction of the inputs fall into the saturation region.
14.3 Two losses and the soft update
The Critic’s loss (regressing onto a constant label):
Here is the mask of true termination (not truncation). The whole of is a constant and must not carry gradient.
The Actor’s objective (maximize the score given by the Critic):
The soft update (Polyak averaging):
is usually taken as 0.001–0.005.
Why a soft update instead of a hard copy? A hard copy ( every steps) makes the target network jump periodically: at every jump, the Critic’s target 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 ? Because automatic differentiation does the chain rule for you:
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 ( 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
with respect to ; only the prediction term contains :
Substituting into gradient descent gives
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 must have its gradient cut off: if also contained derivatives with respect to , the formula above would gain an extra term , and the sign of the error would be polluted; in the extreme case (target and prediction sharing the same network) , 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
treating as a constant; only the action-input path remains:
If the action then passes through and an affine scaling , the chain rule must multiply one more diagonal Jacobian:
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 , and that factor itself changes during training (it tends to 0 when 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 repeatedly and expanding into an explicit weighted sum:
The weights satisfy , so it really is “a probability-weighted average over the history of parameters”, with weights decaying exponentially as and a time constant of about steps (about 200 steps when ). 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 steps, zero earlier”, and at every refresh the target is first-order discontinuous, so jumps as a whole; the soft update spreads that jump into an exponential tail, and the rate of change of is limited to about per step.
Step four: why is the “stability versus lag” knob. The longer the effective window , 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 . 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 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 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 the Critic learns is misaligned with the true state.
Segment 1, ②: the a_t stored in 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 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 – 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 with the online networks → the target moves with the parameters, which is equivalent to having no target network;
- applying
.detach()only to 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
detachonly to while forgetting that also needs no gradient → the Critic backpropagates through the target network to , and is a weighted copy of , 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 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:
If it is written as “first and then ”, 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 to , 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. is usually set to 1%–10% of the initial value.
14.6 Gradient flow and detach: the complete checklist for DDPG
| Quantity | Does it need gradient? | Which loss it belongs to | Explanation |
|---|---|---|---|
| (Critic target) | No | Computed from , , and ; the whole thing is under no_grad | |
| (Critic prediction) | Yes (with respect to ) | Only the online Critic is updated | |
| (target Q) | No | The target network is a constant copy | |
| (target action) | No | Same as above | |
| (Actor output) | Yes (with respect to ) | The action is the Actor’s output | |
| (the Q in the Actor loss) | Yes for , no for | Freeze ; 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:
loss_a.backward()accumulates gradients for the Critic’s parameters (even withrequires_grad=Falsethe 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 formq.requires_grad_(False).- The default reduction of
smooth_l1_lossismean, consistent with the in the pseudocode; when hand-writing(y-q)**2, do not forget.mean(). - 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:
| Symptom | Possible cause | Fix |
|---|---|---|
| The Q value explodes and the policy degenerates | The target is not under no_grad, the target uses the online network, the termination mask is missing | Put the whole target under no_grad; use the target networks; multiply by terminated |
| The Actor does not learn and the action hardly changes | The Critic is wrapped in no_grad, or the shared backbone is frozen, or saturates | Check the gradient along the action path; separate the networks; small initialization of the output layer |
| Periodic spikes in the Q loss | The soft update was written as a hard copy, or is too large | Update in place as , with |
| Completely random early in training, sudden collapse later | Insufficient warm-up, noise decaying too fast | Warm up for steps; keep at 1%–10% |
| Good only within the training distribution, collapses on a new state | The replay buffer is too small, insufficient exploration | Buffer ; add noise or switch to an OU process |
| Actions on the real robot exceed the limits and jitter | The output is not clipped, the noise is not clipped | + linear map + clip; another limit in the low-level controller |
| It collapses when switching tasks, huge differences across seeds | Observations are not normalized, reward scales differ | Normalize observations with running mean/variance; scale rewards; fix 3–5 seeds |
| Memory keeps growing | The soft update is not under no_grad, or the buffer stores tensors that carry gradients | Put 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 episode | Truncation is treated as termination | Use only terminated to control bootstrapping |
| The Critic learns fast but the Actor oscillates | The Actor learning rate is not smaller than the Critic’s, or the update order is reversed | Update the Critic first; set to 1/5–1/10 of |
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:
| Hyperparameter | Typical value | Symptom when set wrong | Direction of adjustment |
|---|---|---|---|
| Actor learning rate | Policy oscillation, Q jitter | 5–10 times smaller than the Critic’s | |
| Critic learning rate | Q does not learn or overshoots | Tune this one first, then the Actor | |
| Soft update | 0.005 | Spikes (too large) / lag (too small) | 0.001–0.005; shorter tasks take smaller values |
| Batch size | 64–256 | Too much gradient noise / updates too slow | Use 256 when the observation dimension is high |
| Replay buffer | Overfits recent data | At least 10 times the single-episode length × batch size | |
| Discount | 0.99 | Myopia / Q value explodes | 0.99 for long-horizon tasks; 0.95 is acceptable for very short episodes |
| Noise | 10% of the action range | No exploration / cannot learn | Scale by action dimension and physical range |
| Update-to-sampling ratio | 1:1 | Low sample efficiency / overfitting | Can be raised to 2:1, but too high overfits |
| Warm-up steps | – | Early collapse | At least 10× the batch size |
How to choose the noise process? Two common choices:
- Gaussian noise: , 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): , 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 (, ). 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 , 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):
| Pathology | Mechanism | Consequence | Patch (see Chapter 15) |
|---|---|---|---|
| Q overestimation | A single Critic, and the target takes “the point given by the policy” over actions; function-approximation error is systematically amplified | Inflated Q values; the policy exploits the error | Twin critics taking the minimum |
| Actor and Critic updated in sync | The Actor chases a Q that is not yet learned accurately at every step | Policy oscillation, accumulated variance | Delayed policy updates (once every 2 steps) |
| The target action is a single point | is evaluated at one point; if Q has a spike there, the target is polluted | Unstable targets, spikes in Q | Target 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 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:
| Patch | Name | Mechanism in one sentence | Which disease it treats |
|---|---|---|---|
| One | Clipped double Q (clipped double Q) | Train two independent Critics and use in the target | The overestimation of a single Critic |
| Two | Delayed policy update (delayed policy update) | Update the Actor only once every Critic updates | The Actor running after a Q that is not yet learned accurately |
| Three | Target policy smoothing (target policy smoothing) | Add clipped noise to the target action | The single-point 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 → update the Actor with the 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 : actions with positive error are more likely to be selected, so the estimate is systematically too high. DDPG has no explicit , but the Actor’s output is itself “the action that makes largest”, which amounts to an implicit 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 ), 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 is to 1, the closer the amplification factor of this loop is to .
(3) High variance of the target. is a value taken at one point. If 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 and with identical structure and independent parameters; both regress onto the same target, but the value inside the target is the smaller of the two:
Here is the termination flag (1 for true termination, 0 for truncation or non-termination), and is the smoothed target action discussed in the next section. The Actor is updated using only the first Critic: .
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 and the estimate be , where is a zero-mean approximation error (independent across actions, with variance ). Take the maximum over the candidate action set :
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
Equality holds only when the error is constant (no randomness). The more candidates and the larger , 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 , 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 enters the target, it is further overestimated as the baseline for the next step. Expanding shows that the bias accumulates as . With this is about a factor of 100—this is why overestimation is especially deadly on long-horizon tasks.
Step four: why works. The of two independent errors satisfies
i.e., is biased downward. So TD3’s use of 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 exactly”, the trade is worthwhile.
Step five: why the two Critics must be independent. If the two Critics share all parameters, , 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 version.
15.3 Patch two: delayed policy updates
The approach: the Critic is updated every step, while the Actor is updated only every steps (with by default), and the target networks are soft-updated together only when the Actor is updated.
Why: the Actor’s gradient is , which directly depends on the shape of . If 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 —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
The direction is entirely determined by “the gradient of the current Critic along the action dimension”. If differs from the true by , then the error in the direction is —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 ( being a constant related to the feature covariance); each Actor update moves the parameters by . 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 does not decrease monotonically with —the Actor chases a target that moves at its own speed. If the Actor moves only once every steps, then between two Actor updates the Critic has already converged more steps, and the error the Actor faces shrinks to roughly the order of ( 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 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 , so under the “one update per environment step” setting the rate of policy improvement drops by roughly a factor of and the number of interaction steps needed for convergence rises; at the same time, the larger is, the older the Q the Actor uses (lagging by steps) and the more outdated the direction of policy improvement. is the empirical compromise: it lets the Critic lead by one step without letting the Actor fall noticeably behind. With or more, the return curve typically shows a markedly longer plateau.
Note: the 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 directly; add a small amount of noise around it and clip:
By default and (when the actions are normalized to ). Note that here there are two layers of clipping: first the noise magnitude is clipped to , 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 has a spike caused by error near , 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 , forcing to become flat near the target action—and a flat is exactly the kind of the Actor can exploit stably: when the Actor moves along 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 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 ; the perturbed target action and the label are
Ignore for now the outer clipping by the “action range”, and suppose is symmetrically distributed on with variance . Taking the expectation over the noise:
Step two: do a second-order Taylor expansion at . Expand to second order:
After taking the expectation, the first-order term vanishes by symmetry , leaving
where 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 (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 , forcing it to flatten near the target action.
Step three: why this exactly suppresses “spikes being fed back”. The Critic uses as the regression label. If has a narrow spike at caused by approximation error, then without smoothing 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 . This divides the labor differently from the in 15.2: 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, still holds, but the second moment grows without bound as increases, and the Taylor expansion fails far away from —there is entirely extrapolated, the “curvature” in the expansion is fabricated by the network, smoothing samples meaningless low values, and is systematically pulled down. Clipping restricts the integral to a neighborhood that “has data and where is trustworthy”; and symmetric clipping still preserves , 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”. pushes the estimate downward (downward bias), and smoothing further suppresses spikes (reducing variance); together they make slightly conservative with a flatter shape. Conservative plus flat is exactly the terrain the Actor wants when walking along : 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 actually executed after clipping, not 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: (patch one), the noise and double clipping of (patch three), and rather than (the target networks). This block must be completed inside no_grad, and the whole of must be used as a constant.
⑤ Both Critics use the same . Note that the two losses share the same ; they are not allowed to compute their own (e.g., each using its own or its own ), 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 . This is the choice of the original paper, for the reason that is already part of the in , and making the Actor optimize both Critics at once would weaken the debiasing effect of the . 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 would run through 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 in t % d == 0 is the environment step count, not the episode count and not the gradient step count. The soft update uses : 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 ( zeroes the bootstrapping term); on time truncation (e.g., forced reset upon reaching the step limit) 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.
| Quantity | Appears in | Detach? | Consequence of not cutting it off |
|---|---|---|---|
| The whole target | Critic loss | Required (no_grad) | The target moves with the parameters being optimized, the loss is always 0, and the Critic learns nothing |
| (with noise) | Inside | Required | The noise gradient backpropagates into the target networks, and the target networks are driven by noise |
| Inside | Required (the target network itself has no gradient) | Same as above | |
| Inside | Required (target network parameters) | The target changes in sync with the online networks and the bootstrapping loop closes | |
| Actor loss | Must not detach | The Actor gets no gradient at all and its parameters never update | |
| The parameters of | Actor loss | Must 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
| Pitfall | Symptom | Correct practice |
|---|---|---|
| The two Critics share all parameters | Double Q degenerates to single Q and overestimation remains | Fully independent, or share only the feature layers and accept a discounted effect |
| Taking also during training before regressing | Both Critics are pulled to the same shape by the same , and independence is lost | is used only to construct ; in training each regresses its own output |
| The target smoothing noise is not clipped | The target action runs into regions without data and Q becomes extrapolation noise | Clip the noise with first, then clip back to |
| The smoothing noise scale is set too large | The target is too conservative, learning is extremely slow or does not happen at all | Start from , ; 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 random | Use the environment step count t % d == 0 |
| The Critic is not frozen during the Actor update | The 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 form | Memory explodes, or the target networks never move at all | with torch.no_grad(): p.mul_(1-tau).add_(p_src, alpha=tau) |
| The exploration noise is not clipped to the action range | The executed action is out of bounds and the environment’s behavior does not match the stored data | Clip the sampled action, then execute, then store |
| Truncation is treated as termination | A spurious dip in value near the time boundary | The terminated mask is 1 and the truncated mask is 0 |
| The reward magnitude is not scaled | The Q value magnitude is too large, the Huber threshold becomes ineffective, and the gradient scales are mismatched | Normalize the rewards and let all losses use the same scaled Q |
| Insufficient warm-up | Early in training Q bootstraps onto itself and diverges immediately | Warm 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
| Dimension | DDPG | TD3 |
|---|---|---|
| Number of Critics | 1 | 2 (the target takes the ) |
| Target action | clipped noise | |
| Actor update frequency | Every step | Every steps |
| When the target networks update | Soft update every step | Soft update in sync with the Actor update |
| Tendency to overestimate | Pronounced | Suppressed by (slightly underestimated) |
| Implementation increment | — | One extra network + one if |
| Typical behavior | Sensitive to hyperparameters, Q values often inflated | More stable, less sensitive to random seeds |
Reference default hyperparameters (continuous control, actions normalized to ):
| Hyperparameter | Common value | Explanation |
|---|---|---|
| 0.99 | Same as DDPG | |
| 0.005 | Soft-update coefficient; the smaller, the more stable the target | |
| Batch size | 256 | 256–1024 |
| Actor / Critic learning rate | / | Both Adam |
| Target smoothing noise / clipping | 0.2 / 0.5 | Values from the original paper |
| Policy delay | 2 | Too large (e.g., 4) and the Actor stops learning |
| Exploration noise | 0.1 with decay | Gaussian; 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 to a “soft maximum”, exploration changes from “attached noise” to “built into the policy itself”, and the temperature coefficient 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 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 ( 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):
is the temperature coefficient (temperature), controlling the weight of “entropy” relative to “reward”: as it degenerates to the ordinary return, and as it becomes a purely random policy. Note that the entropy is discounted by 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:
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 has one extra subtracted term —“the entropy cost that must be paid for choosing this action”. The more deterministic the policy (with close to 1 on some action and ), 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
Here is the simplex (the set of all valid probability distributions). The 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 with the multiplier :
Take the variational derivative with respect to and set it to zero (note that ):
Rearranging gives
The second factor does not depend on and is merely a normalization constant. So the optimal policy is proportional to —this is exactly the Boltzmann distribution (Boltzmann distribution): the higher is, the larger the probability of the action, and the larger 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 . Substituting into the definition of , with normalization constant , gives
For continuous actions the sum becomes an integral:
This expression is a smooth version of : as it degenerates to (a limit property of log-sum-exp), and the larger 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:
Step four: why the entropy in the objective must be discounted. Without the , 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 , of the same order as the return, so the objective is bounded and coincides with the classical return at .
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 ) 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 , the same idea as TD3):
Note two details: ① the action in the target is sampled from the current policy , 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 , and the whole thing is computed under no_grad.
(2) The Actor loss (maximizing “Q minus entropy cost”). The Actor maximizes , written as a minimization:
The directions of the two terms must be distinguished: pushes the action toward high-value regions; penalizes “being too certain” ( 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 must be treated as a constant during backpropagation (it does not participate in the derivative with respect to ), otherwise the temperature is dragged along as well.
(3) The temperature loss (automatic adjustment of ). The target entropy is usually taken as (the negative of the action dimension), and the loss is written as
Its role is intuitive: writing the policy entropy as , the gradient of with respect to is . When the policy is more deterministic than the target entropy (), the gradient is negative, increases and the policy becomes more random; when it is more random than the target entropy (), the gradient is positive, 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 has its gradient cut off, so
Note that appears only inside 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 . This is consistent with the reasoning in 15.2— 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
Differentiating with respect to gives
The two paths have different origins:
- In the entropy term, explicitly contains (the Gaussian density contains , plus the Jacobian correction of ), so it is differentiated directly with respect to without passing through the action.
- In the value term, has no explicit dependence on and can only pass through : . This is the “path gradient”, and it is also the source of SAC’s lower variance compared with a likelihood-ratio estimate ( 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”. is minimized, and is a probability density and is usually negative on its support; minimizing means making more negative, i.e., lowering the density at the sampled point and spreading the probability mass out, so the entropy rises. The larger is, the more dominant this term and the more random the policy—consistent with the intuition that ” is the temperature”.
Step four: why in the Actor term must be a constant. If were also allowed to participate in the derivative with respect to , would be pushed down along the direction of “minimizing ” (because when the objective decreases as 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 . In implementation this is alpha.detach(); at the same time in the Critic target is also a constant (the target as a whole is under no_grad), and is an optimized variable only in the temperature loss.
Step five: the gradient of the temperature loss with respect to . Parameterizing with and gives
where has already been cut off (logp.detach()), so the gradient flows only to . The parameterization has three advantages: is automatically satisfied; the gradient carries a factor , which is equivalent to stepping on a “relative change” scale (a large absolute step when is large, a small one when it is small), so it does not diverge because of magnitude differences; and corresponds to , 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 ), the Actor term is a linear combination of and (magnitude ), and the temperature term is multiplied by a logarithm (magnitude ). The three magnitudes differ, yet they are often given the same learning rate —this is the common reason why “SAC trains unstably under some reward scales”. The robust approach is to normalize the rewards first, so that and 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):
Why reparameterize? If one sampled directly from and then computed the gradient, the sampling operation itself would not be differentiable and the gradient could not be backpropagated to . Reparameterization “moves” the randomness onto , which is independent of the parameters, so becomes a deterministic differentiable function of 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 -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 , , and is invertible, then
Taking logarithms:
Step two: the Jacobian of is diagonal, dimension by dimension. Since ,
Therefore
That is:
Step three: what happens if this term is not subtracted. compresses the whole real line into , so an action near the boundary corresponds to infinitely many , and the probability density is “squeezed”. Not correcting for this is equivalent to using the Gaussian density in -space as the density in -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 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 , or directly 2*(log(2) - u - softplus(-2*u))).
16.5 Automatic adjustment of the temperature
Why automatic adjustment is needed: hand-tuning is extremely sensitive. For tasks with different reward magnitudes, the optimal differs by several orders of magnitude; and 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 solve for itself”.
The line of reasoning: treat as an optimization variable as well, and solve the constrained problem
Differentiating with respect to gives
The direction of gradient descent is therefore:
- if the policy entropy is greater than the target entropy (the policy is too random), the gradient is positive → decreases → the weight of the entropy term shrinks → the policy tightens;
- if is less than (the policy is too deterministic), the gradient is negative → increases → the weight of the entropy term grows → the policy becomes more random.
In other words, pulls the policy entropy toward the target entropy . The default 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 is often parameterized as ” + exponential mapping” to guarantee it is always positive, and is given its own Adam optimizer.
One easy mistake: 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 ); in the Critic target it is also a constant; only in the temperature loss is it an optimized variable. Mixing up the three gives 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 is its multiplier. Maximum entropy policy optimization can be written as a constrained problem:
The Lagrangian is
is the Lagrange multiplier of this entropy constraint, and its non-negativity comes from the constraint direction being "". This step shows that is not a weight set by hand but “the price that must be paid to reach the target entropy”.
Step two: optimizing over gives the Boltzmann distribution, and the stationary point in gives “entropy equals target entropy”. The former is the result of step two in 16.2, . The latter:
So at the optimum we must have —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 , and the gradient can be read off directly with the envelope theorem. Define the dual function ; the dual problem is . Because the inner layer has already been optimized over , , hence
This is the envelope theorem (envelope theorem): when taking the total derivative one need not expand how changes with , because the coefficient of that term is exactly the zero gradient of “the inner layer already optimal”. So the direction of ‘s gradient descent is entirely determined by “the difference between the current entropy and the target entropy”: if the entropy is too large, decreases; if too small, increases.
Step four: SAC v2’s loss is exactly this dual function. Expanding :
So “minimizing ” and “solving the dual problem” are the same thing. Note that in implementation must be detached: this precisely removes the term ” changes with ”, which is equivalent to enforcing the envelope theorem. With detach, ; without detach there is an extra term , the minimum of is no longer “entropy equals target entropy”, and converges to a value that deviates from the target.
Step five: the properties of . 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 . It must be changed when the action dimension changes; and when the reward is rescaled substantially, even if stays fixed the optimal changes markedly (because the magnitude of changes, and with it the ratio between the entropy term and the reward term).
Step six: why needs its own learning rate, usually smaller than the Critic’s. appears in the Critic’s target, so as soon as moves, the target shifts as a whole and must chase it again; then as changes the entropy changes again and moves again—this is a closed loop. The gain of the loop is proportional to ‘s learning rate, so it must be small enough (often 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 , 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 it is (and since , 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 . For the same reason as TD3, to suppress overestimation. Note that the acts only when constructing the target; when training the two Critics, each regresses separately. A common variant uses the only in the Actor loss while the target uses the average; different pairings markedly affect the learning speed.
⑤ The target action 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 in the target use the current . This makes the stability that was provided by “the target policy lagging” compensated by ” 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 , and the two terms are not symmetric. The gradient of is backpropagated through (the path gradient), while the gradient of goes directly to (because it explicitly depends on 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 . Gradient descent directly on may overshoot zero in one step and become negative, making “the entropy reward work in reverse”. guarantees positivity, at the cost that the learning rate must be reinterpreted on the scale of (when , ).
⑧ 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 ; 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 is enough; but if the entropy term is written outside the bootstrapping term (e.g., as ), 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.
| Quantity | Appears in | Cut off? | Consequence of not cutting it off |
|---|---|---|---|
| (including and ) | Critic loss | Required (no_grad) | The target drifts with the parameters and the Critic learns nothing |
| , | Inside | Required | The target networks/policy are driven backward by the objective |
log π (the second factor of the Actor term) | Temperature loss | Must detach | The gradient of would also modify the Actor, and the two pull against each other |
| Actor loss | Treated as a constant (detach) | The temperature is pushed down directly by the “maximize entropy” objective and loses its regulatory meaning | |
| Actor loss | Must not detach (with respect to ) | The Actor gets no gradient at all | |
| The parameters of both Critics | Actor loss | Must be frozen with requires_grad=False | The 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
| Pitfall | Symptom | Correct practice |
|---|---|---|
| Forgetting the tanh Jacobian correction | Entropy overestimated, action stuck at for a long time, learning stalls | Subtract in |
| The sign of the entropy term in the soft target is reversed | The policy collapses late in training, performance rises and then collapses | The target is |
| enters the Actor loss without detach | is pulled toward 0 by “maximize entropy” and loses its regulation | alpha.detach() in the Actor loss |
log π is not cut off in the temperature loss | and the Actor pull against each other and the entropy runs out of control | logp.detach() in the temperature loss |
| is parameterized linearly | A negative temperature appears during training and the entropy term works in reverse | Use log_alpha + exp |
| The target entropy is set too large (e.g., $-2 | \mathcal{A} | $) |
| The Critic uses the average instead of the (or the two are mixed) | Overestimation reappears, or learning is too slow | Take the 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 invalid | The Critic must take the concatenation |
| Forgetting to freeze the Critic parameters | The Critic is directly modified by the Actor’s objective and Q diverges | Freeze the parameters, borrow only the gradient |
Computing after tanh when sampling from the policy | The density conventions are inconsistent and the entropy estimate is biased | Compute the Gaussian density uniformly in -space, then apply the Jacobian correction |
| Still sampling from the policy at deployment | The action jitters in the same state and is not reproducible | Deploy with (the mean action), or fix the random seed |
| Treating truncation as termination | A dip in value appears at the time boundary | terminated=1, truncated=0 (same as TD3) |
16.10 Comparison with PPO / DDPG / TD3 and scope of application
| Dimension | PPO | DDPG | TD3 | SAC |
|---|---|---|---|---|
| Data source | On-policy (large parallel batches) | Off-policy + replay | Off-policy + replay | Off-policy + replay |
| Policy form | Stochastic (Gaussian/categorical) | Deterministic + attached noise | Deterministic + attached noise | Stochastic (Gaussian compressed through tanh) |
| Exploration source | Policy distribution + multiple environments | Noise scale (hand-tuned) | Noise scale (hand-tuned) | Entropy regularization + automatic |
| Multimodal actions | Supported | Not supported | Not supported | Supported |
| Suppression of overestimation | Not explicitly handled | None | Double Q taking the | Double Q taking the |
| Objective | Clipped return | Pure return | Pure return | Return + entropy |
| Main hyperparameter risks | , number of epochs, KL early stopping | Noise scale, learning-rate ratio | Smoothing noise, delay steps | Target entropy, learning rate |
| Deployment determinism | Take the mean | Naturally deterministic | Naturally deterministic | Take the mean |
| Sample efficiency | Low | High | High | High |
| Typical failure | Too large a step collapses the policy | Q inflated, Actor does not move | Smoothing noise too large, no learning | Jacobian/sign written wrong, 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:
The two share “double Q taking the + 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
| Algorithm | Type | Does it need a model? |
|---|---|---|
| Dynamic programming (DP) | Model-based planning | Yes |
| Monte Carlo (MC) | Value prediction | No |
| Temporal difference TD(0) | Value prediction | No |
| Q-learning | Value control | No |
| DQN | Value control | No |
| REINFORCE | Policy gradient | No |
| A2C | Actor-Critic | No |
| A3C | Actor-Critic | No |
| GAE | Advantage estimator | No |
| TRPO | Actor-Critic | No |
| PPO | Actor-Critic | No |
| ACER | Actor-Critic | No |
| DPG | Deterministic policy gradient | No |
| DDPG | Deterministic policy gradient + deep network | No |
| TD3 | Stability upgrade of DDPG (twin critics, delayed updates, target smoothing) | No |
| SAC | Objective-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):
| Scenario | First choice | Reason |
|---|---|---|
| Discrete actions, observable states, offline reuse of data | The 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 TD3 | The policy outputs the action directly, so no over continuous actions is needed |
| Large-scale parallel simulation, limited tuning budget | PPO | On-policy + parallelizable sampling + clipped bounds, and the default hyperparameters are already stable enough |
| A monotonic-improvement guarantee is required for every step | TRPO | Hard KL constraint + line search, at the price of a second-order solve |
| The cost of trial and error on real hardware is extremely high | Model-based reinforcement learning / world models | “Imagine” trial and error inside a learned model; not expanded on in this article |
Three frequent pitfalls:
- Every place that takes a 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 . Whenever you see “take the maximum”, ask: will the estimation noise here be amplified?
- Termination and truncation in GAE must be kept separate. True termination must cut off bootstrapping; time-limit truncation must keep bootstrapping; both the mask and the 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).
- 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: learning rate, discount factor, reward, state value, action value, advantage, stochastic policy, deterministic policy.
18.1 Value-based methods
| Algorithm | Objective policy (what is learned) | Core update formula |
|---|---|---|
| DP (policy evaluation) | State value of a given policy | |
| DP (value iteration) | Optimal state value (implies the optimal policy ) | |
| MC (first-visit / every-visit) | State value (approximated by the mean of sampled returns) | , where Returns collects the return of each visit |
| TD(0) | State value (online bootstrapped estimate) | |
| Q-learning | Optimal action value (the policy takes ) | |
| DQN | Optimal action value (approximated by a neural network) | , |
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
| Algorithm | Objective policy (what is learned) | Core update formula |
|---|---|---|
| REINFORCE | Stochastic policy (maximize the expected return ) | |
| A2C | Stochastic policy + value baseline | , where is the -step advantage |
| TRPO | Stochastic policy (KL trust-region constraint) | , s.t. |
| PPO | Stochastic policy (clipped surrogate objective that limits the update magnitude) | |
| ACER | Stochastic policy (off-policy, truncated importance sampling + Retrace) | ; Retrace computes |
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 weighted by the advantage → limit the update magnitude with a trust region (KL / clipping).
18.3 Deterministic-policy methods
| Algorithm | Objective policy (what is learned) | Core update formula |
|---|---|---|
| DPG | Deterministic policy + critic | Actor: $\theta\leftarrow\theta+\alpha_\theta\nabla_\theta\mu_\theta(s)\cdot\left.\nabla_aQ^w(s,a)\right |
| DDPG | Deterministic policy + target networks + replay | ; , |
| TD3 | DDPG + twin critics + delayed updates + target smoothing | , ; the Actor is updated once every steps |
| SAC | Maximum-entropy stochastic policy (double Q + reparameterization + automatic temperature) | ; , |
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 → softly update the target networks.
Every algorithm answers three questions: what is learned (, , 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
| Algorithm | What is learned | Data source | Action space | Key stabilization means | Main weakness | Typical use case |
|---|---|---|---|---|---|---|
| Dynamic programming (DP) | or | Known model, no sampling needed | Discrete | None (exact iteration) | Requires the full and , and states must be enumerable | Planning problems with few states and known transitions (board games, queueing, inventory) |
| Monte Carlo (MC) | On-policy, requires complete episodes | Discrete or continuous | Sample mean, first-visit | Must wait for the episode to end; large variance | Value prediction with short episodes and controllable return variance | |
| Temporal difference TD(0) | On-policy, online single step | Discrete or continuous | Bootstrapping + step size | Large bias, sensitive to initialization | Value prediction for continuing tasks without termination | |
| Q-learning | Off-policy, any behavior policy | Discrete | target + step size | Tabular dimensionality explosion, maximization bias | Small-scale discrete control, teaching demonstrations | |
| DQN | Off-policy, experience replay | Discrete | Experience replay + target network + termination mask | Supports discrete actions only; Q-value overestimation | Atari-style discrete control, scheduling and recommendation | |
| REINFORCE | On-policy, complete trajectories | Discrete or continuous | Baseline subtraction (optional) | Extremely large variance, lowest sample efficiency | Teaching, minimal continuous-control prototypes | |
| A2C / A3C | and | On-policy, parallel sampling | Discrete or continuous | Advantage baseline + parallel environments | Sensitive to step size; data used only once | Parallel simulation environments, quick algorithm validation |
| GAE (a component, not a standalone algorithm) | Advantage estimate | Follows the host algorithm (usually on-policy) | Not involved | trades off bias and variance | Termination and truncation masks are easy to get wrong | Advantage estimation for every Actor-Critic style algorithm |
| TRPO | On-policy | Discrete or continuous | Hard KL constraint + conjugate gradient + line search | Second-order solve is expensive; complex implementation | Small and medium networks that need a “no degradation at every step” guarantee | |
| PPO | and | On-policy (the same batch is reused for several rounds) | Discrete or continuous | Clipping + GAE + advantage normalization + KL early stopping | The soft constraint can still be violated; the approximate KL must be monitored | Large-scale parallel simulation, RLHF (Reinforcement Learning from Human Feedback), robot control |
| ACER | and | Off-policy + experience replay | Discrete or continuous | Retrace value estimation + truncated importance sampling | The most complex implementation, the most hyperparameters | Real hardware or expensive environments where old data must be reused |
| DPG | Deterministic policy and | Off-policy | Continuous | Deterministic policy + the Critic passing the action gradient back | Insufficient exploration, deviates from policy-based methods | Algorithm prototypes and theoretical validation for continuous control |
| DDPG | and | Off-policy + experience replay | Continuous | Target networks + soft updates + action-noise exploration | Sensitive to hyperparameters, Critic overestimation | Single-task continuous control with moderate state dimension |
| TD3 (see Chapter 15) | Deterministic policy and | Off-policy + experience replay | Continuous | Twin critics taking the + delayed policy updates + target policy smoothing | Exploration still needs external noise; cannot express multimodality | Single-task continuous control, real-hardware manipulation, scenarios requiring deterministic deployment |
| SAC (see Chapter 16) | Maximum-entropy stochastic policy and | Off-policy + experience replay | Continuous | Twin critics + entropy regularization + reparameterization + automatic tuning of | The three losses and the tanh Jacobian are easy to get wrong; the target entropy must be tuned | Real-hardware grasping, assembly, dexterous hands, multimodal continuous control |
Three things to notice when reading this table:
- “What is learned” determines the applicable action space. Whenever the objective contains an 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).
- “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.
- 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 ; policy-based methods output the action distribution directly and rewrite the probabilities by gradient ascent.
| Point of divergence | Value-based (Q-learning, DQN) | Policy-based (REINFORCE, PPO) |
|---|---|---|
| Action selection | Explicit | Sample from |
| Continuous actions | Requires the global maximum over the action space, which is costly | The network outputs the mean and variance directly, so it is naturally supported |
| Stochasticity | The policy itself can be a deterministic greedy rule | The policy is stochastic by construction, so exploration is more natural |
| Data efficiency | Can be off-policy and can replay | Usually on-policy, with low data utilization |
| Convergence properties | The target is fixed (), but it suffers from maximization bias | The 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
| Dimension | Stochastic policy | Deterministic policy |
|---|---|---|
| Source of exploration | The policy distribution itself (entropy, sampling) | Action noise must be attached externally (DDPG uses Ornstein–Uhlenbeck or Gaussian noise) |
| Multimodal actions | Can 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 path | Take the gradient with respect to , independent of the action value | Take the gradient of the Critic with respect to the action, which requires to be differentiable in |
| Typical algorithms | REINFORCE, A2C, PPO, SAC | DPG, 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 , 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 inside , 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:
| Estimation method | Bias | Variance | When it is biased |
|---|---|---|---|
| One-step TD target | Large (depends on the estimation error of the current ) | Small | When the value function is already fairly accurate |
| -step return | Medium | Medium | When a compromise is needed and episodes have a definite length |
| Complete return | None | Large | When episodes are short and rewards are dense |
| GAE ( interpolation) | Continuously adjustable through | Continuously adjustable through | The standard practice for Actor-Critic style algorithms |
The interpolation formula of GAE:
Criterion: trusts bootstrapping more (stable but biased); trusts the true return more (accurate but noisy). Continuous control commonly uses ; 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.
| Dimension | Model-free | Model-based |
|---|---|---|
| Sample efficiency | Low (especially on-policy) | High; one real interaction can be reused repeatedly by “imagining” |
| Asymptotic performance | High, not limited by model error | Limited by model error; long-horizon predictions become distorted |
| Implementation difficulty | Medium | High (the model and the policy must be trained together, and model bias must be handled) |
| Applicable scenario | Simulation is cheap and can be parallelized at scale | Real 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 constraint | First choice | Alternative | What not to choose |
|---|---|---|---|
| Ample compute, parallelizable environments, stable reproduction desired | PPO | A2C (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 methods | REINFORCE, A2C (on-policy, lowest sample utilization) |
| Limited tuning manpower, few hyperparameters required | PPO | DQN (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:
- 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.
- Using DQN for continuous actions. The DQN target contains , 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).
- 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.
- 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 , approximating 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 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 —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 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 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 or , policy-based methods estimate it with 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 solve | Means | Where it appears |
|---|---|---|
| A single update step is too large and the policy collapses | Limit the step size: hard KL constraint, soft clipping constraint, trust region, line search | TRPO, PPO, ACER |
| The gradient variance is too large to learn | Reduce the variance: baseline, advantage, GAE, return normalization, entropy regularization | REINFORCE, A2C, PPO, SAC |
| The data are highly correlated and training is unstable | Decouple the correlation: experience replay, target networks, soft updates, parallel sampling | DQN, 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 axis | Leaning left | Leaning right | Knobs |
|---|---|---|---|
| Bias ↔ variance | One-step TD, small , small | Complete return, large , large | GAE’s , PPO’s , the of -step returns |
| Sample efficiency ↔ stability | On-policy, each piece of data used once | Off-policy, replay reuse, importance-sampling correction | Replay buffer size, the number of epochs each batch is reused for |
| Exploration ↔ exploitation | Strong entropy regularization, large noise, large | Weak entropy regularization, small noise, greedy | SAC’s , DDPG’s noise scale, the of -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 , 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
| Abbreviation | Full name in English | Explanation |
|---|---|---|
| AC | Actor-Critic | Actor-Critic (a policy network plus a value network) |
| ACER | Actor-Critic with Experience Replay | Actor-Critic with experience replay |
| A2C | Advantage Actor-Critic | Advantage Actor-Critic (synchronous version) |
| A3C | Asynchronous Advantage Actor-Critic | Asynchronous Advantage Actor-Critic |
| BN | Batch Normalization | Batch normalization (standardizing the input of each layer) |
| DDPG | Deep Deterministic Policy Gradient | Deep Deterministic Policy Gradient |
| DP | Dynamic Programming | Dynamic programming |
| DPG | Deterministic Policy Gradient | Deterministic policy gradient |
| DQN | Deep Q-Network | Deep Q-Network |
| DRL | Deep Reinforcement Learning | Deep reinforcement learning |
| GAE | Generalized Advantage Estimation | Generalized advantage estimation |
| i.i.d. | independent and identically distributed | Independent and identically distributed |
| KL | Kullback-Leibler divergence | KL divergence (a measure of the difference between two probability distributions) |
| MC | Monte Carlo | Monte Carlo |
| MDP | Markov Decision Process | Markov decision process |
| OU | Ornstein–Uhlenbeck process | Ornstein–Uhlenbeck process (a continuous-time noise process with mean reversion) |
| PG | Policy Gradient | Policy gradient |
| PPO | Proximal Policy Optimization | Proximal policy optimization |
| RLHF | Reinforcement Learning from Human Feedback | Reinforcement learning from human feedback |
| SAC | Soft Actor-Critic | Soft Actor-Critic (the maximum-entropy version) |
| TD | Temporal Difference | Temporal difference |
| TD3 | Twin Delayed DDPG | Twin Delayed Deep Deterministic Policy Gradient |
| TRPO | Trust Region Policy Optimization | Trust 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…
Want to leave a note? Sign in first — comments are open to every signed-in reader.