SAC: include a stochastic policy in the value target
SAC
Trace reparameterization, tanh densities, twin Q and temperature while distinguishing the 2018 and later algorithms.
sacWhy should an actor deliberately remain random?
In a teaching control task, several nearby actions may all score well. A deterministic actor emits one action per state; SAC learns a distribution that trades high action values against the entropy of keeping options. Its critic considers future policy entropy as well as future rewards. Randomness enters the training objective rather than serving only as temporary exploration noise.
Soft Actor-Critic combines off-policy replay, a stochastic actor, reparameterized gradients and soft value backups. Do not merge all algorithm versions into one diagram. The ICML 2018 version has separate V and target-V networks. The later Algorithms and Applications version removes separate V, uses target Q and discusses learned temperature. The pinned Spinning Up implementation follows the later value structure but fixes temperature. 2018 version Later version Pinned implementation
We focus on continuous actions with twin Q-functions and no separate V. The program fixes temperature. Automatic-temperature derivation and numerical checks are separate; the program does not claim to train adaptive temperature or reproduce robotics experiments.
Identify who generates an action and who values it
Sample from replay. Let denote true termination, target-critic parameters, and current actor parameters. Sample a fresh next-state action from the current actor and compute its log density using the same sample:
Replay supplies transitions. The next action is neither an old actor action stored in replay nor a TD3 target-actor action with smoothing noise. No target actor is required here: target Q changes slowly, but the current actor generates the action. True termination removes the entire continuation term, including next-step entropy. An external truncation still allows continuation unless the task itself has ended. Backup without V Actual implementation
After updating critics, minimize the actor loss:
The twin-Q minimum also participates in actor learning here, whereas the classic TD3 actor uses Q1 only. Freeze critic weights while preserving action-path derivatives. Where both Q-values coincide, the minimum may be nondifferentiable; the implementation chooses one branch as a subgradient. One sample supplies a stochastic gradient of the fixed-replay surrogate, not a claim of exact optimization of the original return over all states. Actor objective
For actions that can be sampled and differentiated, first draw parameter-independent Gaussian noise and then transform it into bounded actions. Allow a positive scale and center for each coordinate:
Subtracting the log absolute Jacobian determinant accounts for the same probability mass occupying a different width after compression. The transformed distribution is no longer Gaussian. Using the uncorrected Gaussian log density for compressed actions gives the wrong entropy term and actor derivatives. Change of variables
For large , floating-point tanh can round to ±1, making direct evaluation of problematic. Keep the pre-squash value and use the stable identity:
The program computes actions and log densities from the same , rather than applying inverse tanh to an action rounded to a boundary. Mathematical support is an open interval, though a floating-point output can reach an endpoint. Its finite log density comes from the retained numerical preimage, not a claim of a probability atom at the endpoint. Stable implementation
In one dimension with unit scale, let , and . The pathwise derivatives can be derived by hand. Let be the action derivative of the currently smaller critic, holding noise and critic parameters fixed:
The term comes from the tanh density correction; comes from the Gaussian log density’s term. Multiplying by state features then updates mean and log-standard-deviation parameters. The program clips log standard deviation to [−3,1], with zero derivative through the clipped path outside that interval. Central-difference consistency checks avoid nondifferentiable boundary points.
Automatic temperature addresses a different problem: require average entropy to be at least target . Hold the current policy samples fixed, call estimated entropy , and parameterize the nonnegative Lagrange multiplier as :
Insufficient entropy gives a negative gradient, so descent increases and temperature, increasing entropy’s weight in actor learning. The common update based on has the same sign but lacks the factor. It is not exactly the same gradient under the same parameterization. The pinned Spinning Up implementation does not perform this automatic adjustment. Temperature dual objective Fixed-temperature implementation
Separate three evaluation quantities
The original environment matches the DDPG and TD3 lessons: initial position is uniform on , reward is , next position is , termination occurs after two steps, and discount is 0.9. Each critic uses six quadratic features. Each phase’s actor has two linear mean parameters and two linear log-standard-deviation parameters, followed by tanh. Standard deviation can depend on position.
Using only the Python standard library, train for 6000 steps with 200 initial uniform exploration steps, replay capacity 2000, batch size 32 and fixed temperature 0.1. Critic and actor learning rates are 0.04 and 0.02; the target-critic coefficient is 0.01. Subsequent environment actions come directly from the stochastic actor, without additional DDPG-style exploration noise. Update both Q-functions, then the actor, then target Q-functions.
"""Original fixed-temperature SAC lesson; quadratic critics, not a deep benchmark."""
import json
import math
import random
def clip(x, low=-1.0, high=1.0):
return min(high, max(low, x))
def features(x, a):
return [1.0, x, a, x*x, x*a, a*a]
def value(w, x, a):
return sum(u*v for u, v in zip(w, features(x, a)))
def action_gradient(w, x, a):
return w[2] + w[4]*x + 2*w[5]*a
def policy(w, x):
return math.tanh(w[0]*x + w[1])
def transition(phase, x, a):
if phase not in (0, 1) or not -1 <= a <= 1:
raise ValueError('phase must be 0/1 and action in [-1,1]')
return 1.0-(a-0.5*x)**2, 0.5*(x+a), phase == 1
def bootstrap(reward, future, terminated, truncated=False, gamma=0.9):
# External collection limits do not erase the continuation value.
# A real terminal state takes precedence even if both flags are true.
return reward if terminated else reward + gamma*future
def evaluate(actor):
returns = []
for i in range(101):
x = -1.0 + 2.0*i/100
total = 0.0
for h in (0, 1):
a = policy(actor[h], x)
r, x, _ = transition(h, x, a)
total += (0.9**h)*r
returns.append(total)
return sum(returns)/len(returns)
def softplus(x):
return max(0.0, x) + math.log1p(math.exp(-abs(x)))
def sample(actor, x, epsilon, low=-1.0, high=1.0):
if not low < high or not all(math.isfinite(v) for v in (*actor, x, epsilon, low, high)):
raise ValueError('finite inputs and ordered action bounds required')
raw_log_std = actor[2]*x + actor[3]
log_std = clip(raw_log_std, -3.0, 1.0)
delta = math.exp(log_std)*epsilon
u = actor[0]*x + actor[1] + delta
z = math.tanh(u)
scale, center = (high-low)/2, (high+low)/2
log_jacobian = 2*(math.log(2)-u-softplus(-2*u))
logp = -0.5*epsilon**2 - 0.5*math.log(2*math.pi) - log_std - log_jacobian - math.log(scale)
return center+scale*z, logp, (z, delta, scale, -3 < raw_log_std < 1)
def actor_loss_gradient(actor, q1, q2, x, epsilon, alpha=0.1):
a, logp, (z, delta, scale, live_std) = sample(actor, x, epsilon)
v1, v2 = value(q1, x, a), value(q2, x, a)
# A deterministic subgradient at ties; finite-difference checks avoid ties.
chosen = q1 if v1 <= v2 else q2
path = action_gradient(chosen, x, a)*scale*(1-z*z)
gm = 2*alpha*z-path
gl = (-alpha+(2*alpha*z-path)*delta) if live_std else 0.0
return alpha*logp-min(v1,v2), [gm*x, gm, gl*x, gl], logp
def temperature_step(log_alpha, entropy, target_entropy, learning_rate=0.01):
# Exact gradient of exp(log_alpha)*(H-H_target), with H detached.
if learning_rate < 0 or not all(math.isfinite(v) for v in (log_alpha, entropy, target_entropy, learning_rate)):
raise ValueError('finite temperature arguments and nonnegative learning rate required')
return log_alpha-learning_rate*math.exp(log_alpha)*(entropy-target_entropy)
def train(seed=0, steps=6000, alpha=0.1):
if not math.isfinite(alpha) or alpha <= 0:
raise ValueError('positive finite alpha required')
explore, replay_rng = random.Random(seed), random.Random(seed+10000)
init, target_rng, actor_rng = (random.Random(seed+k) for k in (20000, 30000, 40000))
actor = [[0.0, 0.0, 0.0, -0.7] for _ in range(2)]
critics = [[[init.uniform(-0.05,0.05) for _ in range(6)] for _ in range(2)] for _ in range(2)]
targets = [[w[:] for w in q] for q in critics]
replay, capacity, tau = [], 2000, 0.01
initial = evaluate(actor)
phase, x, updates = 0, explore.uniform(-1, 1), 0
for t in range(steps):
a = explore.uniform(-1,1) if t < 200 else sample(actor[phase],x,explore.gauss(0,1))[0]
r, nx, terminal = transition(phase,x,a)
item = (phase,x,a,r,nx,terminal)
if len(replay) < capacity:
replay.append(item)
else:
replay[t % capacity] = item
phase,x = (0,explore.uniform(-1,1)) if terminal else (1,nx)
if t < 200:
continue
batch = [replay_rng.choice(replay) for _ in range(32)]
cg = [[[0.0]*6 for _ in range(2)] for _ in range(2)]
for h,sx,act,reward,next_x,done in batch:
future = 0.0
if not done:
na,lp,_ = sample(actor[1],next_x,target_rng.gauss(0,1))
future = min(value(q[1],next_x,na) for q in targets)-alpha*lp
y = bootstrap(reward,future,done)
for k,q in enumerate(critics):
error = value(q[h],sx,act)-y
for j,f in enumerate(features(sx,act)):
cg[k][h][j] += 2*error*f/len(batch)
for k,q in enumerate(critics):
for h in (0,1):
q[h] = [w-0.04*g for w,g in zip(q[h],cg[k][h])]
ag = [[0.0]*4 for _ in range(2)]
for h,sx,*_ in batch:
_,gradient,_ = actor_loss_gradient(actor[h],critics[0][h],critics[1][h],sx,actor_rng.gauss(0,1),alpha)
for j,g in enumerate(gradient):
ag[h][j] += g/len(batch)
for h in (0,1):
actor[h] = [w-0.02*g for w,g in zip(actor[h],ag[h])]
for qt,q in zip(targets,critics):
qt[h] = [(1-tau)*v+tau*w for v,w in zip(qt[h],q[h])]
updates += 1
evaluation_rng = random.Random(seed+50000)
rewards, soft_returns, entropies = [], [], []
for _ in range(1000):
sx = evaluation_rng.uniform(-1,1)
reward_return = soft_return = 0.0
for h in (0,1):
act,logp,_ = sample(actor[h],sx,evaluation_rng.gauss(0,1))
reward,sx,_ = transition(h,sx,act)
reward_return += 0.9**h*reward
soft_return += 0.9**h*(reward-alpha*logp)
entropies.append(-logp)
rewards.append(reward_return)
soft_returns.append(soft_return)
return {'seed':seed,'alpha':alpha,'initial':initial,'deterministic_final':evaluate(actor),
'stochastic_reward':sum(rewards)/len(rewards),'stochastic_soft_return':sum(soft_returns)/len(soft_returns),
'mean_entropy':sum(entropies)/len(entropies),'reward_optimum':1.9,
'critic_updates':updates,'actor_updates':updates,'actor':actor,'critics':critics}
if __name__ == '__main__':
print(json.dumps(train(),sort_keys=True))
Inspect the complete recorded output
{"actor": [[0.5412346442457966, 0.0031440163545796884, 0.0008827443153855828, -1.3717024479653757], [0.5255505201552346, 0.01410547334058794, 0.0007468602712448647, -1.3915726759208558]], "actor_updates": 5800, "alpha": 0.1, "critic_updates": 5800, "critics": [[[1.8467552675914314, 0.00034318610935943556, 0.0003385451321445187, -0.24414118079584754, 0.9727528208668991, -0.9746552795259257], [0.9973626973612275, 0.00026677615664755775, -0.0007388491919690741, -0.23391921500204577, 0.9509034177853424, -0.9585608565256443]], [[1.846750311403298, 0.000344020190230736, 0.00033758649904466905, -0.24412166767225482, 0.9726713244090277, -0.9745633241901841], [0.9974171866234459, 0.0002564365266644398, -0.0007200024926649706, -0.23443336320440183, 0.9520176943830062, -0.959143883142303]]], "deterministic_final": 1.899709453091233, "initial": 1.795875, "mean_entropy": -0.08136317148073031, "reward_optimum": 1.9, "seed": 0, "stochastic_reward": 1.8014228225018432, "stochastic_soft_return": 1.7857204171655978}Output separates three evaluations: deterministic-action return on a fixed 101-point grid; plain reward over 1000 independently sampled stochastic episodes; and soft return on those same stochastic episodes. Deterministic evaluation applies tanh to the Gaussian mean, which generally is not the mean of the transformed action distribution. Fixed-grid and random-start evaluations use different sampling designs; tiny differences should not become superiority claims.
All seeds 0–7 are retained. Mean deterministic evaluation is approximately 1.899827, mean stochastic reward 1.804782, and mean stochastic soft return 1.786261. Seed 0’s mean differential entropy is about −0.081363, so soft return can be below plain reward. The value 1.9 bounds plain reward in this task, not all soft objectives. These results do not show SAC outperforming DDPG or TD3 because training objectives and evaluated policies differ.
Checks cover analytic actor gradients against central differences, an independently integrated density close to 1, action-scale Jacobians, finite calculations at extreme preimages, temperature-update direction, termination masks and actual training for every seed. Update cost grows with batch size and model computation; for these fixed small features it is linear in batch size, with replay space linear in capacity. Neural versions additionally incur network forward/backward and optimizer-state costs.
State the temperature, coordinates and version
Action units affect differential entropy. For a positive one-dimensional scaling:
The entropy target must transform consistently. In the pinned Spinning Up code, actions are multiplied by act_limit but log density remains in normalized action coordinates. Our general sampling function explicitly includes the scale term; actual training uses . A fixed scale constant does not alter the local actor derivative at a given state, but changes value constants. With variable episode lengths or automatic temperature, coordinate changes cannot be described unconditionally as having no effect. Code coordinate convention
Exact soft policy iteration arguments require their finite-action and exact-update conditions. Neural critics, restricted policy classes, stochastic gradients and alternating steps that have not converged do not automatically inherit a general optimality guarantee. A tanh Gaussian can struggle with complex multimodal action preferences. Twin critics sharing replay are not independent confidence estimators either. Theory scope Approximation and temperature
On PDF 6 of the later v2 paper, Eq. 7 writes Q with two state arguments, while Eq. 9 on the same page uses a state and an action. This article follows Eq. 9 and the fixed implementation. Citations refer to the reviewed scope; downloadable papers and the authors’ robot demonstrations are not treated as project-side validation. Version check
Track densities and update directions
- A nonterminal transition has reward 1, discount 0.9, target Q-values 3 and 2, next-action log density −0.5, and temperature 0.2. What is the backup?
Answer: Choose 2, then subtract 0.2×(−0.5), giving continuation 2.1. The target is 1+0.9×2.1=2.89. True termination still gives 1.
- At with unit scale and a standard Gaussian, what is the tanh Jacobian correction? What if actions are scaled to ?
Answer: Tanh has derivative 1 at zero, so its log correction is 0. Scaling by 2 additionally subtracts . The Gaussian’s own log density at zero must still be computed; zero correction does not mean density 1.
- Current mean entropy is −0.5, target entropy −0.2 and temperature 0.2. What is the exact log-temperature gradient used in the derivation, and which way does the update move?
Answer: The gradient is 0.2×(−0.3)=−0.06. Gradient descent increases log temperature and strengthens the actor’s entropy preference. The surrogate omitting the temperature factor gives −0.3: same direction, different step scale.
- Does higher deterministic test return than stochastic test return show that entropy regularization failed?
Answer: No. The soft training objective differs from plain reward, and deterministic evaluation changes the policy. Report stochastic reward, soft return, deterministic return, seeds and sampling designs, then judge against task needs instead of selecting only one score.
Identify the algorithm version before comparing code
The 2018 paper explains explicit V and soft policy iteration; our reading covers PDF 3–5. 2018 methods The later v2 reading covers PDF 4–8 and 16, including target Q, temperature objectives and the tanh change of variables. It is not a complete proof or robotics audit. Later methods The pinned Spinning Up commit supports checks of current-policy sampling, twin Q, fixed temperature, stable log densities and action coordinates. No upstream code was executed or copied. Implementation reading
Make a prediction, then check
How does later SAC without a separate V generate the next target action?
Learning objectives
- Compute squashed Gaussian log density and check pathwise actor derivatives.
- Distinguish fixed and learned temperature and transform entropy targets consistently with action coordinates.
Prerequisites & connections
- Maximum entropy reinforcement learning
- The reparameterization trick
- Deep deterministic policy gradient
References
- Soft Actor-Critic — ICML2018 scoped methods
Tuomas Haarnoja; Aurick Zhou; Pieter Abbeel; Sergey Levine · 2018 - Soft Actor-Critic Algorithms and Applications — arXiv v2 methods
Tuomas Haarnoja; Aurick Zhou; Kristian Hartikainen; George Tucker; Sehoon Ha; Jie Tan; Vikash Kumar; Henry Zhu; Abhishek Gupta; Pieter Abbeel; Sergey Levine · 2019 - Spinning Up — SAC fixed-commit methods
OpenAI; Joshua Achiam and contributors · 2020
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: PMLR80:1861–1870. Read PDF3–5: exact finite-action theory versus approximate training, explicit V/target V, twin Q and reparameterization. Full appendices and benchmark replication excluded. First2018-12-13, v2 dated2019-01-29. Read PDF4–8 and16, viewed6: target Q, current stochastic actor, dual temperature and tanh Jacobian. Eq9 resolves Eq7 Q(s,s) notation; no complete proof audit or robot replication. Docs1–236, main file179–323, all98 core lines; fixed alpha, current policy, stable tanh density and normalized action coordinates. Fixed commit; reference only, no upstream execution or copying. 7 paired equations and four explained exercises. Later no-V SAC uses current-policy next actions, twin critics and fixed alpha in the original teaching program. Pathwise gradients, stable tanh/scaling Jacobians, density quadrature, clipping and temperature-direction examples tested. Eight seeds preserve stochastic reward, soft return and deterministic evaluation separately; automatic temperature was not trained.
- Later no-V SAC uses current-policy next actions, twin critics and fixed alpha in the original teaching program. Pathwise gradients, stable tanh/scaling Jacobians, density quadrature, clipping and temperature-direction examples tested. Eight seeds preserve stochastic reward, soft return and deterministic evaluation separately; automatic temperature was not trained.
- Four computed SVG variants per topic;10 numeric/geometry tests and24 current responsive cases passed. All eight selected current captures directly viewed; all four groups use the checked initial captures. Actual assets and manuscripts are SHA bound. Full article acceptance recorded separately.
Source locations checked:
- Soft Actor-Critic — ICML2018 scoped methods · PMLR80:1861–1870. Read PDF3–5: exact finite-action theory versus approximate training, explicit V/target V, twin Q and reparameterization. Full appendices and benchmark replication excluded.
- Soft Actor-Critic Algorithms and Applications — arXiv v2 methods · First2018-12-13, v2 dated2019-01-29. Read PDF4–8 and16, viewed6: target Q, current stochastic actor, dual temperature and tanh Jacobian. Eq9 resolves Eq7 Q(s,s) notation; no complete proof audit or robot replication.
- Spinning Up — SAC fixed-commit methods · Docs1–236, main file179–323, all98 core lines; fixed alpha, current policy, stable tanh density and normalized action coordinates. Fixed commit; reference only, no upstream execution or copying.
Related topics