In the previous post, we looked at policy gradient methods. The basic idea there was to parameterize the policy directly as πθ(a∣s), and then update θ so that the expected return increases.
Q-learning takes a different route. Instead of directly optimizing the policy, it tries to learn an ideal state-action value function, which we will call Q∗ for now. Intuitively, Q∗(s,a) tells us how good it is to take action a in state s, assuming we act optimally afterward.
If we had this ideal Q-function, then we could get an optimal policy by choosing the action with the largest Q-value:
π∗(s)∈arga∈AmaxQ∗(s,a).
In practice, Q-learning learns an approximation Qϕ≈Q∗. Given the learned Qϕ, the greedy policy is
πgreedy(s)∈arga∈AmaxQϕ(s,a).
So the policy is derived from the learned Q-function. If Qϕ were exactly equal to Q∗, then the greedy policy would be optimal. In reality, Qϕ is only an approximation, so the greedy policy is only as good as the learned Q-values.
Bellman optimality
Optimal policy and value functions
Now let us define the optimal Q-function more precisely.
Recall that the state value function and state-action value function are defined as
We say a policy π∗ is optimal if it is at least as good as any other policy from every starting state:
Vπ∗(s)≥Vπ(s)∀s∈S,∀π.
At first glance, it is not obvious that an optimal policy exists. Different states might seem to prefer different policies, so it is not clear that one policy can dominate globally. However, we will soon establish that an optimal policy always exists.
If an optimal policy π∗ exists, we define the optimal value function and optimal Q-function by
V∗(s)Q∗(s,a)=Vπ∗(s),=Qπ∗(s,a).
Bellman optimality equation for V∗
Recall the one-step Bellman equation for a fixed policy π:
Vπ(s)=Ea∼π(⋅∣s),(r,s′)∼p(⋅∣s,a)[r+γVπ(s′)].
If an optimal policy π∗ exists, the same one-step relation should hold for V∗:
V∗(s)=Ea∼π∗(⋅∣s),(r,s′)∼p(⋅∣s,a)[r+γV∗(s′)].
Now the question is: which action should π∗ choose? If we take action a first and then act optimally afterward, the expected value is
E(r,s′)∼p(⋅∣s,a)[r+γV∗(s′)].
So an optimal policy would choose an action that maximizes this quantity. Therefore, we expect V∗ to satisfy
V∗(s)=a∈AmaxE(r,s′)∼p(⋅∣s,a)[r+γV∗(s′)].
This is called the Bellman optimality equation. Just as we did for the Bellman equation, we can establish a similar theorem.
Theorem. Assume γ∈(0,1), ∣S∣<∞, ∣A∣<∞, and ∣r∣≤R<∞ almost surely. Then the optimal value function V∗:S→R exists and satisfies the Bellman optimality equation:
V∗(s)=a∈AmaxE(r,s′)∼p(⋅∣s,a)[r+γV∗(s′)].
Define the Bellman optimality operator T∗ on value functions by
(T∗V)(s)=a∈AmaxE(r,s′)∼p(⋅∣s,a)[r+γV(s′)].
Then the Bellman optimality equation can be written as
T∗V∗=V∗.
Conversely, if a function V:S→R satisfies
T∗V=V,
then V=V∗.
Moreover, for any bounded initial function V0,
(T∗)kV0→V∗as k→∞.
Finally, any greedy policy of the form
π∗(s)∈arga∈AmaxE(r,s′)∼p(⋅∣s,a)[r+γV∗(s′)]
is an optimal policy.
Proof
1. Existence and uniqueness of the fixed point
First, T∗ is a strict contraction with respect to ∥⋅∥∞:
It remains to show that no other policy can do better. We use two simple facts:
TπV≤T∗Vfor any policy π,
and if U≤V pointwise, then
T∗U≤T∗V.
The first fact holds because T∗ maximizes over actions. The second says that increasing the input value function cannot decrease the Bellman optimality update.
For any policy π,
Vπ=TπVπ≤T∗Vπ.
Applying the monotonicity of T∗ repeatedly,
Vπ≤T∗Vπ≤(T∗)2Vπ≤⋯.
Since T∗ is a contraction, (T∗)kVπ→V∗. Therefore Vπ≤V∗ for every policy π.
Vπ∗=V∗andVπ≤V∗∀π.
Thus π∗ is an optimal policy, and V∗ is the optimal value function.
Finally, if a function V satisfies the Bellman optimality equation, then T∗V=V. Since T∗ has a unique fixed point, V=V∗.
Bellman optimality equation for Q∗
The same result can be written directly for the optimal state-action value function.
Theorem. Assume γ∈(0,1), ∣S∣<∞, ∣A∣<∞, and ∣r∣≤R<∞ almost surely. Then the optimal state-action value function Q∗:S×A→R exists and satisfies the Bellman optimality equation:
Q∗(s,a)=E(r,s′)∼p(⋅∣s,a)[r+γa′∈AmaxQ∗(s′,a′)].
Define the Bellman optimality operator T∗ on Q-functions by
Then the Bellman optimality equation can be written as
T∗Q∗=Q∗.
Conversely, if a function Q:S×A→R satisfies
T∗Q=Q,
then Q=Q∗.
Moreover, for any bounded initial function Q0,
(T∗)kQ0→Q∗as k→∞.
Finally, any greedy policy of the form
π∗(s)∈arga∈AmaxQ∗(s,a)
is an optimal policy.
Deep Q-Networks (DQN)
From Q-iteration to DQN
Now we can turn the Bellman optimality equation for Q∗ into an algorithm.
The theory above gives us Q-iteration:
Qk+1k→∞limQk=T∗Qk,=Q∗.
In the ideal case, suppose we can store Q(s,a) for every possible state-action pair, and suppose we know the dynamics well enough to compute the expectation exactly. Then we can start from any initial Q0 and iterate
Then Qk converges to Q∗. This is the Q-function version of value iteration.
In practice, both assumptions are usually false. The state space may be too large, or even continuous, so we cannot store a table of all Q(s,a) values. Also, we usually do not know the transition dynamics, so we cannot compute the expectation exactly.
This suggests two approximations. Instead of storing all Q-values, we represent the Q-function with a neural network Qϕ(s,a). Instead of computing the expectation exactly, we estimate the Bellman backup from sampled transitions (s,a,r,s′).
This gives the simplest version of deep Q-learning. Following Mnih et al., we call this kind of neural-network Q-learning a deep Q-network, or DQN.1 Here, sg[⋅] denotes the stop-gradient operator.
Algorithm: DQN version 0repeatGiven a transition (s,a,r,s′)y←{r,r+γa′∈AmaxQϕ(s′,a′),if s′ is terminalotherwiseϕ←ϕ−α∇ϕ21(Qϕ(s,a)−sg[y])2until convergence
Note that we do not propagate the gradient through the target value y.
Why stop-gradient?
Why do we stop the gradient through the target value y? Remember that the goal is to approximate Q-iteration:
Qk+1≈T∗Qk.
With a neural network, this means the next network should be close to the Bellman update of the previous network. At iteration k, we write this as
ϕk+1=argϕminE[(Qϕ(s,a)−(T∗Qϕk)(s,a))2].
The point is that we want Qϕ to move closer to T∗Qϕk. We do not want to move T∗Qϕk during the same update. If we also differentiate through T∗Qϕk, then we are no longer just fitting the next Q-function to the Bellman update of the previous one.
So in the DQN update, (T∗Qϕk)(s,a) is treated as a fixed target. This is what the stop-gradient operator does in the algorithm above.
Residual learning
What if we do not stop the gradient through the target? Then the loss becomes
Lres(ϕ)=21(Qϕ(s,a)−(r+γa′∈AmaxQϕ(s′,a′)))2.
This loss minimizes the Bellman residual of the Q-function. This is usually called Bellman residual minimization, and the corresponding gradient method is usually called the residual-gradient method, or Residual Gradient (RG).2
Empirically, residual-gradient methods often perform worse than DQN-style semi-gradient updates in deep RL.34 One reason is gradient cancellation.
Consider one transition from (s,a) to (s′,a∗), where
a∗∈arga′∈AmaxQϕ(s′,a′).
The Bellman residual is
δ=Qϕ(s,a)−(r+γQϕ(s′,a∗)).
In the DQN update, we reduce this error by moving only Qϕ(s,a) toward the target. In residual learning, both sides are updated. Roughly speaking,
ΔQϕ(s,a)∝−δ,ΔQϕ(s′,a∗)∝γδ.
So the current value and the next-state value are pushed in opposite directions. But s and s′ come from the same transition, so their network gradients can be similar. If
∇ϕQϕ(s,a)≈∇ϕQϕ(s′,a∗),
then the residual-gradient direction contains the difference
∇ϕQϕ(s,a)−γ∇ϕQϕ(s′,a∗)≈(1−γ)∇ϕQϕ(s,a).
When γ is close to one, the two terms almost cancel. This makes the update small and learning slow.
Sampling states and actions
Let's go back to the DQN update. So far, we have assumed that a transition (s,a,r,s′) is given. In practice, how do we get this transition?
In some cases, we can sample state-action pairs directly. For example, a simulator may let us reset to a chosen state and try a chosen action.
In general, this is not possible. For example, a real robot cannot freely jump to any state we want. In the usual RL setup, transitions come from interaction with the environment: the agent is at state s, chooses action a, observes (r,s′), and then continues from s′.
Then the algorithm becomes:
Algorithm: DQN with online samplingrepeatChoose action a and observe (r,s′)y←{r,r+γa′∈AmaxQϕ(s′,a′),if s′ is terminalotherwiseϕ←ϕ−α∇ϕ21(Qϕ(s,a)−sg[y])2s←s′until convergence
Replay buffer
However, this version has a problem. As we update Qϕ along one trajectory, nearby updates use nearby transitions. These transitions are highly correlated, so the network may overfit to a local part of the state-action space.
DQN reduces this problem with a replay buffer.1 A replay buffer is just a dataset of past transitions.
Each time the agent acts, we add (s,a,r,s′) to the buffer. For training, we sample one or more minibatches from the buffer instead of using only the newest transition.
This has two advantages. First, minibatch samples are less correlated than consecutive samples from one episode. Second, using a batch gives a lower-variance gradient estimate than using one transition.
In practice, the buffer has fixed capacity: it stores at most N transitions, and once it is full, adding a new transition removes an old one. Capacity matters because it changes the data used for training. A very small buffer stays too close to recent trajectories, while a very large buffer can keep data that no longer matches the current agent well.
With a replay buffer, the algorithm becomes:
Algorithm: DQN with replay bufferrepeatChoose action a and observe (r,s′)D←D∪{(s,a,r,s′)}for each sampled minibatch B⊂D doyi←{ri,ri+γa′∈AmaxQϕ(si′,a′),if si′ is terminalotherwise,(si,ai,ri,si′)∈Bϕ←ϕ−α∇ϕ∣B∣1i∈B∑21(Qϕ(si,ai)−sg[yi])2end foruntil convergence
Exploration
How should the agent choose actions while collecting transitions?
One simple idea is to always choose the greedy action:
a∈arga∈AmaxQϕ(s,a).
This can be a problem early in training. The Q-function is still inaccurate, so the greedy action may only look good because of a bad estimate. If the agent keeps choosing it, the replay buffer may contain data from only a narrow part of the state-action space.
The opposite extreme is to choose actions uniformly at random:
a∼Uniform(A).
Choosing actions uniformly at random gives broad exploration, but it is usually inefficient in RL. Useful rewards often require several good actions in a row, and a uniformly random policy is unlikely to follow such a trajectory for long.
A common compromise is ϵ-greedy exploration:
a∼{arga∈AmaxQϕ(s,a),Uniform(A),with probability 1−ϵwith probability ϵ
The parameter ϵ controls the balance between exploration and exploitation. A larger ϵ makes the agent explore more. A smaller ϵ makes the agent follow the current Q-function more often.
With ϵ-greedy exploration, the replay-buffer algorithm becomes:
Algorithm: DQN with explorationrepeata∼{arga∈AmaxQϕ(s,a),Uniform(A),w.p. 1−ϵw.p. ϵTake action a and observe (r,s′)D←D∪{(s,a,r,s′)}for each sampled minibatch B⊂D doyi←{ri,ri+γa′∈AmaxQϕ(si′,a′),if si′ is terminalotherwise,(si,ai,ri,si′)∈Bϕ←ϕ−α∇ϕ∣B∣1i∈B∑21(Qϕ(si,ai)−sg[yi])2end foruntil convergence
In practice, ϵ is often scheduled during training. Early in training, the Q-function is unreliable, so we use a large ϵ. Later, as the Q-function becomes more stable, we reduce ϵ. In the original DQN experiments, ϵ was annealed from 1.0 to 0.1 during training.1
The choice of exploration strategy can have a large effect on learning. If exploration is too weak, the agent may miss useful actions. If exploration is too strong, the agent may not use what it has already learned. Later DQN variants also found that changing the exploration mechanism can significantly affect performance.5
On-policy vs off-policy
Let us pause and think about this question:
Can we use the replay buffer idea for policy-gradient methods?
For the policy-gradient methods we discussed, the answer is no. The policy-gradient estimator assumes that actions are sampled from the current policy:
This is why old transitions cannot be reused directly. If the action came from an older policy, this is no longer the right gradient estimate.
DQN is different. To update the Q-function, we only need a transition (s,a,r,s′). The action a does not have to come from the current policy.
So we use the following terminology:
On-policy:Off-policy:learn from data generated by the same policy being updatedlearn from data generated by a different policy
Off-policy methods can learn from data generated by a different policy. This data may come from past experience, exploratory actions, or expert demonstrations. The policy that generates the data is called the behavior policy.
The main advantage of off-policy methods is sample efficiency: a single experience can be used multiple times. On-policy methods cannot reuse old data directly after the policy changes. This may be acceptable when data collection is cheap, such as in a simulated environment, but it becomes a serious limitation when data collection is expensive, such as with a real-world robot.
Off-policy methods can also learn while following a safe behavior policy. This is useful in practical robotics, where the robot may need to improve its policy without directly executing risky exploratory actions.
Stabilizing DQN
Target networks
Let's go back to the DQN update. In the algorithm above, the target is
yi={ri,ri+γmaxa′∈AQϕ(si′,a′),if si′ is terminalotherwise
The same network Qϕ is used to compute the target and is also being updated. So after every gradient step, ϕ changes, and the target yi changes too.
But in fitted Q-learning, we wanted
ϕk+1=argϕminE[(Qϕ(s,a)−(T∗Qϕk)(s,a))2].
The replay-buffer algorithm above does not quite follow this. It takes only one gradient step toward the current target. Then ϕ changes, so the next target also changes. In other words, the target moves before we have had much time to fit it.
DQN handles this with a target network. We keep two networks: an online network Qϕ, which is updated by gradient descent, and a target network Qϕ−, which is used to compute the target. In practice, we update the target network every C gradient updates.
Algorithm: DQN with target networkrepeata∼{arga∈AmaxQϕ(s,a),Uniform(A),w.p. 1−ϵw.p. ϵTake action a and observe (r,s′)D←D∪{(s,a,r,s′)}for each sampled minibatch B⊂D doyi←{ri,ri+γa′∈AmaxQϕ−(si′,a′),if si′ is terminalotherwise,(si,ai,ri,si′)∈Bϕ←ϕ−α∇ϕ∣B∣1i∈B∑21(Qϕ(si,ai)−sg[yi])2Every C gradient updates, set ϕ−←ϕend foruntil convergence
This algorithm is now close to Algorithm 1 in the original DQN paper. Two remaining differences are that the paper samples one random minibatch per environment step, and its implementation uses clipped TD errors, which is equivalent to using a Huber loss with threshold 1. See the paper for the full implementation details.
Polyak averaging
Original DQN updates the target network by a hard copy:
ϕ−←ϕ.
This happens only every C gradient updates. Between these updates, the target network Qϕ− becomes older and older. Then it is suddenly replaced by the current online network Qϕ.
Polyak averaging is a smoother alternative. Instead of copying the whole network at once, we update the target network slowly:
ϕ−←τϕ−+(1−τ)ϕ,
where τ is close to 1, such as τ=0.999.
Double DQN
Consider an MDP where r=0 for every transition.
Q∗(s,a)=0∀s,a.
What happens if we apply DQN to this MDP?
The DQN target is
y=r+γa′maxQϕ−(s′,a′).
Since r=0,
y=γa′maxQϕ−(s′,a′).
Early in training, Qϕ− is noisy. Although the correct value is zero,
a′maxQϕ−(s′,a′)
will often be positive. Hence the target is positive, and the update pushes Qϕ(s,a) upward.
This is not just an artifact of this example. In practice, DQN can overestimate action values; van Hasselt, Guez, and Silver observed substantial overestimation in some Atari games.6
To see why the max operator creates this bias, rewrite it as
a′maxQϕ−(s′,a′)=Qϕ−(s′,arga′maxQϕ−(s′,a′)).
The argmax favors actions with positive estimation error. The outer Qϕ− then reuses the same positive error as the value. This correlation between action selection and value evaluation causes overestimation.
Double Q-learning avoids this reuse by separating action selection from value evaluation:7
Look again at the r=0 MDP. Even if QϕA selects an action with large positive noise, the value is evaluated by QϕB. The noise in QϕB is not tied to the noise in QϕA, so the same positive noise is not reused.
In DQN, we already have two networks: the online network Qϕ and the target network Qϕ−. Double DQN uses them for the same separation.
Standard DQN uses the target network for both selection and evaluation:
yi=ri+γQϕ−(si′,arga′maxQϕ−(si′,a′)).
Double DQN changes only the action selection inside the target:
yi=ri+γQϕ−(si′,arga′maxQϕ(si′,a′)).
This gives the following Double DQN algorithm:
Algorithm: Double DQNrepeata∼{arga∈AmaxQϕ(s,a),Uniform(A),w.p. 1−ϵw.p. ϵTake action a and observe (r,s′)D←D∪{(s,a,r,s′)}for each sampled minibatch B⊂D doyi←⎩⎨⎧ri,ri+γQϕ−(si′,arga′∈AmaxQϕ(si′,a′)),if si′ is terminalotherwise,(si,ai,ri,si′)∈Bϕ←ϕ−α∇ϕ∣B∣1i∈B∑21(Qϕ(si,ai)−sg[yi])2Every C gradient updates, set ϕ−←ϕend foruntil convergence
Q-learning with continuous actions
So far, we have assumed a discrete action space. What goes wrong if the action space is continuous?
The issue is that DQN repeatedly asks us to maximize the Q-function over actions.
When collecting data, this appears in the greedy action:
a∈arga∈AmaxQϕ(s,a).
When training the Q-function, it appears again in the target value:
yi=ri+γa′∈AmaxQϕ−(si′,a′).
The simplest workaround is to sample candidate actions and choose the one with the largest Q-value:
amaxQϕ(s,a)(a1,…,aN)≈max{Qϕ(s,a1),…,Qϕ(s,aN)} sampled from some distribution (e.g., uniform)
A more accurate version is to use an iterative stochastic optimizer. For example, QT-Opt uses the cross-entropy method (CEM) to approximately maximize the Q-function over continuous actions.8
Algorithm: CEM action maximizationInitialize a Gaussian distribution over actionsrepeat K timesSample N candidate actions a1,…,aNEvaluate Qϕ(s,aj) for all candidatesKeep the top M elite actionsRefit the Gaussian distribution to the elite actionsreturn the best action found
This can work when the action dimension is low enough. But as the dimension grows, sampled actions are unlikely to land near the maximizer, so the resulting target can be a poor approximation of the true max.
Normalized Advantage Functions (NAF)
Another way to avoid numerical maximization is to choose a Q-function class that is easy to maximize.
Normalized Advantage Functions (NAF) do this by changing the structure of the Q-network.9 Given a state s, the network outputs a value Vϕ(s), an action mean μϕ(s), and a lower-triangular matrix Lϕ(s). These outputs define the Q-value by
The diagonal entries of Lϕ(s) are constrained to be positive, so Lϕ(s)Lϕ(s)⊤ is positive definite. Therefore, the quadratic term is always non-positive and is maximized at a=μϕ(s):
argamaxQϕ(s,a)=μϕ(s),amaxQϕ(s,a)=Vϕ(s).
So the Q-learning target no longer needs an inner optimization problem. For the next state, the target network can directly use Vϕ−(s′) as the maximized Q-value.
However, this works because NAF restricts the advantage to be quadratic in the action. The resulting Q-function is easy to maximize, but it cannot represent more complicated action-value landscapes, such as cases where several distinct actions are good for the same state.
Deep Deterministic Policy Gradient (DDPG)
Another approach is to learn an approximate maximizer. The maximized Q-value can be written as
amaxQϕ(s,a)=Qϕ(s,argamaxQϕ(s,a)).
DDPG introduces another network πθ(s), called the actor, and trains it to approximate the action that maximizes the critic Qϕ:10
πθ(s)≈argamaxQϕ(s,a).
For a single state, the idealized update would be
θ←argθmaxQϕ(s,πθ(s)).
In practice, we optimize this over states sampled from the replay buffer:
θmaxEs∼D[Qϕ(s,πθ(s))].
In DQN, exploration was done with ϵ-greedy actions over a finite action set. For a deterministic actor in a continuous action space, a natural exploration strategy is to perturb the actor's action:
a=πθ(s)+ϵ,
where ϵ is some exploration noise.
DDPG also updates the target networks by Polyak averaging, instead of periodically copying the online networks.
This gives the following DDPG algorithm:
Algorithm: DDPGrepeata←πθ(s)+ϵ,ϵ is some exploration noiseTake action a and observe (r,s′)D←D∪{(s,a,r,s′)}for each sampled minibatch B⊂D doyi←{ri,ri+γQϕ−(si′,πθ−(si′)),if si′ is terminalotherwise,(si,ai,ri,si′)∈Bϕ←ϕ−αQ∇ϕ∣B∣1i∈B∑21(Qϕ(si,ai)−sg[yi])2θ←θ+απ∇θ∣B∣1i∈B∑Qϕ(si,πθ(si))ϕ−←τϕ−+(1−τ)ϕθ−←τθ−+(1−τ)θend foruntil convergence
DDPG as deterministic policy gradient method
The previous section described DDPG from the DQN view:
πθ(s)≈argamaxQϕ(s,a).
However, the original DDPG paper presents the algorithm from the deterministic policy gradient (DPG) view.11
Equivalently, the actor performs gradient ascent on
Es∼D[Qϕ(s,πθ(s))].
In minibatch form,
θ←θ+απ∇θ∣B∣1i∈B∑Qϕ(si,πθ(si)).
This is the actor update used in the DDPG algorithm above.
Twin Delayed Deep Deterministic Policy Gradient (TD3)
Clipped double Q-learning
DDPG uses the target
y=r+γQϕ−(s′,μθ−(s′)).
This has the same kind of overestimation problem we saw in DQN. TD3 applies the basic idea of Double Q-learning to reduce this overestimation.12
Unlike Double DQN, which reused the online and target networks as the two value estimates, TD3 follows the original Double Q-learning idea and learns two critics:
Qϕ1(s,a),Qϕ2(s,a).
A direct actor-critic version of Double Q-learning can be written as
TD3 makes this idea more conservative. Instead of letting each critic use the other critic's value, TD3 uses the smaller of the two target critic values:
y=r+γj=1,2minQϕj−(s′,μθ−(s′)).
This is called clipped double Q-learning. Taking the minimum can make the target underestimate the true value, but this is usually safer than overestimation. Since the actor update maximizes Qϕ(s,μθ(s)), overestimated actions are more likely to be selected. They can then appear again in future rollouts and TD targets, so the error can reinforce itself. Underestimated actions are less likely to be selected, so their errors are less likely to propagate.
Target policy smoothing
TD3 also adds a small amount of clipped noise to the target action. This target policy smoothing prevents the critic target from overfitting to narrow peaks in the value estimate, and encourages nearby actions to have similar values:
a~′=μθ−(s′)+ϵ,ϵ∼clip(N(0,σ),−c,c).
So the actual target is
y=r+γj=1,2minQϕj−(s′,a~′).
Delayed policy updates
TD3 updates the critic more frequently while updating the actor more cautiously. The critics are updated every gradient step, while the actor and target networks are updated only after every d critic updates. A common choice is d=2.
TD3 algorithm
Combining clipped double Q-learning, target policy smoothing, and delayed policy updates gives the complete TD3 algorithm:
Algorithm: TD3Initialize Qϕ1,Qϕ2,μθ and target networks Qϕ1−,Qϕ2−,μθ−Initialize replay buffer Drepeata←μθ(s)+η,η is some exploration noiseTake action a and observe (r,s′)D←D∪{(s,a,r,s′)}for each sampled minibatch B⊂D doϵi′∼clip(N(0,σ),−c,c)a~i′←μθ−(si′)+ϵi′yi←{ri,ri+γj=1,2minQϕj−(si′,a~i′),if si′ is terminalotherwise,(si,ai,ri,si′)∈Bfor j∈{1,2} doϕj←ϕj−αQ∇ϕj∣B∣1i∈B∑21(Qϕj(si,ai)−sg[yi])2end forafter every d critic updates doθ←θ+αμ∇θ∣B∣1i∈B∑Qϕ1(si,μθ(si))ϕ1−←τϕ1−+(1−τ)ϕ1ϕ2−←τϕ2−+(1−τ)ϕ2θ−←τθ−+(1−τ)θend afterend foruntil convergence
Maximum Entropy RL
So far, the goal has been to find a policy that maximizes expected return. Maximum-entropy RL changes the objective slightly. Instead of maximizing only reward, it maximizes reward and policy entropy:
JH(π)=Es0∼p0π[t=0∑T−1γt(rt+βH(π(⋅∣st)))]
where H denotes the entropy of the policy at state s:
H(π(⋅∣s))=Ea∼π(⋅∣s)[−logπ(a∣s)].
Here β>0 is the temperature. When β is small, the entropy term matters less and the objective becomes close to the usual RL objective. When β is large, the policy is pushed to stay more random.
Why optimize this objective instead of the usual return? The ordinary objective gives a greedy policy:
π∗(s)∈arga∈AmaxQ∗(s,a).
So the policy tries to learn one best action for each state. This is sometimes exactly what we want. But in many tasks, a single state can have several good actions. For example, when picking up a cup, we might grab the handle, support the cup from the bottom, or hold it near the rim depending on the situation.
The maximum-entropy objective captures this idea. It still prefers actions with high return, but among actions with similar return, it prefers a policy that keeps multiple options available. So if there are many ways to solve the task, the policy is encouraged to represent many of them instead of collapsing immediately to one arbitrary choice.
Here is an example that demonstrates the difference between the ordinary objective and the maximum-entropy objective.
This video compares the standard RL objective with the maximum-entropy RL objective. DDPG represents the standard objective, while Soft Q-learning (SQL) represents the maximum-entropy objective. In this experiment, a quadruped is rewarded for moving quickly without specifying a particular direction.13 DDPG tends to pick one consistent direction, whereas SQL can keep several directions as plausible behavior because its objective rewards high-return behavior without forcing the policy to collapse to one mode.
Discrete entropy and differential entropy
The entropy you might be more familiar with is the entropy of a discrete random variable. If X takes values in a finite set X, then
H(X)=−x∈X∑p(x)logp(x)=Ex∼p[−logp(x)].
For a finite discrete random variable,
0≤H(X)≤log∣X∣.
The minimum value 0 is achieved if and only if X is deterministic. The maximum value log∣X∣ is achieved by the uniform distribution.
For a continuous random variable, the analogous object is called differential entropy. If X has density p(x), then
h(X)=−∫p(x)logp(x)dx=Ex∼p[−logp(x)].
This looks almost identical, but it behaves differently. Differential entropy has no universal lower or upper bound. It can be negative, and it can be made arbitrarily large by spreading the density over a wider region. So we should not treat discrete entropy and differential entropy as exactly the same object.
Soft value functions
From the augmented objective, we can define soft value functions. For a fixed policy π,
The first term is the expected return after fixing the first action. The entropy term for the current state can then be written as an expectation over the sampled first action.
Handling terminal states
Under the original MDP definition, a trajectory ends when it reaches sT=sterm. Since the agent does not choose another action at the terminal state, π(⋅∣sterm), and therefore its entropy, is not defined.
To avoid writing a separate terminal case in every equation, we introduce a single dummy action aterm at the terminal state. This action keeps the process at sterm and produces zero reward:
p(r=0,s′=sterm∣sterm,aterm)=1.
Since it is the only available action,
π(aterm∣sterm)=1,H(π(⋅∣sterm))=0.
There is no reward or entropy bonus after reaching the terminal state. Therefore,
VHπ(sterm)=0,QHπ(sterm,aterm)=0.
To keep the notation simple, we will omit separate terminal-state cases in the equations below. If a fully explicit terminal-state equation is needed, it can be recovered using the dummy-action convention above.
Soft Bellman equation
We can derive a similar Bellman equation for the soft Q-function.
Theorem. Let π be a fixed policy. Assume γ∈(0,1), ∣S∣<∞, ∣A∣<∞, and ∣r∣≤R<∞ almost surely. Then QHπ exists and satisfies the soft Bellman equation
The reward and entropy terms cancel in the difference, so this is exactly the same contraction argument as before.
By the contraction mapping theorem, THπ has a unique fixed point, and repeated application of the operator converges to it. Since QHπ is already a fixed point, it must be that unique fixed point.
Softmax policy
Now suppose the soft Q-function is given. What should the policy look like?
Before, we simply chose an action that maximized the Q-value:
πgreedy(s)∈arga∈AmaxQ(s,a).
In maximum-entropy RL, the policy at state s should maximize the Q-value and the entropy of the policy:
Ea∼π(⋅∣s)[QH(s,a)]+βH(π(⋅∣s)).
The greedy argmax is no longer the right solution, because it maximizes only the Q-value and ignores the entropy bonus. We need a policy that balances high Q-values with high entropy.
For a Q-function Q, define its softmax policy by
πβ1Q(a∣s)πβ1Q(a∣s)=∑a~∈Aexp(β1Q(s,a~))exp(β1Q(s,a)),if ∣A∣<∞=∫Aexp(β1Q(s,a~))da~exp(β1Q(s,a)),if A is continuousDerivation
For simplicity, assume A is finite. For a fixed state s, write πa=π(a∣s) and Qa=Q(s,a). The optimization problem is
πβ1Q(⋅∣s)=argπ(⋅∣s)maxa∑πaQa−βa∑πalogπa
subject to
a∑πa=1,πa≥0
The Lagrangian is
L(π,λ)=a∑πaQa−βa∑πalogπa+λ(a∑πa−1).
Taking the derivative with respect to πa gives
∂πa∂L=Qa−β(logπa+1)+λ.
At the optimum,
Qa−β(logπa+1)+λ=0.
Therefore,
logπa=βQa+βλ−β,
so
πa∝exp(Qa/β).
Normalizing over actions gives πβ1Q(⋅∣s).
The softmax policy is proportional to exp(β1Q(s,a)). So every action can still be chosen, but actions with larger Q-values are chosen more often. Also, as β→0, the largest Q-value dominates the exponential, and the policy becomes the greedy argmax policy.
Softmax and log-sum-exp
The policy above is called a softmax policy because it uses the softmax function. Since this name is used in a slightly confusing way, let us pause and make the notation clear.
For β>0, define the softmax function with temperature β, softmaxβ:Rn→Rn, as
Finally, the two functions are connected by a simple gradient relation:
softmaxβ(x)=∇LSEβ(x).
Soft Bellman optimality equation
Now we can write the maximum-entropy version of the Bellman optimality equation.
Theorem. Assume γ∈(0,1), ∣S∣<∞, ∣A∣<∞, and ∣r∣≤R<∞ almost surely. Then the optimal soft Q-function QH∗:S×A→R exists and satisfies the soft Bellman optimality equation
The left side is the gap between the soft maximum and the expected soft value that the policy π actually achieves. The identity says this gap is exactly a KL divergence: it measures how far π is from the softmax policy of Q.
This can be checked directly. By definition of the softmax policy,
logπβ1Q(a∣s)=β1Q(s,a)−β1LSEβ(Q(s,⋅)).
Substituting this into the definition of the KL divergence gives
The right side is nonnegative, so this gives an inequality: for any policy π and any bounded Q,
THπQ≤TH∗Q.
The right side is zero exactly when the two distributions are equal at every next state, so the inequality becomes an equality exactly when π is the softmax policy of Q:
THπβ1QQ=TH∗Q.
We will use both facts several times below.
Note that the key identity also strengthens the earlier softmax derivation. There we showed that the softmax policy maximizes the expected Q-value plus entropy. The identity says more: it gives the maximum value and the exact cost of using any other policy,
Note that the contraction proof for the hard-max operator used exactly these two properties of the max, and nothing else. LSEβ has both, so the same argument goes through.
So TH∗ has a unique bounded fixed point. Denote it by Qˉ:
TH∗Qˉ=Qˉ.
Also, for any bounded Q0, repeated application converges: (TH∗)kQ0→Qˉ.
At this point, we only know that Qˉ is the fixed point of TH∗. We still need to show that it is the optimal soft Q-function.
2. Define πˉ and show Qˉ=QHπˉ
Next, define πˉ to be the softmax policy of Qˉ:
πˉ=πβ1Qˉ.
We do not yet know that πˉ is optimal.
By the equality case of the key identity, the KL term vanishes when the policy is the softmax policy of the same Q-function. So
THπˉQˉ=TH∗Qˉ=Qˉ.
This says Qˉ is a bounded fixed point of THπˉ. But the soft Bellman equation theorem tells us that THπˉ has a unique bounded fixed point, namely QHπˉ. Therefore
Qˉ=QHπˉ.
So the softmax policy πˉ has soft Q-function Qˉ.
3. Show πˉ is optimal
It remains to show that no other policy can do better. We use two simple facts:
THπQ≤TH∗Qfor any policy π,
and if Q1≤Q2 pointwise, then
TH∗Q1≤TH∗Q2.
The first fact is the key identity from step 0. The second holds because LSEβ and expectations are both monotone.
For any policy π,
QHπ=THπQHπ≤TH∗QHπ.
Applying the monotonicity of TH∗ repeatedly,
QHπ≤TH∗QHπ≤(TH∗)2QHπ≤⋯.
Since TH∗ is a contraction, (TH∗)kQHπ→Qˉ. Therefore QHπ≤Qˉ for every policy π.
QHπˉ=QˉandQHπ≤Qˉ∀π.
Thus πˉ is an optimal policy, and Qˉ is the optimal soft Q-function: QH∗=Qˉ. This also gives the claimed form of the optimal policy, πH∗=πβ1QH∗.
Finally, if a bounded function Q satisfies the soft Bellman optimality equation, then TH∗Q=Q. Since TH∗ has a unique fixed point, Q=QH∗.
Soft Q-learning
The theory above gives us soft Q-iteration:
Qk+1k→∞limQk=TH∗Qk,=QH∗.
Earlier, we derived the DQN algorithm from Q-iteration. Now we can apply the same idea to soft Q-iteration, which gives the following Soft Q-learning algorithm:13
Algorithm: Soft Q-learningInitialize Qϕ and target network Qϕ−Initialize replay buffer Drepeata∼πβ1Qϕ(⋅∣s)Take action a and observe (r,s′)D←D∪{(s,a,r,s′)}for each sampled minibatch B⊂D doyi←ri+γLSEβ(Qϕ−(si′,⋅)),(si,ai,ri,si′)∈Bϕ←ϕ−αQ∇ϕ∣B∣1i∈B∑21(Qϕ(si,ai)−sg[yi])2Every C gradient updates, set ϕ−←ϕend foruntil convergence
Compared with DQN, two parts of the algorithm have changed.
First, action sampling changes from ϵ-greedy sampling to sampling from the softmax policy:
Note that Soft Q-learning removes explicit ϵ-greedy exploration from action sampling, because the maximum-entropy objective already encourages exploration.
In a finite action space, both soft replacements are straightforward to implement. We can evaluate Qϕ(s,a) for every action, normalize the softmax probabilities, and sample from them. We can also compute LSEβ by summing over all actions.
The continuous case is different. Recall from Q-learning with continuous actions that continuous action spaces are difficult because max and argmax over actions are no longer easy to compute. Soft Q-learning has the same issue in soft form.
For target evaluation, we need
LSEβ(Qϕ−(s′,⋅))=βlog∫Aexp(β1Qϕ−(s′,a′))da′.
For action sampling, we need
a∼πβ1Qϕ(⋅∣s),πβ1Qϕ(a∣s)∝exp(β1Qϕ(s,a)).
For a general neural network Qϕ, the log-sum-exp term is intractable to compute, and sampling from the softmax policy is not straightforward. The Soft Q-learning paper solves these problems as follows.
Estimating the target
The log-sum-exp term in the target can be estimated by importance sampling. For any proposal distribution q(⋅∣s′) whose density is positive on the action space,
How can we draw an action a∼πβ1Qϕ(⋅∣s) for a given state s?
Generic sampling methods such as MCMC could be used in principle, but they would require an iterative sampling procedure for every action, which is too expensive in practice.
Soft Q-learning instead trains a separate network to be the sampler. Let
a=fθ(ξ;s),ξ∼N(0,I).
For each state s, the noise-conditioned network fθ induces a distribution over actions. Call this distribution πθ(⋅∣s). Ideally, we want
πθ(⋅∣s)≈πβ1Qϕ(⋅∣s).
Equivalently, we would like to minimize
Jπ(θ;s)=DKL(πθ(⋅∣s)πβ1Qϕ(⋅∣s)).
Writing Zϕ(s) for the normalizing constant, expanding the KL divergence gives
The Q term is straightforward. We can differentiate Qϕ(s,fθ(ξ;s)) through the sampler fθ.
The problem is the density term logπθ(a∣s). The network fθ lets us sample actions, but it does not directly give their probabilities. In other words, we can generate a=fθ(ξ;s), but we generally cannot evaluate πθ(a∣s).
One way around this is to restrict the sampler to a distribution with a tractable density. For example, if the policy is Gaussian and the network outputs μθ(s) and σθ(s), then we can sample
a=μθ(s)+σθ(s)⊙ξ,ξ∼N(0,I),
and evaluate logπθ(a∣s) explicitly. Later, Soft Actor-Critic uses this kind of tractable stochastic policy.14
Soft Q-learning takes a different route. It keeps the more expressive implicit sampler fθ, and estimates the sampler update from samples without evaluating logπθ(a∣s) directly.
Amortized SVGD
Soft Q-learning uses amortized SVGD to update the sampler. Instead of trying to evaluate the sampler density πθ(a∣s), it directly updates the sampler toward the same target as before:
πθ(⋅∣s)≈πβ1Qϕ(⋅∣s).
The idea of amortized SVGD is to use samples from the sampler itself. If the sampled actions are not distributed like the target softmax policy, we ask how those actions should move to look more like samples from the target. Then we update fθ so that future samples are already shifted in those directions.
Concretely, first sample particles from the current sampler:
ak=fθ(ξk;s),ξk∼N(0,I),k=1,…,K.
SVGD assigns a movement direction to each particle:
Here κ is a kernel, which measures similarity between actions. The first term pulls particles toward high-density actions. The second term makes nearby particles repel each other, which helps the particles represent a distribution instead of all chasing the same high-value action.
Ordinary SVGD would use this velocity field to iteratively move particles toward the target distribution. Amortized SVGD instead uses the velocity field as a training signal for the sampler: update θ so that fθ produces actions shifted in those directions.
Δθ∝Eξ[Δ(fθ(ξ;s))⊤∂θ∂fθ(ξ;s)].
Algorithm summary
Putting the target update and sampler update together, we get the following algorithm:
Algorithm: Soft Q-learningInitialize Qϕ,fθ and target network Qϕ−Initialize replay buffer Drepeatξ∼N(0,I)a←fθ(ξ;s)Take action a and observe (r,s′)D←D∪{(s,a,r,s′)}for each sampled minibatch B⊂D doFor each i∈B, sample aij′∼q(⋅∣si′),j=1,…,MVi←βlogM1j=1∑Mq(aij′∣si′)exp(β1Qϕ−(si′,aij′))yi←ri+γViϕ←ϕ−αQ∇ϕ∣B∣1i∈B∑21(Qϕ(si,ai)−sg[yi])2For each i∈B, sample particles a~ik=fθ(ξik;si),k=1,…,KCompute the SVGD field Δi using Qϕ and the particles a~ikCompute the sampler update direction Δθ from Δiθ←θ+απΔθEvery C gradient updates, set ϕ−←ϕend foruntil convergence
The algorithm resembles actor-critic structurally, but fθ is better understood as an approximate sampler for the softmax policy defined by Qϕ, not as a separate policy being evaluated by Qϕ.
Why use an expressive sampler?
Why does Soft Q-learning keep the expressive sampler instead of using a simpler Gaussian policy that would avoid amortized SVGD altogether?
The paper motivates this choice by pointing to multimodality. The softmax policy defined by the Q-function can assign probability to multiple high-value action regions, while a deterministic policy or a simple Gaussian policy tends to represent only one behavior mode. The paper argues that this can help exploration, because the agent can keep several behaviors available before it knows which one is best, and can also help pretraining, because a broad maximum-entropy policy can contain several useful behaviors for later tasks. The swimmer, quadruped maze, and quadruped pretraining experiments illustrate these points.13
Soft Actor-Critic (SAC)
Note.
SAC is not Q-learning in the same sense as DQN or Soft Q-learning. I include it here because it belongs to the same maximum-entropy RL story, and it is easiest to understand right after Soft Q-learning.
There are two SAC papers.1415 The second paper refines the original SAC algorithm and is closer to the SAC implementation that is standard today. In this section, we will mainly follow that later version.
Soft Q-learning tries to learn the optimal soft Q-function directly. Soft Actor-Critic takes a slightly different view: it starts from policy iteration.
Policy iteration alternates two steps:
repeatQπk←evaluate the current policy πkπk+1←improve the policy using Qπkuntil convergence
In classical policy iteration, this improvement step is greedy. After evaluating πk, we define the next policy by choosing the action with the largest current Q-value:
πk+1(s)=argamaxQπk(s,a).
The policy-gradient methods from the previous post can also be viewed as approximate versions of this evaluate-and-improve loop. The critic evaluates the current policy, and the actor update improves the policy using that estimate.
SAC uses the maximum-entropy version of the same idea. The policy evaluation step is the soft version of the critic update we saw in actor-critic methods. Given a sampled transition (si,ai,ri,si′), we first sample the next action from the current policy:
ai′∼πθk(⋅∣si′).
Then we compute the soft Bellman target:
yi=ri+γ[Qϕ−(si′,ai′)−βlogπθk(ai′∣si′)].
The critic is trained to fit this target:
JQ(ϕ)=∣B∣1i∈B∑21(Qϕ(si,ai)−sg[yi])2.
For the policy improvement step, SAC uses the maximum-entropy version of the greedy update. We already showed that, for the maximum-entropy objective, the greedy policy for a given Q-function is the softmax policy
πβ1QHπk(⋅∣s).
SAC chooses the closest policy to this softmax policy inside a policy class Π by minimizing the KL divergence. We will make the policy class concrete below.
In the actor-critic methods from the previous post, the policy update came directly from a policy-gradient estimate:
∇θJ(θ)≈∇θlogπθ(at∣st)A^t(k).
So the update direction was explicitly tied to the objective J(θ). Here, the improvement step is written differently: we choose a new policy by a KL projection onto the softmax policy induced by QHπk. It is not immediately obvious that this projection really improves the policy. The next theorem shows that it does, in the exact policy-iteration setting.
Theorem. Suppose QHπk is the exact soft Q-function of the current policy πk∈Π. Define the next policy by
As before, the issue is whether we can evaluate the density term logπθ(a∣s). Unlike Soft Q-learning, SAC chooses a policy class whose density can be evaluated explicitly.
For example, SAC can use a squashed Gaussian policy:
When β=0, the SAC actor update is almost identical to the DDPG actor update. So the same overestimation issue can appear here as well. Recall that TD3 addressed this by using clipped double Q-learning. Practical SAC also uses clipped double Q-learning:
The authors note that SAC can still learn hard tasks with a single Q-function, but two soft Q-functions significantly speed up training, especially on harder tasks.
This is the end of the third post. We started from the Bellman optimality equation, extended Q-learning to continuous actions, and then studied maximum entropy RL and SAC. For now, this is the end of the series, although I may add another post on offline or model-based reinforcement learning in the future.
References
Footnotes
Volodymyr Mnih, Koray Kavukcuoglu, David Silver, Andrei A. Rusu, Joel Veness, Marc G. Bellemare, Alex Graves, Martin Riedmiller, Andreas K. Fidjeland, Georg Ostrovski, Stig Petersen, Charles Beattie, Amir Sadik, Ioannis Antonoglou, Helen King, Dharshan Kumaran, Daan Wierstra, Shane Legg, and Demis Hassabis, “Human-level control through deep reinforcement learning”, Nature, 2015. ↩↩2↩3
Meire Fortunato, Mohammad Gheshlaghi Azar, Bilal Piot, Jacob Menick, Ian Osband, Alex Graves, Vlad Mnih, Rémi Munos, Demis Hassabis, Olivier Pietquin, Charles Blundell, and Shane Legg, “Noisy Networks for Exploration”, ICLR, 2018. ↩
Tuomas Haarnoja, Aurick Zhou, Kristian Hartikainen, George Tucker, Sehoon Ha, Jie Tan, Vikash Kumar, Henry Zhu, Abhishek Gupta, Pieter Abbeel, and Sergey Levine, “Soft Actor-Critic Algorithms and Applications”, arXiv, 2018. ↩