Module contents
Stage 6 of 8Advanced 110 min

SAC: off-policy maximum entropy learning

Implement Soft Actor-Critic with replay, twin critics and soft targets, a tanh-squashed Gaussian and automatic temperature, then compare SAC and PPO in environment steps and wall time.

After this lesson you can

  • Implement the replay buffer and double-Q critic updates with soft targets.
  • Implement the tanh-squashed policy and Jacobian correction in log probability.
  • Adjust temperature automatically toward target entropy.
  • Compare SAC and PPO in sample efficiency and wall time.

Before you start

A million steps PPO throws away

In PPO from scratch you trained a cheetah for one million environment steps with five seeds. The five policies’ HalfCheetah-v5 IQM was 1331 (95% bootstrap interval: 1265 to 1916). Each transition was used in four epochs of its own 2000-step rollout and then discarded: PPO’s clipped objective is valid only for data from the generating policy or a very similar one. At the end the agent retains no memory of step 10,000.

Off-policy algorithms break this restriction. They store each transition (s,a,r,s′)(s, a, r, s') in a buffer and reuse it in thousands of updates long after the generating policy changes. Soft Actor-Critic (SAC) is a canonical continuous-control example, and with the same million steps reference implementations reach returns around 9500 on HalfCheetah: CleanRL’s table gives 9634.89±1423.739634.89 \pm 1423.73 and the Stable-Baselines3 zoo 9535.459535.45. Seven times more return with the same data.

That figure hides a catch this lesson measures: a SAC step costs much more computation than a PPO step, because every new transition accompanies one gradient step for two critics and actor with batch size 256, plus passes through two target copies. If simulation is cheap, minutes rather than steps are scarce, so an honest comparison has two axes: return versus steps and return versus wall time.

SAC combines four ideas, each addressing a specific problem:

  1. Maximum entropy. Reward and policy randomness are both valued. The optimal policy becomes a Boltzmann distribution over actions rather than deterministic, providing exploration and robustness without noise heuristics.
  2. Two critics and target networks. Bellman target uses the minimum of two QQ estimates and slow-moving copies so the actor does not exploit optimistic critic errors.
  3. A Gaussian squashed by tanh. Actions live in a box; policy is a Gaussian transformed by tanh, whose log density needs Jacobian correction.
  4. Automatic temperature. Instead of fixing entropy weight, specify desired entropy and adapt temperature like a Lagrange multiplier.

Maximum entropy: objective and optimal policy

You saw the idea in the reinforcement-learning module. Here precision matters because every SAC loss term follows from these definitions.

Notice entropy’s position: Qπ(s,a)Q^\pi(s, a) excludes the current step’s entropy (action is already chosen) but includes all future entropy because Vπ(s′)V^\pi(s') accumulates it. Term −αlog⁡π(a∣s)-\alpha\log\pi(a \given s) is a one-sample unbiased estimator of αH⁡\alpha\Ent: its expectation is exactly α H⁡(π(⋅∣s))\alpha\,\Ent(\pi(\cdot \given s)). This makes everything below implementable without integrating entropy: evaluate sampled action log density instead.

Now fix the critic and consider one state. Which action distribution maximizes Eπ[Q(s,a)]+α H⁡(π)\E_\pi[Q(s, a)] + \alpha\,\Ent(\pi)? A classical statistical-physics result answers.

Proof

Since log⁡pQ(a∣s)=Q(s,a)/α−log⁡Z(s)\log p_Q(a \given s) = Q(s, a)/\alpha - \log Z(s), we have Q(s,a)=αlog⁡pQ(a∣s)+αlog⁡Z(s)Q(s, a) = \alpha\log p_Q(a \given s) + \alpha\log Z(s). Take expectation under π\pi and add α H⁡(π)=−α Eπ[log⁡π]\alpha\,\Ent(\pi) = -\alpha\,\E_\pi[\log \pi]:

Eπ[Q]+α H⁡(π)=αlog⁡Z(s)+α Eπ[log⁡pQ−log⁡π]=αlog⁡Z(s)−α KL⁡(π ∥ pQ).\E_\pi[Q] + \alpha\,\Ent(\pi) = \alpha\log Z(s) + \alpha\,\E_\pi\bigl[\log p_Q - \log \pi\bigr] = \alpha\log Z(s) - \alpha\,\KL(\pi \,\|\, p_Q).

Kullback-Leibler divergence is nonnegative and zero only when the densities coincide almost everywhere (Gibbs inequality).

∎

Two immediate readings. Optimal-policy state value is V(s)=αlog⁡∫exp⁡(Q/α) ⁣daV(s) = \alpha\log\int\exp(Q/\alpha)\dd a, a soft maximum: as α→0\alpha \to 0 it tends to max⁡aQ(s,a)\max_a Q(s, a) and the distribution concentrates on the argmax (recovering classical control); as α\alpha grows, if the action set is bounded (a box as in MuJoCo), policy approaches uniform. And any policy’s gap to optimum in the objective is exactly α KL⁡(π ∥ pQ)\alpha\,\KL(\pi\,\|\,p_Q).

The practical problem is that pQp_Q cannot be sampled: with actions in R6\R^6 and a network-defined QQ, constant Z(s)Z(s) is an intractable integral. SAC settles for the best policy in a tractable family Π\Pi (squashed Gaussians here), defining improvement as projection:

πnueva(⋅∣s)=arg min⁡π′∈ΠKL⁡(π′(⋅∣s) ∥ exp⁡(Qπvieja(s,⋅)/α)Z(s)).\pi_{\text{nueva}}(\cdot \given s) = \argmin_{\pi' \in \Pi} \KL\Bigl(\pi'(\cdot \given s) \,\Big\|\, \frac{\exp\bigl(Q^{\pi_{\text{vieja}}}(s, \cdot)/\alpha\bigr)}{Z(s)}\Bigr).

By the theorem, minimizing that divergence equals maximizing Eπ′[Q]+α H⁡(π′)\E_{\pi'}[Q] + \alpha\,\Ent(\pi'), and Z(s)Z(s) disappears: it does not depend on π′\pi'. The figure shows what projection means when the family is too limited.

InteractivePolicy improvement projects a Boltzmann distribution
Fixed critic Q(a)Q(a)
Densities over action aa
  • Boltzmann pQ∝eQ/αp_Q \propto e^{Q/\alpha}: unconstrained optimum
  • Gaussian π=N(m,s2)\pi = \Normal(m, s^2)
  • Q(a)Q(a)
0.300
0.90
Gaussian policy
Starting peak
Eπ[Q]\E_\pi[Q]0.718
α H⁡(π)\alpha\,\Ent(\pi)0.034
Objective J(π)=Eπ[Q]+αH⁡(π)J(\pi)=\E_\pi[Q]+\alpha\Ent(\pi)0.751
Bound αlog⁡Z\alpha\log Z (Boltzmann)1.010
Gap α KL⁡(π ∥ pQ)\alpha\,\KL(\pi\,\|\,p_Q)0.2587
Peak covered by the Gaussianright
From the other peak the fit ends at m=−1.19m = −1.19 with J=0.819J = 0.819. The other fit is better, so this fit is stuck at a local optimum.
Above: fixed two-peaked critic Q(a)Q(a). Below in blue: Boltzmann policy pQ∝eQ/αp_Q \propto e^{Q/\alpha}, the unrestricted optimum; orange: best Gaussian found by gradient ascent from the chosen side. Readouts show both objective parts and the gap to bound αlog⁡Z\alpha\log Z, exactly α KL⁡(π ∥ pQ)\alpha\,\KL(\pi\,\|\,p_Q). With small α\alpha the Gaussian chooses one peak; with large α\alpha it covers both. Try manual mode too.

The figure teaches three facts recurring in real training. At low temperature projection is a narrow Gaussian over one mode and depends on starting point: two initializations reach different local optima and gradient ascent does not jump between them. At high temperature the Gaussian widens to cover both peaks despite paying for mass in the valley: exploration purchased by entropy. And gap α KL⁡\alpha\,\KL is never zero unless pQp_Q is Gaussian: the family limits what can be reached.

Proof

Since πvieja∈Π\pi_{\text{vieja}} \in \Pi, the projection cannot be worse than it under the minimized objective. By Gibbs’ principle this means, in every state,

Ea∼πnueva[Qπvieja(s,a)−αlog⁡πnueva(a∣s)]≥Ea∼πvieja[Qπvieja(s,a)−αlog⁡πvieja(a∣s)]=Vπvieja(s).\E_{a \sim \pi_{\text{nueva}}}\bigl[Q^{\pi_{\text{vieja}}}(s, a) - \alpha\log\pi_{\text{nueva}}(a \given s)\bigr] \ge \E_{a \sim \pi_{\text{vieja}}}\bigl[Q^{\pi_{\text{vieja}}}(s, a) - \alpha\log\pi_{\text{vieja}}(a \given s)\bigr] = V^{\pi_{\text{vieja}}}(s).

Expand the soft Bellman equation of πvieja\pi_{\text{vieja}} and apply that inequality at each next state:

Qπvieja(s0,a0)=r0+γ Es1[Vπvieja(s1)]≤r0+γ Es1,a1∼πnueva[Qπvieja(s1,a1)−αlog⁡πnueva(a1∣s1)].Q^{\pi_{\text{vieja}}}(s_0, a_0) = r_0 + \gamma\,\E_{s_1}\bigl[V^{\pi_{\text{vieja}}}(s_1)\bigr] \le r_0 + \gamma\,\E_{s_1, a_1 \sim \pi_{\text{nueva}}}\bigl[Q^{\pi_{\text{vieja}}}(s_1, a_1) - \alpha\log\pi_{\text{nueva}}(a_1 \given s_1)\bigr].

Repeating for Qπvieja(s1,a1)Q^{\pi_{\text{vieja}}}(s_1, a_1) and so on turns the upper bound into discounted reward and entropy sum of πnueva\pi_{\text{nueva}} starting at (s0,a0)(s_0, a_0), which is Qπnueva(s0,a0)Q^{\pi_{\text{nueva}}}(s_0, a_0). The series remainder is multiplied by γn\gamma^n and tends to zero because values are bounded.

∎

Alternating soft evaluation (iterating QπQ^\pi’s Bellman equation, a sup-norm contraction for the same reason as the classical one) and soft improvement gives soft policy iteration, converging to the optimum within Π\Pi in the tabular case. SAC approximates it with one gradient step for each per environment step. The tabular guarantee does not transfer to neural networks, but the structure does: each loss implemented below is one of these steps.

The cell checks Gibbs’ principle in one state with four discrete actions, where everything is exact: no random policy exceeds the bound, Boltzmann reaches it, and the two temperature limits yield argmax and uniform.

[ ]The Gibbs principle in a discrete stateBrowser
import numpy as np

q = np.array([1.0, 0.8, -0.5, 0.2])
rng = np.random.default_rng(0)

def objetivo(P, alpha):
    """E_pi[Q] + alpha H(pi) para cada fila de P (una política por fila)."""
    P = np.atleast_2d(P)
    plogp = np.where(P > 0, P * np.log(np.where(P > 0, P, 1.0)), 0.0)
    return P @ q - alpha * plogp.sum(axis=1)

al_azar = rng.dirichlet(np.ones(4), size=20000)              # 20000 políticas aleatorias
for alpha in (0.05, 0.3, 3.0):
    cota = alpha * np.log(np.sum(np.exp(q / alpha)))       # alpha * log Z
    boltz = np.exp((q - q.max()) / alpha)
    boltz /= boltz.sum()
    j_boltz, mejor = objetivo(boltz, alpha)[0], objetivo(al_azar, alpha).max()
    print(f'alpha = {alpha:4.2f}  cota = {cota:.4f}  Boltzmann = {j_boltz:.4f}  '
          f'mejor de 20000 al azar = {mejor:.4f}  pi = {np.round(boltz, 3)}')
    assert abs(j_boltz - cota) < 1e-12 and mejor <= cota

With α=0.05\alpha = 0.05 the policy places 98% of mass on the best action and the bound lies 0.0010.001 from maximum QQ; with α=3\alpha = 3 distribution is nearly uniform and the bound greatly exceeds the maximum because entropy also scores.

Critics: double Q, target networks and soft updates

With a transition buffer (s,a,r,s′,d)(s, a, r, s', d), where d=1d = 1 if the episode truly terminated in s′s', soft evaluation becomes regression. Sample a new action a′∼πϕ(⋅∣s′)a' \sim \pi_\phi(\cdot \given s') from the current policy (not the buffer) and fit each critic to target

y=r+γ(1−d)[min⁡i=1,2Qθˉi(s′,a′)−αlog⁡πϕ(a′∣s′)],L(θi)=Ebuˊfer[(Qθi(s,a)−y)2],y = r + \gamma(1 - d)\Bigl[\min_{i = 1, 2} Q_{\bar\theta_i}(s', a') - \alpha\log\pi_\phi(a' \given s')\Bigr], \qquad \Loss(\theta_i) = \E_{\text{búfer}}\bigl[(Q_{\theta_i}(s, a) - y)^2\bigr],

without propagating gradients through yy. Sampling the next action from the current policy makes this target valid off-policy: the buffer only supplies (s,a)(s, a) pairs where the function is fitted, just as in Q-learning, and the expectation over a′a' defining Vπ(s′)V^\pi(s') is estimated using the policy being evaluated. No importance ratio is needed. Buffer pair distribution (s,a)(s, a) only determines where regression fits best.

This extends DQN experience replay to continuous actions. Two pieces remain: the minimum and bars over θ\theta.

Why the minimum of two critics

The actor seeks actions where the critic is high. With critic errors, chosen actions systematically have positive error: maximization bias. With KK equal-true-value actions and independent errors εk∼N(0,σ2)\eps_k \sim \Normal(0, \sigma^2), the chosen action’s estimated value is E[max⁡kεk]>0=max⁡kE[εk]\E[\max_k \eps_k] > 0 = \max_k \E[\eps_k] by Jensen applied to convex max⁡\max. At K=10K = 10 bias is 1.539 σ1.539\,\sigma. Bellman target feeds it back: overestimated s′s' enters yy, the critic learns it and error accumulates over effective horizon 1/(1−γ)=1001/(1-\gamma) = 100 steps.

Tabular double Q decouples selection and evaluation. For actor-critic, Fujimoto, van Hoof and Meger (2018) observe critics are too correlated for decoupling and propose clipped double Q: evaluate with the minimum of two independently trained critics. ICML 2018 SAC already uses it citing that work; the 2018b version retains it.

InteractiveBias in the value entering the target
Error of the value used in the target (true value 0), 6000 repetitions
  • single critic: max⁡kQ^1(ak)\max_k \hat Q_1(a_k)
  • Double Q: Q^2\hat Q_2 at arg⁡max⁡kQ^1\arg\max_k \hat Q_1
  • minimum of two: max⁡kmin⁡iQ^i(ak)\max_k \min_i \hat Q_i(a_k)
10
1.00
0.00
Bias of max⁡kQ^1\max_k \hat Q_11.550
Theory: σ E[max⁡kZk]\sigma\,\E[\max_k Z_k]1.539
Decoupled Double Q bias0.008
Bias of max⁡kmin⁡(Q^1,Q^2)\max_k \min(\hat Q_1, \hat Q_2)0.676
Bias with critic feedback, γb/(1−γ)\gamma b/(1-\gamma) at γ=0.99\gamma=0.99153.4
All actions truly have value 0; each critic sees value with noise deviation σ\sigma, and the two critics have correlation ρ\rho on the same action. Compare three estimators for the chosen action’s value over 6000 fixed-seed repeats: one critic’s maximum (red), decoupled double Q (aqua), and maximum of two critics’ minimum as in TD3 and SAC (blue). Dashed lines are means.

The minimum does not remove optimism; it clips it. With K=10K = 10 actions and independent critics, bias of one critic’s maximum is 1.54 σ1.54\,\sigma and maximum of the minimum 0.68 σ0.68\,\sigma; at K=2K = 2 it is already slightly negative, and with one action and no selection clearly pessimistic. Decoupled double Q is unbiased with independent critics, but independence is exactly what fails in actor-critic. Everything depends on critic disagreement. Raise ρ\rho toward 1 and the minimum stops correcting: identical estimates have the same error, preserved by the minimum. Hence critics have different initializations and separate gradients despite a shared target. Pessimism without selection has a closed form.

Proof

For real numbers, min⁡(x,y)=12(x+y)−12∣x−y∣\min(x, y) = \tfrac{1}{2}(x + y) - \tfrac{1}{2}\abs{x - y}. Difference X−YX - Y is Gaussian with mean 0 and variance 2σ2(1−ρ)2\sigma^2(1 - \rho), and for W∼N(0,τ2)W \sim \Normal(0, \tau^2) we have E∣W∣=τ2/π\E\abs{W} = \tau\sqrt{2/\pi}. Therefore E[min⁡(X,Y)]=μ−122σ2(1−ρ)2/π=μ−σ(1−ρ)/π\E[\min(X, Y)] = \mu - \tfrac12\sqrt{2\sigma^2(1-\rho)}\sqrt{2/\pi} = \mu - \sigma\sqrt{(1-\rho)/\pi}.

∎

With independent critics and σ=1\sigma = 1, the minimum underestimates by 0.5640.564; at ρ=0.5\rho = 0.5 by 0.3990.399; at ρ=1\rho = 1 it does nothing. The minimum therefore trades some optimistic bias for pessimistic bias across all actions, an attractive trade for an asymmetric reason: the actor pursues and amplifies positive errors, whereas a negative action error merely causes the actor to avoid that action, which then leaves the target. The cell reproduces figure and theorem numbers.

[ ]Maximization bias and the minimum of two criticsBrowser
import numpy as np
from scipy import integrate, stats

g = np.random.default_rng(1)
n, K, sigma = 200_000, 10, 1.0
e_max = integrate.quad(lambda x: x * K * stats.norm.pdf(x) * stats.norm.cdf(x) ** (K - 1), -10, 10)[0]
print(f'teoría E[max de {K} normales] = {e_max:.4f}')
for rho in (0.0, 0.5, 0.9):
    z1 = g.standard_normal((n, K))
    z2 = rho * z1 + np.sqrt(1 - rho**2) * g.standard_normal((n, K))
    q1, q2 = sigma * z1, sigma * z2
    un_critico = q1.max(axis=1).mean()
    doble = q2[np.arange(n), q1.argmax(axis=1)].mean()
    minimo = np.minimum(q1, q2).max(axis=1).mean()
    sin_seleccion = np.minimum(q1[:, 0], q2[:, 0]).mean()
    print(f'rho = {rho:.1f}: un crítico {un_critico:+.3f}   doble Q {doble:+.3f}   '
          f'max del mínimo {minimo:+.3f}   mínimo sin selección {sin_seleccion:+.3f} '
          f'(teoría {-sigma * np.sqrt((1 - rho) / np.pi):+.3f})')

Target networks with Polyak averaging

Target yy uses critic copies θˉi\bar\theta_i not updated by gradient: after each step they mix with live parameters, θˉ←(1−τ)θˉ+τθ\bar\theta \leftarrow (1 - \tau)\bar\theta + \tau\theta, with τ=0.005\tau = 0.005. Expanding the recurrence,

θˉt=∑j≥0τ(1−τ)j θt−j(maˊs un teˊrmino inicial que decae como (1−τ)t),\bar\theta_t = \sum_{j \ge 0} \tau(1 - \tau)^j\,\theta_{t - j} \quad (\text{más un término inicial que decae como } (1-\tau)^t),

an exponential moving average of recent parameters. Weights sum to 1, mean delay is (1−τ)/τ=199(1 - \tau)/\tau = 199 updates and parameters from 200 or more updates ago collectively retain (1−τ)200=36.7 %(1 - \tau)^{200} = 36.7\,\% of weight. As with DQN’s target network, if yy depended on the same parameters being fitted, every regression step would move the target too; function approximation, bootstrap and off-policy data (the deadly triad) can diverge together. A slow copy makes each update regression toward a nearly fixed target.

Termination is not truncation

Factor (1−d)(1 - d) zeroes future value only if s′s' is MDP terminal. HalfCheetah never terminates: episodes truncate at 1000 steps due to an external time limit. The cheetah at step 1000 keeps running; value of s′s' is not zero. Saving done = terminated or truncated teaches the critic at each episode end that running has no future value. Since observation excludes time, the critic cannot even know which states are near the cutoff: step-1000 state resembles any running state, so the false end creates contradictory targets for ordinary states (sometimes r+γVr + \gamma V, sometimes only rr) and, through bootstrap, downward bias spreading to neighbors. As in the PPO implementation, store terminated and the actual next observation, not the reset observation.

Actor: reparameterization, tanh and corrected log probability

Soft improvement minimizes, at buffer states,

L(ϕ)=Es∼buˊfer Ea∼πϕ(⋅∣s)[αlog⁡πϕ(a∣s)−min⁡iQθi(s,a)].\Loss(\phi) = \E_{s \sim \text{búfer}}\,\E_{a \sim \pi_\phi(\cdot \given s)}\Bigl[\alpha\log\pi_\phi(a \given s) - \min_i Q_{\theta_i}(s, a)\Bigr].

The inner expectation depends on ϕ\phi through the distribution of aa. PPO handled this with the score-function estimator ∇ϕlog⁡πϕ\grad_\phi\log\pi_\phi times a weight. Here there is a better option: the critic is differentiable in action, so express action deterministically in ϕ\phi and noise independent of ϕ\phi, a=fϕ(ε;s)a = f_\phi(\eps; s) with ε∼N(0,I)\eps \sim \Normal(\vb{0}, \mat{I}), and differentiate inside the expectation:

∇ϕL=Es,ε[α∇ϕlog⁡πϕ(fϕ(ε;s)∣s)−∇amin⁡iQθi(s,a)∣a=fϕ(ε;s) ∇ϕfϕ(ε;s)].\grad_\phi\Loss = \E_{s, \eps}\Bigl[\alpha\grad_\phi\log\pi_\phi\bigl(f_\phi(\eps; s) \given s\bigr) - \grad_a \min_i Q_{\theta_i}(s, a)\big|_{a = f_\phi(\eps; s)}\,\grad_\phi f_\phi(\eps; s)\Bigr].

This is the variational autoencoder reparameterization trick. The critic term uses slope ∇aQ\grad_a Q: it says which way to move the action, not just whether it was good or bad. This first-order information makes SAC actor gradient much lower variance than the score-function gradient, and explains why SAC needs a Q(s,a)Q(s, a) critic rather than just V(s)V(s).

A Gaussian inside a box

In PPO’s Gaussian parameterization, actions were clipped to bounds when sent to the environment and log probability computed before clipping. For PPO this is a detail: the probability ratio uses the same unclipped action in numerator and denominator. In SAC it does not work: log density enters the objective as entropy, and a clipped Gaussian places point mass at boundaries where its density does not exist. The solution is a smooth bijection from latent space to the box.

Proof

Map g(u)=b+c⊙tanh⁡(u)g(\vb{u}) = \vb{b} + \vb{c}\odot\tanh(\vb{u}) is a differentiable bijection from Rd\R^d into the box interior with differentiable inverse, acting componentwise, so its Jacobian is diagonal with entries ∂ai/∂ui=ci(1−tanh⁡2ui)>0\partial a_i/\partial u_i = c_i(1 - \tanh^2 u_i) > 0. By change of variables in densities, pA(a)=pU(u) ∣det⁡∂g/∂u∣−1p_{\vb{A}}(\vb{a}) = p_{\vb{U}}(\vb{u})\,\abs{\det \partial g/\partial \vb{u}}^{-1} with u=g−1(a)\vb{u} = g^{-1}(\vb{a}). A diagonal determinant is the product of entries and its logarithm their log sum (the log-determinant composition rule also separates tanh and affine parts). Since u\vb{u} components are independent, log⁡pU\log p_{\vb{U}} is also a componentwise sum.

∎

The minus sign has a geometric reading: tanh contracts the line, and compressing the same mass into a shorter interval increases density. Near boundaries contraction is enormous because 1−tanh⁡2u≈4e−2∣u∣1 - \tanh^2 u \approx 4e^{-2\abs{u}}, and a wide latent Gaussian accumulates mass against box walls.

InteractiveSquashing a Gaussian with tanh
Density of latent variable U∼N(μ,σ2)U \sim \Normal(\mu, \sigma^2)
The map a=tanh⁡ua = \tanh u
Density of action A=tanh⁡UA = \tanh U
  • pU(u)p_U(u)
  • pA(a)p_A(a)
  • band [u−δ,u+δ][u-\delta, u+\delta]
  • image under tanh: same probability mass
0.50
0.80
1.20
a=tanh⁡ua = \tanh u0.833655
log⁡pU(u)\log p_U(u)−1.0786
Stable log⁡(1−tanh⁡2u)\log(1-\tanh^2 u)−1.1874
Naive calculation in float32−1.1874
Corrected log⁡pA(a)\log p_A(a)0.1088
Probability mass in each band0.0815
H⁡(U)\Ent(U) / H⁡(A)\Ent(A) in nats1.196 / 0.510
P(∣A∣>0.99)\Pr(\abs{A} > 0.99)0.4 %
Top: latent variable UU density; middle: map a=tanh⁡ua = \tanh u; bottom: action density. Orange band [u−δ,u+δ][u - \delta, u + \delta] and its aqua image have equal mass: the image is narrower by factor 1−tanh⁡2u1 - \tanh^2 u and therefore taller. Drag the point or use slider uu through 12, and compare stably computed Jacobian term with naive float32 calculation.

Three observations. Initially μ=0.5\mu = 0.5 and σ=0.8\sigma = 0.8, the latent Gaussian is an ordinary bell but action density already peaks at a≈0.94a \approx 0.94 near a boundary. With σ=1.4\sigma = 1.4 and μ=0.8\mu = 0.8 the peak, pressed against a=1a = 1, reaches density near 18, and raising σ\sigma to 3 gives two boundary peaks and a central valley: more latent variance does not mean more action randomness. Entropy confirms it: H⁡(U)\Ent(U) grows without bound with σ\sigma, but H⁡(A)\Ent(A) rises, peaks and falls. At u=9u = 9 naive float32 already gives the wrong number (−15.94-15.94 instead of −16.61-16.61); from u≈9.01u \approx 9.01, −∞-\infty.

The Jacobian without cancellation

In float32, tanh(u) is exactly 1 for u≳9.01u \gtrsim 9.01, and log(1 - tanh(u)**2) returns log⁡0=−∞\log 0 = -\infty; before then subtraction 1−tanh⁡2u1 - \tanh^2 u has already lost nearly all digits. One −∞-\infty in a batch makes actor loss NaN. The stable form comes from writing tanh⁡\tanh using exponentials:

1−tanh⁡2u=1cosh⁡2u=4(eu+e−u)2=4e−2u(1+e−2u)2,1 - \tanh^2 u = \frac{1}{\cosh^2 u} = \frac{4}{(e^{u} + e^{-u})^2} = \frac{4e^{-2u}}{(1 + e^{-2u})^2},

and taking logarithms,

log⁡(1−tanh⁡2u)=2(log⁡2−u−softplus⁡(−2u)),softplus⁡(x)=log⁡(1+ex).\log\bigl(1 - \tanh^2 u\bigr) = 2\bigl(\log 2 - u - \operatorname{softplus}(-2u)\bigr), \qquad \operatorname{softplus}(x) = \log(1 + e^x).

The expression is exact for every real uu and never subtracts nearly equal numbers: for large uu, softplus(-2u) is tiny and result is ≈2log⁡2−2u\approx 2\log 2 - 2u; for very negative uu, softplus(-2u) ≈−2u=2∣u∣\approx -2u = 2\abs{u} and result is ≈2log⁡2−2∣u∣\approx 2\log 2 - 2\abs{u}: ∣u∣\abs{u} and 2∣u∣2\abs{u}, numbers of different magnitudes, are subtracted without catastrophic cancellation, provided softplus is stably implemented (as in PyTorch and np.logaddexp). It is evaluated at uu, always available when sampling: tanh never needs to be inverted from the action, which also fails at boundaries.

What the box does to entropy

Integrating log density under UU gives a useful per-dimension formula:

H⁡(A)=H⁡(U)+E[log⁡(1−tanh⁡2U)]≤H⁡(U),\Ent(A) = \Ent(U) + \E\bigl[\log(1 - \tanh^2 U)\bigr] \le \Ent(U),

because the second term is negative. There is also an absolute ceiling: maximum-entropy distribution on (−1,1)(-1, 1) is uniform with log⁡2≈0.693\log 2 \approx 0.693 nats. No squashed Gaussian reaches it: the family maximum is 0.6840.684 nats at μ=0\mu = 0 and σ≈0.874\sigma \approx 0.874. This constrains reasonable target entropies.

Finally the deterministic evaluation action b+c⊙tanh⁡(μ)\vb{b} + \vb{c}\odot\tanh(\vb{\mu}) is the image of the latent median and therefore each action component’s median, not its mean: tanh is monotone and preserves quantiles, not expectations. The cell checks normalization, stability and that entropy maximum in NumPy.

[ ]Checking the squashed densityBrowser
import numpy as np
from scipy.integrate import quad
from scipy.optimize import minimize_scalar

def log_jac(u):
    return 2 * (np.log(2.0) - u - np.logaddexp(0.0, -2 * u))   # logaddexp(0, x) = softplus(x)

def log_pa(u, mu, s):
    return -0.5 * ((u - mu) / s) ** 2 - np.log(s) - 0.5 * np.log(2 * np.pi) - log_jac(u)

for mu, s in [(0.8, 1.4), (0.0, 3.0), (2.0, 0.3)]:
    area = quad(lambda a: np.exp(log_pa(np.arctanh(a), mu, s)), -1, 1, limit=200)[0]
    print(f'mu = {mu}, sigma = {s}: integral de p_A en (-1, 1) = {area:.8f}')

u = np.array([3.0, 6.0, 9.0, 10.0, 12.0], dtype=np.float32)
with np.errstate(divide='ignore'):
    ingenua = np.log(np.float32(1) - np.tanh(u) ** 2)
print('float32 ingenua:', ingenua)
print('estable        :', log_jac(u.astype(np.float64)).round(4))

def entropia_a(s, mu=0.0):
    f = lambda u: np.exp(-0.5 * ((u - mu) / s) ** 2) / (s * np.sqrt(2 * np.pi)) * log_jac(u)
    return 0.5 * np.log(2 * np.pi * np.e * s * s) + quad(f, mu - 12 * s, mu + 12 * s)[0]

r = minimize_scalar(lambda s: -entropia_a(s), bounds=(0.1, 5), method='bounded')
print(f'máxima entropía de tanh(U): {-r.fun:.4f} nats en sigma = {r.x:.3f}; uniforme: log 2 = {np.log(2):.4f}')

Automatic temperature and target entropy

Fixed α\alpha creates a scale problem: the objective adds reward and entropy, while reward units are arbitrary. Multiplying all rewards by 10 makes the optimum much more deterministic at the same α\alpha. Haarnoja and colleagues (2018b) reformulate: maximize return subject to mean entropy staying above a minimum,

max⁡π Eπ[∑tγtrt]sujeto aEst[H⁡(π(⋅∣st))]≥Hˉ  para todo t.\max_\pi\ \E_\pi\Bigl[\sum_t \gamma^t r_t\Bigr] \quad \text{sujeto a} \quad \E_{s_t}\bigl[\Ent(\pi(\cdot \given s_t))\bigr] \ge \bar{\mathcal H} \ \text{ para todo } t.

Temperature appears as a Lagrange multiplier for the constraint. The dual alternates maximization in π\pi with fixed α\alpha (already done by actor and critics) and minimization over α≥0\alpha \ge 0 of

L(α)=Es∼buˊfer, a∼π[−α(log⁡π(a∣s)+Hˉ)]=α (H⁡(π)−Hˉ) en esperanza.\Loss(\alpha) = \E_{s \sim \text{búfer},\, a \sim \pi}\bigl[-\alpha\bigl(\log\pi(a \given s) + \bar{\mathcal H}\bigr)\bigr] = \alpha\,\bigl(\Ent(\pi) - \bar{\mathcal H}\bigr) \text{ en esperanza}.

The multiplier sign works as follows: if entropy is below target, H⁡−Hˉ<0\Ent - \bar{\mathcal H} < 0, loss falls as α\alpha increases and gradient descent raises it; the policy widens with more entropy reward. With excess entropy α\alpha falls. To avoid projection onto α≥0\alpha \ge 0 optimize β=log⁡α\beta = \log\alpha; this lesson uses that variable’s loss −β(log⁡π+Hˉ)-\beta(\log\pi + \bar{\mathcal H}), whose gradient is exactly batch-estimated H⁡(π)−Hˉ\Ent(\pi) - \bar{\mathcal H}. CleanRL uses −eβ(log⁡π+Hˉ)-e^\beta(\log\pi + \bar{\mathcal H}), whose gradient carries factor α\alpha: same fixed point, different step scale, which Adam nearly equalizes by normalizing gradient magnitude.

InteractiveA self-adjusting temperature
Policy entropy by iteration
Temperature log⁡10α\log_{10}\alpha by iteration
Policy at iteration 1500 and the optimal action for QQ at a=0.5a = 0.5
  • entropy H(πt)\mathcal H(\pi_t) and density πt\pi_t
  • target Hˉ\bar{\mathcal H}
  • log⁡10αt\log_{10}\alpha_t
  • selected iteration
−1.00
1.0
0.010
1500
αt\alpha_t0.0165
H(πt)\mathcal H(\pi_t) (nats)−1.000
Eπt[Q]\E_{\pi_t}[Q]−0.0081
Median tanh⁡m\tanh m and latent standard deviation ss0.505 and 0.121
α\alpha final / k/\,k0.0165
One state, fixed critic Q(a)=−k(a−0.5)2Q(a) = -k(a - 0.5)^2 and a squashed Gaussian policy. Each iteration applies an Adam policy step on E[Q]+αH⁡\E[Q] + \alpha\Ent and another to log⁡α\log\alpha with gradient H⁡−Hˉ\Ent - \bar{\mathcal H}, starting at α=1\alpha = 1. Expectations are calculated by quadrature. Move the iteration slider to view the policy at any point.

The key experiment is reward scale kk. With Hˉ=−1\bar{\mathcal H} = -1 and k=1k = 1, temperature converges to α≈0.0165\alpha \approx 0.0165; with k=100k = 100 to α≈1.65\alpha \approx 1.65: one hundred times larger. Final entropy is the same −1-1 nats in both. This is the goal: fix behavior (randomness) while temperature absorbs reward units. Without tanh it takes one line: with π=N(m,s2)\pi = \Normal(m, s^2), E[Q]+αH⁡=−k(s2+(m−0.5)2)+α2log⁡(2πes2)\E[Q] + \alpha\Ent = -k\bigl(s^2 + (m - 0.5)^2\bigr) + \tfrac{\alpha}{2}\log(2\pi e s^2), whose optimum is m=0.5m = 0.5 and s2=α/(2k)s^2 = \alpha/(2k); imposing H⁡=Hˉ\Ent = \bar{\mathcal H} gives

α⋆=k e2Hˉπe,\alpha^\star = \frac{k\,e^{2\bar{\mathcal H}}}{\pi e},

proportional to kk. For Hˉ=−1\bar{\mathcal H} = -1 it is α⋆/k=0.0159\alpha^\star/k = 0.0159, close to 0.01650.0165 found by the figure with tanh (policy is at a=0.5a = 0.5, where tanh contraction is moderate).

The other two experiments are practical failures. Too high a temperature learning rate makes the system oscillate because α\alpha changes faster than the policy can follow: the loops need separate timescales. A target above 0.6840.684 nats is unattainable for the family, so α\alpha grows without bound and the policy becomes as uniform as possible, forgetting reward.

The convention Hˉ=−dim⁡A\bar{\mathcal H} = -\dim\mathcal A

The paper uses Hˉ=−d\bar{\mathcal H} = -d with dd action dimension, copied by almost all implementations; for HalfCheetah d=6d = 6 and Hˉ=−6\bar{\mathcal H} = -6. What does it mean? Per dimension it is −1-1 nats, entropy of a uniform distribution on an interval of length e−1≈0.37e^{-1} \approx 0.37 (in a width-2 box), or a Gaussian of deviation e−1/2πe≈0.089e^{-1}/\sqrt{2\pi e} \approx 0.089. It is moderate exploration, well below the family ceiling 6×0.684=4.106 \times 0.684 = 4.10 nats. It is not a law: this default depends on action scale because differential entropy changes by log⁡c\log c on rescaling. If robot actions live in [−10,10][-10, 10], the same behavior has log⁡10≈2.3\log 10 \approx 2.3 more nats per dimension.

The complete algorithm

Putting the pieces together, our SAC implementation maintains actor πϕ\pi_\phi, two critics Qθ1,Qθ2Q_{\theta_1}, Q_{\theta_2} with targets Qθˉ1,Qθˉ2Q_{\bar\theta_1}, Q_{\bar\theta_2}, temperature α=eβ\alpha = e^\beta and a circular buffer. At each environment step:

  1. Act. For the first inicio steps, uniform action in the box (filling the buffer with diverse data before the critic is meaningful); then sampled a∼πϕ(⋅∣s)a \sim \pi_\phi(\cdot \given s), not deterministic.
  2. Store (s,a,r,s′,terminated)(s, a, r, s', \text{terminated}) with the actual next observation.
  3. Critics. With 256 uniformly sampled buffer transitions, compute yy with new current-policy actions at s′s', the target-copy minimum and −αlog⁡π-\alpha\log\pi term; one Adam step on ∑i(Qθi−y)2\sum_i (Q_{\theta_i} - y)^2.
  4. Actor. Same batch of states, new reparameterized actions; one Adam step on αlog⁡πϕ−min⁡iQθi\alpha\log\pi_\phi - \min_i Q_{\theta_i} with frozen critics.
  5. Temperature. One Adam step on −β(log⁡πϕ+Hˉ)-\beta(\log\pi_\phi + \bar{\mathcal H}) with the previous step’s detached log density.
  6. Target copies. θˉi←(1−τ)θˉi+τθi\bar\theta_i \leftarrow (1 - \tau)\bar\theta_i + \tau\theta_i.
HyperparameterPaper (2018b, Appendix D)CleanRLThis lab
Hidden layers2 of 256, ReLU2 of 256, ReLU2 of 256, ReLU
Batch256256256
Buffer10610^610610^610610^6 (20,000 in short run)
γ\gamma, τ\tau0.99, 0.0050.99, 0.0050.99, 0.005
Adam: critics, actor, α\alpha3⋅10−43\cdot 10^{-4} for all10−310^{-3}, 3⋅10−43\cdot 10^{-4}, 10−310^{-3}10−310^{-3}, 3⋅10−43\cdot 10^{-4}, 10−310^{-3}
Target entropy−dim⁡A-\dim\mathcal A−dim⁡A-\dim\mathcal A−dim⁡A-\dim\mathcal A
Actor updates1 per step2 every 2 steps1 per step
Initial uniform stepsnot stated in table50005000

The left table comes from Appendix D of Haarnoja et al. (2018b); CleanRL values are script defaults. The actor bounds log⁡σ\log\sigma to [−5,2][-5, 2] using a smooth tanh, like CleanRL: without bounds, rare buffer states can make the network request σ≈0\sigma \approx 0 and log density diverge.

Lab: SAC from scratch in PyTorch

The full lab is on this page: cells do not depend on other lessons. It needs local Python with PyTorch, Gymnasium and MuJoCo and uses a GPU if available. As in previous module lessons, default execution is short (a few minutes to verify operation); the full experiment is launched by changing two constants and takes hours.

The first cell defines squashed log density in PyTorch and tests it: numerically integrate action density on (−1,1)(-1, 1) for four Gaussians, including a very wide one and a very narrow one near the boundary, and compare naive with stable float32 Jacobian.

[ ]Squashed log density and its checkLocal GPU
import math
import torch
from torch.nn import functional as F
from scipy.integrate import quad

LOG_2PI = math.log(2 * math.pi)


def log_jacobiano_tanh(u):
    """log(1 - tanh(u)^2) sin cancelación: 2 (log 2 - u - softplus(-2u))."""
    return 2.0 * (math.log(2.0) - u - F.softplus(-2.0 * u))


def squashed_log_prob(u, media, log_std, escala=None):
    """log pi(a) para a = escala * tanh(u) + sesgo, u ~ N(media, exp(log_std)^2) diagonal.
    Se calcula desde u (nunca desde a) y se suma sobre la última dimensión."""
    z = (u - media) * torch.exp(-log_std)
    log_normal = -0.5 * z * z - log_std - 0.5 * LOG_2PI
    log_p = log_normal - log_jacobiano_tanh(u)
    if escala is not None:
        log_p = log_p - torch.log(escala)
    return log_p.sum(dim=-1)


# 1) La densidad de la acción integra 1 en (-1, 1): integración numérica en el eje de a.
for mu, sigma in [(0.0, 1.0), (0.5, 0.7), (-1.0, 2.5), (2.0, 0.3)]:
    m = torch.tensor([mu], dtype=torch.float64)
    ls = torch.tensor([math.log(sigma)], dtype=torch.float64)

    def densidad(a):
        u = torch.tensor([math.atanh(a)], dtype=torch.float64)
        return math.exp(squashed_log_prob(u, m, ls).item())

    area, error = quad(densidad, -1.0, 1.0, limit=500, epsabs=1e-12)
    print(f'mu = {mu:5.2f}, sigma = {sigma:4.2f}: integral de p_A = {area:.10f}')
    assert abs(area - 1.0) < 1e-7

# 2) Estabilidad en float32: la fórmula ingenua da -inf en cuanto tanh(u) se redondea a 1.
u = torch.tensor([0.0, 3.0, 6.0, 9.0, 12.0, 30.0], requires_grad=True)
ingenua = torch.log(1 - torch.tanh(u) ** 2)
estable = log_jacobiano_tanh(u)
for x, a, b in zip(u.tolist(), ingenua.tolist(), estable.tolist()):
    print(f'u = {x:5.1f}   ingenua = {a:12.4f}   estable = {b:12.4f}')
estable.sum().backward()
print('gradiente estable, finito en todos los puntos:', bool(torch.isfinite(u.grad).all()))
assert torch.isfinite(estable).all() and torch.isfinite(u.grad).all()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

All four integrals equal 1 to nine or ten digits, and the table shows three failure phases: at u=6u = 6 the naive formula is already wrong in the fourth digit, at u=9u = 9 in the first (−15.94-15.94 versus −16.61-16.61), and at u=12u = 12 it returns −∞-\infty.

The second cell contains networks, buffer and update. Two implementation decisions merit comment. The buffer stores each transition as a row in one float32 GPU tensor, [obs | acción | recompensa | obs siguiente | terminado], so storage is one copy and batch sampling is indexing without CPU transfer; for HalfCheetah (17+6+1+17+1=4217 + 6 + 1 + 17 + 1 = 42 numbers per row) one million transitions occupy 168 MB. The update returns tensors without converting to Python numbers: each .item() waits for the GPU, so conversion occurs only during logging.

[ ]SAC networks, buffer and updateLocal GPU
import copy
import numpy as np
from torch import nn

DISPOSITIVO = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
if DISPOSITIVO.type == 'cuda':
    # Tope de 3 GB de VRAM para este proceso: SAC con HalfCheetah usa bastante menos.
    total = torch.cuda.get_device_properties(0).total_memory
    torch.cuda.set_per_process_memory_fraction(min(1.0, 3 * 2**30 / total))


class Actor(nn.Module):
    LOG_STD_MIN, LOG_STD_MAX = -5.0, 2.0

    def __init__(self, obs_dim, act_dim, bajo, alto, oculto=256):
        super().__init__()
        self.cuerpo = nn.Sequential(nn.Linear(obs_dim, oculto), nn.ReLU(),
                                    nn.Linear(oculto, oculto), nn.ReLU())
        self.media = nn.Linear(oculto, act_dim)
        self.log_std = nn.Linear(oculto, act_dim)
        self.register_buffer('escala', torch.as_tensor((alto - bajo) / 2, dtype=torch.float32))
        self.register_buffer('sesgo', torch.as_tensor((alto + bajo) / 2, dtype=torch.float32))

    def forward(self, obs):
        h = self.cuerpo(obs)
        t = torch.tanh(self.log_std(h))  # log_std acotado con suavidad en [-5, 2]
        log_std = self.LOG_STD_MIN + 0.5 * (self.LOG_STD_MAX - self.LOG_STD_MIN) * (t + 1)
        return self.media(h), log_std

    def muestrear(self, obs):
        media, log_std = self(obs)
        u = media + log_std.exp() * torch.randn_like(media)  # reparametrización
        accion = torch.tanh(u) * self.escala + self.sesgo
        return accion, squashed_log_prob(u, media, log_std, self.escala)

    @torch.no_grad()
    def determinista(self, obs):
        media, _ = self(obs)
        return torch.tanh(media) * self.escala + self.sesgo


class DobleQ(nn.Module):
    """Dos críticos independientes (inicializaciones distintas) evaluados a la vez."""

    def __init__(self, obs_dim, act_dim, oculto=256):
        super().__init__()

        def red():
            return nn.Sequential(nn.Linear(obs_dim + act_dim, oculto), nn.ReLU(),
                                 nn.Linear(oculto, oculto), nn.ReLU(), nn.Linear(oculto, 1))
        self.q1, self.q2 = red(), red()

    def forward(self, obs, accion):
        x = torch.cat([obs, accion], dim=-1)
        return self.q1(x).squeeze(-1), self.q2(x).squeeze(-1)


class Repeticion:
    """Búfer circular en float32 dentro del dispositivo: una fila por transición,
    [obs | acción | recompensa | obs siguiente | terminado], una sola copia por paso."""

    def __init__(self, capacidad, obs_dim, act_dim, dispositivo, semilla=0):
        self.d_obs, self.d_act = obs_dim, act_dim
        self.datos = torch.zeros((capacidad, 2 * obs_dim + act_dim + 2), dtype=torch.float32, device=dispositivo)
        self.capacidad, self.i, self.n = capacidad, 0, 0
        self.gen = torch.Generator(device=dispositivo).manual_seed(semilla)

    def guardar(self, obs, accion, recompensa, obs_sig, terminado):
        fila = np.concatenate([obs, accion, [recompensa], obs_sig, [float(terminado)]]).astype(np.float32)
        self.datos[self.i] = torch.from_numpy(fila).to(self.datos.device)
        self.i = (self.i + 1) % self.capacidad
        self.n = min(self.n + 1, self.capacidad)

    def muestra(self, lote):
        idx = torch.randint(0, self.n, (lote,), device=self.datos.device, generator=self.gen)
        f = self.datos[idx]
        o, a = self.d_obs, self.d_act
        return (f[:, :o], f[:, o:o + a], f[:, o + a], f[:, o + a + 1:2 * o + a + 1], f[:, -1])


def actualizar_sac(lote, actor, critico, objetivo, log_alfa, opts, gamma, tau, h_objetivo):
    opt_actor, opt_critico, opt_alfa = opts
    obs, acc, rec, sig, term = lote
    alfa = log_alfa.exp().detach()

    # 1) Críticos: objetivo suave con el mínimo de las dos redes objetivo.
    with torch.no_grad():
        acc_sig, logp_sig = actor.muestrear(sig)
        q1_o, q2_o = objetivo(sig, acc_sig)
        y = rec + gamma * (1.0 - term) * (torch.minimum(q1_o, q2_o) - alfa * logp_sig)
    q1, q2 = critico(obs, acc)
    perdida_q = F.mse_loss(q1, y) + F.mse_loss(q2, y)
    opt_critico.zero_grad(set_to_none=True)
    perdida_q.backward()
    opt_critico.step()

    # 2) Actor: el gradiente pasa por la acción reparametrizada; los críticos, congelados.
    for p in critico.parameters():
        p.requires_grad_(False)
    acc_pi, logp = actor.muestrear(obs)
    q1_pi, q2_pi = critico(obs, acc_pi)
    perdida_pi = (alfa * logp - torch.minimum(q1_pi, q2_pi)).mean()
    opt_actor.zero_grad(set_to_none=True)
    perdida_pi.backward()
    opt_actor.step()
    for p in critico.parameters():
        p.requires_grad_(True)

    # 3) Temperatura en escala logarítmica: d/d(log alfa) = H(pi) - H_objetivo.
    perdida_alfa = -(log_alfa * (logp.detach() + h_objetivo)).mean()
    opt_alfa.zero_grad(set_to_none=True)
    perdida_alfa.backward()
    opt_alfa.step()

    # 4) Redes objetivo: media móvil exponencial (Polyak) con peso tau.
    with torch.no_grad():
        for p, p_obj in zip(critico.parameters(), objetivo.parameters()):
            p_obj.lerp_(p, tau)
    return {'perdida_q': perdida_q.detach(), 'q': q1.detach().mean(),
            'entropia': -logp.detach().mean(), 'alfa': alfa}


# Comprobación rápida del búfer y de una actualización con datos sintéticos (sin entorno).
_b = Repeticion(8, 3, 2, DISPOSITIVO)
for k in range(11):  # 11 > 8: el índice vuelve al principio
    _b.guardar(np.full(3, k, np.float32), np.zeros(2, np.float32), float(k), np.full(3, k + 1, np.float32), k == 10)
print('búfer: n =', _b.n, 'posición =', _b.i, 'recompensas guardadas =', sorted(_b.datos[:, 5].tolist()))
_actor = Actor(3, 2, np.array([-1., -1.]), np.array([1., 1.])).to(DISPOSITIVO)
_crit = DobleQ(3, 2).to(DISPOSITIVO)
_obj = copy.deepcopy(_crit)
_la = torch.zeros(1, requires_grad=True, device=DISPOSITIVO)
_opts = (torch.optim.Adam(_actor.parameters(), 3e-4), torch.optim.Adam(_crit.parameters(), 1e-3), torch.optim.Adam([_la], 1e-3))
_m = actualizar_sac(_b.muestra(4), _actor, _crit, _obj, _la, _opts, 0.99, 0.005, -2.0)
print('una actualización:', {k: round(float(v), 4) for k, v in _m.items()})
with torch.no_grad():  # Adam mueve cada peso unos lr = 1e-3 y la copia objetivo solo tau de eso
    _dif = max(float((p - q).abs().max()) for p, q in zip(_crit.parameters(), _obj.parameters()))
print('máxima diferencia crítico-objetivo tras una actualización:', round(_dif, 6))
del _b, _actor, _crit, _obj, _la, _opts, _m
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Three final checks detect common buffer and update failures: after 11 insertions in an 8-slot buffer, rewards 3 through 10 remain and write position is 3; update produces finite numbers; and maximum difference between a critic and its copy after one Adam step (moving each weight by about 10−310^{-3}, the learning rate) is (1−τ)⋅10−3≈0.000995(1 - \tau)\cdot 10^{-3} \approx 0.000995.

The training loop uses a nonvectorized environment that does not autoreset: obs_sig is thus always the actual final observation on both termination and truncation. It separately measures environment time (simulate, choose action, store), update time and evaluation time, and monitors process memory to abort before exceeding 4 GB. Evaluations use deterministic action and their own fixed seeds, distinct from training, following the module’s evaluation protocol.

[ ]Training and evaluation loopLocal GPU
import gc
import json
import random
import time
from pathlib import Path
import gymnasium as gym
import psutil


def evaluar(actor, env, episodios, semilla_base):
    """Retorno de la política determinista b + c tanh(media) en episodios con semillas fijas."""
    retornos = []
    for k in range(episodios):
        obs, _ = env.reset(seed=semilla_base + k)
        total, fin = 0.0, False
        while not fin:
            a = actor.determinista(torch.as_tensor(obs, dtype=torch.float32, device=DISPOSITIVO).unsqueeze(0))
            obs, r, terminado, truncado, _ = env.step(a[0].cpu().numpy())
            total += float(r)
            fin = terminado or truncado
        retornos.append(total)
    return retornos


def entrenar_sac(env_id='HalfCheetah-v5', pasos=1_000_000, semilla=0, capacidad=1_000_000,
                 inicio=5_000, lote=256, gamma=0.99, tau=0.005, lr_actor=3e-4, lr_critico=1e-3,
                 lr_alfa=1e-3, evaluar_cada=10_000, episodios_eval=5, carpeta=None, limite_ram_gb=4.0):
    proceso = psutil.Process()
    random.seed(semilla); np.random.seed(semilla); torch.manual_seed(semilla)
    env, env_eval = gym.make(env_id), gym.make(env_id)
    obs, _ = env.reset(seed=semilla)
    env.action_space.seed(semilla)
    d_obs, d_act = env.observation_space.shape[0], env.action_space.shape[0]
    bajo, alto = env.action_space.low, env.action_space.high

    actor = Actor(d_obs, d_act, bajo, alto).to(DISPOSITIVO)
    critico = DobleQ(d_obs, d_act).to(DISPOSITIVO)
    objetivo = copy.deepcopy(critico).requires_grad_(False)
    log_alfa = torch.zeros(1, requires_grad=True, device=DISPOSITIVO)  # alfa inicial = 1
    fusionado = DISPOSITIVO.type == 'cuda'  # Adam fusionado: muchos menos lanzamientos de kernels
    opts = (torch.optim.Adam(actor.parameters(), lr_actor, fused=fusionado),
            torch.optim.Adam(critico.parameters(), lr_critico, fused=fusionado),
            torch.optim.Adam([log_alfa], lr_alfa, fused=fusionado))
    h_objetivo = -float(d_act)  # convención de Haarnoja et al. (2018b): -dim(A)
    buf = Repeticion(min(capacidad, pasos), d_obs, d_act, DISPOSITIVO, semilla)

    historia, metricas = [], None
    reloj = {'entorno': 0.0, 'actualizar': 0.0, 'evaluar': 0.0}
    sincronizar = torch.cuda.synchronize if DISPOSITIVO.type == 'cuda' else (lambda: None)
    try:
        for paso in range(1, pasos + 1):
            t0 = time.perf_counter()
            if paso <= inicio:
                accion = env.action_space.sample()  # exploración uniforme inicial
            else:
                with torch.no_grad():
                    a, _ = actor.muestrear(torch.as_tensor(obs, dtype=torch.float32, device=DISPOSITIVO).unsqueeze(0))
                accion = a[0].cpu().numpy()
            obs_sig, r, terminado, truncado, _ = env.step(accion)
            # Se guarda 'terminado', nunca 'terminado or truncado': al truncar, obs_sig es el
            # estado real en el que se cortó el episodio y el objetivo debe hacer bootstrap.
            buf.guardar(obs, accion, r, obs_sig, terminado)
            obs = obs_sig
            if terminado or truncado:
                obs, _ = env.reset()
            t1 = time.perf_counter()
            reloj['entorno'] += t1 - t0
            if paso > inicio:
                metricas = actualizar_sac(buf.muestra(lote), actor, critico, objetivo, log_alfa, opts,
                                          gamma, tau, h_objetivo)
                sincronizar()  # para que el reloj atribuya a la actualización su propio coste
                reloj['actualizar'] += time.perf_counter() - t1
            if paso % 1000 == 0 and proceso.memory_info().rss > limite_ram_gb * 2**30:
                raise MemoryError(f'RAM del proceso por encima de {limite_ram_gb} GB')
            if paso % evaluar_cada == 0 or paso == pasos:
                t2 = time.perf_counter()
                retornos = evaluar(actor, env_eval, episodios_eval, 10_000)
                reloj['evaluar'] += time.perf_counter() - t2
                fila = {'pasos': paso, 'retorno': float(np.mean(retornos)), 'retornos': retornos,
                        'segundos': reloj['entorno'] + reloj['actualizar'], **dict(reloj)}
                if metricas is not None:
                    fila.update({k: float(v) for k, v in metricas.items()})
                historia.append(fila)
                print(f"paso {paso:>8}  retorno {fila['retorno']:9.1f}  alfa {fila.get('alfa', 1.0):.3f}  "
                      f"entropía {fila.get('entropia', float('nan')):6.2f}  minutos {fila['segundos'] / 60:6.2f}", flush=True)
        if carpeta is not None:
            ruta = Path(carpeta) / f'sac-{env_id}-semilla{semilla}.json'
            ruta.parent.mkdir(parents=True, exist_ok=True)
            ruta.write_text(json.dumps({'env_id': env_id, 'semilla': semilla, 'pasos': pasos, 'inicio': inicio,
                                        'dispositivo': str(DISPOSITIVO), 'historia': historia}, indent=1), encoding='utf-8')
            torch.save(actor.state_dict(), ruta.with_suffix('.pt'))
        return historia, reloj
    finally:
        env.close(); env_eval.close()
        del actor, critico, objetivo, log_alfa, opts, buf
        gc.collect()
        if DISPOSITIVO.type == 'cuda':
            torch.cuda.empty_cache()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Short run and full experiment

The next cell trains for 20,000 steps with one seed: 5000 uniform steps and 15,000 updates, a few minutes on a laptop GPU. For the full experiment change PASOS to 1_000_000 and SEMILLAS to [0, 1, 2, 3, 4]. Each seed writes history and actor weights to ATLAS_RUNS/p09-l06 (default atlas_runs under the working directory). Use a clean folder per experiment: final comparison reads every history it finds.

[ ]Short verification runLocal GPU
import os

# Experimento completo: PASOS = 1_000_000 y SEMILLAS = [0, 1, 2, 3, 4] (horas por semilla).
PASOS = 20_000
SEMILLAS = [0]
EVALUAR_CADA = 5_000 if PASOS < 100_000 else 10_000
CARPETA = Path(os.environ.get('ATLAS_RUNS', 'atlas_runs')) / 'p09-l06'

resultados_sac = {}
for semilla in SEMILLAS:
    historia, reloj = entrenar_sac(pasos=PASOS, semilla=semilla, evaluar_cada=EVALUAR_CADA,
                                   episodios_eval=3 if PASOS < 100_000 else 5, carpeta=CARPETA)
    resultados_sac[semilla] = historia

n_act = PASOS - 5_000
print(f"\ncoste por paso de entorno (simulación + acción + guardar): {1e3 * reloj['entorno'] / PASOS:.3f} ms")
print(f"coste por actualización de SAC (lote 256, {DISPOSITIVO}):       {1e3 * reloj['actualizar'] / n_act:.3f} ms")
print(f"evaluación (aparte del reloj de entrenamiento):          {reloj['evaluar']:.1f} s")
print('RAM del proceso:', round(psutil.Process().memory_info().rss / 2**30, 2), 'GB')
if DISPOSITIVO.type == 'cuda':
    print('pico de VRAM reservada:', round(torch.cuda.max_memory_reserved() / 2**30, 3), 'GB')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Lesson verification ran two variants of this cell with seed 0 on a shared laptop’s 8 GB GPU: the shown fused-Adam version and an identical standard-Adam version. In both, evaluation return was negative at 10,000 steps (−602-602 fused, −140-140 standard) and clearly positive at 20,000 (13761376 and 482482), with temperature between 0.010.01 and 0.020.02 and batch entropy approaching target −6-6 (fused: −4.4-4.4 at 10,000 and −5.8-5.8 at 20,000). Repeating fused reproduced exact figures. The distinction is instructive: optimizers are mathematically the same but add in a different order, and in RL a rounding difference changes sampled action, which changes data and everything afterward. One seed is not an experiment. These short runs show the algorithm learns, not how much. Published references set expectations at one million steps: roughly 9500 to 11,000 HalfCheetah return (next table).

Also notice temperature: it starts at 1 and falls two orders of magnitude in the first few thousand updates because an initial policy with large σ\sigma has much higher entropy than target −6-6. This is the temperature figure’s curve at real scale.

Where time goes

The short run measured something worth examining: each SAC update took 15–19 ms depending on machine load despite modest computation: each network has about 73,000 parameters, one 256-batch pass is about 37 megaflops, and the full update (target, critic and actor passes with backpropagation) is under one gigaflop, a fraction of a millisecond for a laptop GPU. The next cell profiles ten updates and separates CPU kernel-launch time from GPU compute time.

[ ]Profiling one updateLocal GPU
from torch.profiler import profile, ProfilerActivity

_b = Repeticion(10_000, 17, 6, DISPOSITIVO)
for _ in range(10_000):
    _b.guardar(np.random.randn(17), np.random.uniform(-1, 1, 6), 0.1, np.random.randn(17), False)
_actor = Actor(17, 6, -np.ones(6), np.ones(6)).to(DISPOSITIVO)
_crit = DobleQ(17, 6).to(DISPOSITIVO)
_obj = copy.deepcopy(_crit).requires_grad_(False)
_la = torch.zeros(1, requires_grad=True, device=DISPOSITIVO)
_f = DISPOSITIVO.type == 'cuda'
_opts = (torch.optim.Adam(_actor.parameters(), 3e-4, fused=_f), torch.optim.Adam(_crit.parameters(), 1e-3, fused=_f),
         torch.optim.Adam([_la], 1e-3, fused=_f))
for _ in range(20):  # calentamiento
    actualizar_sac(_b.muestra(256), _actor, _crit, _obj, _la, _opts, 0.99, 0.005, -6.0)
actividades = [ProfilerActivity.CPU] + ([ProfilerActivity.CUDA] if _f else [])
with profile(activities=actividades) as prof:
    t = time.perf_counter()
    for _ in range(10):
        actualizar_sac(_b.muestra(256), _actor, _crit, _obj, _la, _opts, 0.99, 0.005, -6.0)
    if _f:
        torch.cuda.synchronize()
    pared = (time.perf_counter() - t) / 10
eventos = prof.key_averages()
lanzamientos = sum(e.count for e in eventos if e.key == 'cudaLaunchKernel')
gpu = sum(e.self_device_time_total for e in eventos) / 1e3 / 10 if _f else float('nan')
print(f'tiempo de pared por actualización (con el perfilador activo): {1e3 * pared:.2f} ms')
print(f'kernels lanzados por actualización: {lanzamientos / 10:.0f}')
print(f'tiempo de cálculo en la GPU por actualización: {gpu:.2f} ms')
del _b, _actor, _crit, _obj, _la, _opts
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

On the verification machine each update launched 251 kernels and GPU was busy about 2 ms of the 15–19 ms unprofiled update: the remainder is Python launch cost, tens of microseconds per kernel on Windows. With such small networks SAC is launch-latency limited, not arithmetic-limited. Reducing launches helps: fused Adam (fused=True, one kernel for all parameters rather than several per tensor), and in faster implementations capturing the whole update in a CUDA graph or compiling it. This also explains a surprising result: a separate verification-machine test found the same standard-Adam update took nearly as long on CPU (about 15 ms) as GPU.

SAC versus PPO in steps and wall time

Comparing sample efficiency asks return per transition; wall-time comparison asks return per minute. These differ, and the verdict can reverse. Published sources suggest the following HalfCheetah results at one million steps:

SourceAlgorithmEnvironmentReturn at 10610^6 stepsMeasurement
CleanRLSACHalfCheetah-v29634.89±1423.739634.89 \pm 1423.73training return, 3 seeds
CleanRL, reading paper figureSAC (2018b)HalfCheetah≈11 250\approx 11\,250deterministic evaluation
SB3 ZooSACHalfCheetah-v39535.459535.45deterministic evaluation, 1 run
SB3 ZooPPOHalfCheetah-v35819.105819.10deterministic evaluation, 1 run
p09-l04Custom PPOHalfCheetah-v5IQM 13311331deterministic evaluation, 5 seeds

Rows are not directly comparable: environment version, protocol and seed count differ. The zoo warns each figure is one training run and hyperparameters are tuned per environment, unlike our generic PPO configuration. Even so, order of magnitude is clear: per environment step SAC performs several times better on this task.

For wall time, measure PPO step cost using p09-l04’s computation: single-threaded CPU, 64-unit networks, 2000-step rollouts, four epochs and eight minibatches. The cell does not reproduce full PPO (no evaluation or normalization); it only measures per-step cost, constant over training.

[ ]PPO and SAC cost per stepLocal GPU
from torch.distributions import Normal


def coste_ppo_por_paso(env_id='HalfCheetah-v5', rollouts=3, n=2000, epocas=4, minilotes=8, semilla=0):
    """Mide el coste de reloj de PPO por paso de entorno con la forma de cálculo de p09-l04:
    CPU con un hilo, redes 64-64 tanh, rollouts de 2000 pasos, 4 épocas y 8 minilotes, GAE."""
    hilos = torch.get_num_threads()
    torch.set_num_threads(1)
    torch.manual_seed(semilla)
    env = gym.make(env_id)
    d_obs, d_act = env.observation_space.shape[0], env.action_space.shape[0]

    def mlp(salida):
        return nn.Sequential(nn.Linear(d_obs, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, salida))
    pi, v = mlp(d_act), mlp(1)
    log_std = nn.Parameter(torch.zeros(d_act))
    opt = torch.optim.Adam([*pi.parameters(), *v.parameters(), log_std], lr=3e-4, eps=1e-5)
    obs, _ = env.reset(seed=semilla)
    t_rollout = t_update = 0.0
    try:
        for _ in range(rollouts):
            t0 = time.perf_counter()
            O, A, LP, R, T, V = [], [], [], [], [], []
            for _ in range(n):
                o = torch.as_tensor(obs, dtype=torch.float32)
                with torch.no_grad():
                    dist = Normal(pi(o), log_std.exp())
                    a = dist.sample()
                    O.append(o); A.append(a); LP.append(dist.log_prob(a).sum()); V.append(v(o)[0])
                obs, r, term, trunc, _ = env.step(np.clip(a.numpy(), -1, 1))
                R.append(r); T.append(term)
                if term or trunc:
                    obs, _ = env.reset()
            O, A, LP, V = torch.stack(O), torch.stack(A), torch.stack(LP), torch.stack(V)
            R, T = torch.tensor(R, dtype=torch.float32), torch.tensor(T, dtype=torch.float32)
            with torch.no_grad():  # GAE(0.99, 0.95); el detalle de truncamientos no cambia el coste
                v_fin = v(torch.as_tensor(obs, dtype=torch.float32))[0]
                ventaja, acumulado = torch.zeros(n), 0.0
                for t in reversed(range(n)):
                    v_sig = v_fin if t == n - 1 else V[t + 1]
                    delta = R[t] + 0.99 * (1 - T[t]) * v_sig - V[t]
                    acumulado = delta + 0.99 * 0.95 * (1 - T[t]) * acumulado
                    ventaja[t] = acumulado
                retorno = ventaja + V
            t1 = time.perf_counter()
            for _ in range(epocas):
                for idx in torch.randperm(n).chunk(minilotes):
                    dist = Normal(pi(O[idx]), log_std.exp())
                    razon = (dist.log_prob(A[idx]).sum(-1) - LP[idx]).exp()
                    adv = (ventaja[idx] - ventaja[idx].mean()) / (ventaja[idx].std() + 1e-8)
                    l_pi = -torch.minimum(razon * adv, razon.clamp(0.8, 1.2) * adv).mean()
                    l_v = 0.5 * ((v(O[idx]).squeeze(-1) - retorno[idx]) ** 2).mean()
                    opt.zero_grad(); (l_pi + l_v).backward()
                    nn.utils.clip_grad_norm_([*pi.parameters(), *v.parameters(), log_std], 0.5)
                    opt.step()
            t_rollout += t1 - t0
            t_update += time.perf_counter() - t1
    finally:
        env.close()
        torch.set_num_threads(hilos)
    pasos = rollouts * n
    return 1e3 * t_rollout / pasos, 1e3 * t_update / pasos


ms_rollout, ms_update = coste_ppo_por_paso()
ms_ppo = ms_rollout + ms_update
ms_sac = 1e3 * (reloj['entorno'] / PASOS + reloj['actualizar'] / n_act)  # un paso y una actualización
print(f'PPO: {ms_rollout:.3f} ms de rollout + {ms_update:.3f} ms de actualización = {ms_ppo:.3f} ms por paso')
print(f'SAC en régimen (un paso de entorno y una actualización): {ms_sac:.3f} ms por paso')
print(f'cociente SAC / PPO por paso: {ms_sac / ms_ppo:.1f}')
for nombre, ms in (('PPO', ms_ppo), ('SAC', ms_sac)):
    print(f'{nombre}: un millón de pasos costaría {ms * 1e6 / 3.6e6:.2f} h de reloj a este ritmo, sin evaluaciones')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Across five verification-machine runs, a PPO step cost 0.8–1.5 ms and a SAC steady-state step (environment plus update) 17–21.5 ms: factor 12–23. One million steps take 13–25 minutes for PPO versus 5–6 hours for SAC. Exact figures depend on machine and load, but the factor is structural: PPO makes 32 gradient steps per 2000-transition rollout (four epochs of eight minibatches of 250), one per 62.5 transitions with 64-unit networks; SAC makes one per transition with batch 256, three learned networks and two target copies.

These numbers allow reasoning about wall-time verdict. In the hours SAC takes for a million steps, PPO could make twelve to twenty-three million. If PPO reached SAC return in that budget it would win on wall time; otherwise SAC would. Table references do not settle this, stopping at one million, and this lesson’s full experiment does not completely settle it either: its wall-time panel shows PPO’s first minutes against SAC’s hours. To resolve it, extend PPO until SAC wall time is matched by raising total_steps in p09-l04. Three levers change the calculation:

  • Environment cost. A real robot or slow simulator makes each step expensive, making sample efficiency paramount: SAC wins between these two there. With cheap massively parallel GPU simulators, PPO with thousands of parallel environments turns sample inefficiency into wall-time advantage.
  • Update-to-data ratio (UTD). SAC makes one update per step; raising it extracts more per transition while multiplying wall cost.
  • Implementation. SAC update is launch-latency limited: compilation or CUDA graph capture can cut cost severalfold without changing the algorithm.

The last cell plots both comparisons using available disk data: SAC histories from the previous cell and, if ATLAS_P09_L04 names the folder containing p09-l04 runs, PPO curves from that lesson, whose wall time is reconstructed by multiplying steps by measured cost. With multiple seeds it plots IQM and a 95% bootstrap interval resampling seeds; with one, only the curve.

[ ]SAC and PPO curves against steps and wall timeLocal GPU
import matplotlib.pyplot as plt
from scipy.stats import trim_mean


def iqm_con_intervalo(matriz, n_boot=5000, semilla=0):
    """matriz: semillas x puntos de evaluación. IQM por columna e intervalo bootstrap del 95 %
    remuestreando semillas (con menos de 3 semillas no se calcula intervalo)."""
    matriz = np.asarray(matriz, dtype=float)
    iqm = trim_mean(matriz, 0.25, axis=0)
    if matriz.shape[0] < 3:
        return iqm, None, None
    g = np.random.default_rng(semilla)
    idx = g.integers(0, matriz.shape[0], size=(n_boot, matriz.shape[0]))
    replicas = trim_mean(matriz[idx], 0.25, axis=1)
    return iqm, np.percentile(replicas, 2.5, axis=0), np.percentile(replicas, 97.5, axis=0)


def cargar_sac(carpeta):
    curvas = [json.loads(p.read_text(encoding='utf-8'))['historia']
              for p in sorted(Path(carpeta).glob('sac-HalfCheetah-v5-semilla*.json'))]
    n = min(len(c) for c in curvas)
    pasos = np.array([f['pasos'] for f in curvas[0][:n]])
    minutos = np.mean([[f['segundos'] / 60 for f in c[:n]] for c in curvas], axis=0)
    return pasos, minutos, np.array([[f['retorno'] for f in c[:n]] for c in curvas])


def cargar_ppo(carpeta):
    """Historias que guarda el PPO de p09-l04: own-HalfCheetah-v5-seed{s}.json."""
    curvas = [json.loads(p.read_text(encoding='utf-8')) for p in sorted(Path(carpeta).glob('own-HalfCheetah-v5-seed*.json'))]
    if not curvas:
        return None
    n = min(len(c) for c in curvas)
    pasos = np.array([f['steps'] for f in curvas[0][:n]])
    return pasos, np.array([[np.mean([e['return'] for e in f['evaluation']]) for f in c[:n]] for c in curvas])


pasos_sac, min_sac, R_sac = cargar_sac(CARPETA)
curvas = {'SAC': (pasos_sac, min_sac, *iqm_con_intervalo(R_sac))}
dir_ppo = os.environ.get('ATLAS_P09_L04')
ppo = cargar_ppo(dir_ppo) if dir_ppo else None
if ppo is not None:
    pasos_ppo, R_ppo = ppo
    curvas['PPO'] = (pasos_ppo, pasos_ppo * ms_ppo / 6e4, *iqm_con_intervalo(R_ppo))
else:
    print('Sin corridas de PPO de p09-l04 (define ATLAS_P09_L04): se dibuja solo SAC.')

print('semillas de SAC:', R_sac.shape[0])
for p, m, r in zip(pasos_sac, min_sac, curvas['SAC'][2]):
    print(f'SAC  pasos {p:>8}  minutos {m:6.2f}  IQM {r:8.1f}')

fig, ejes = plt.subplots(1, 2, figsize=(10, 3.6), sharey=True)
for nombre, (pasos, minutos, iqm, lo, hi) in curvas.items():
    for ax, x in zip(ejes, (pasos, minutos)):
        ax.plot(x, iqm, label=nombre)
        if lo is not None:
            ax.fill_between(x, lo, hi, alpha=0.25)
ejes[0].set_xlabel('pasos de entorno'); ejes[1].set_xlabel('minutos de reloj (sin evaluación)')
ejes[0].set_ylabel('retorno de evaluación (IQM)'); ejes[0].legend()
fig.tight_layout()
fig.savefig(CARPETA / 'sac-frente-a-ppo.png', dpi=120)
print('figura guardada en', CARPETA / 'sac-frente-a-ppo.png')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The CleanRL reference

To compare your implementation with an independent one, run CleanRL’s SAC script (MIT license) at a pinned revision. It targets Gymnasium 0.28, which handles vectorized episode ends differently, and pinned dependencies require Python 3.8–3.10: install it in a separate environment, not the lab environment. That Gymnasium version lacks HalfCheetah-v5, so use v4; versions differ in documented details, so compare cautiously. Remember two further differences: CleanRL stores its buffer on CPU (Stable-Baselines3’s) and copies each batch to device, and its table reports training return under the stochastic policy, not deterministic evaluation return from our loop.

git clone https://github.com/vwxyzjn/cleanrl.git
cd cleanrl
git checkout 35896b1fefa9898b904f7e09bcbe6e168e15d2a9
py -3.10 -m venv .venv-cleanrl
.venv-cleanrl\Scripts\python.exe -m pip install -r requirements/requirements-mujoco.txt
.venv-cleanrl\Scripts\python.exe cleanrl/sac_continuous_action.py --env-id HalfCheetah-v4 --seed 0 --total-timesteps 1000000

Common mistakes

Exercises

ProofThe log-probability correction
Prove: Let U∼N(μ,σ2)U \sim \Normal(\mu, \sigma^2) and A=tanh⁡UA = \tanh U. Prove that for a∈(−1,1)a \in (-1, 1) and u=artanh⁡au = \operatorname{artanh} a, log⁡pA(a)=log⁡pU(u)−log⁡(1−tanh⁡2u)\log p_A(a) = \log p_U(u) - \log(1 - \tanh^2 u).
0
Use the distribution function of AA and that tanh⁡\tanh is an increasing bijection from R\R to (−1,1)(-1, 1).

Step 1 of 4. How is FA(a)=P(A≤a)F_A(a) = \Pr(A \le a) expressed in terms of UU?

CodeStable squashed log density
Implement squashed_log_prob(u, mu, log_std) for a diagonal Gaussian followed by tanh, with no additional scale. Inputs are NumPy arrays with action dimensions on the last axis (mu and log_std may broadcast against u). Return log density summed on that axis. It must give finite and accurate values for large absolute u: use np.logaddexp for softplus.
import numpy as np

def squashed_log_prob(u, mu, log_std):
  u = np.asarray(u, dtype=float)
  normal = -0.5 * ((u - mu) / np.exp(log_std))**2 - log_std - 0.5 * np.log(2 * np.pi)
  return np.sum(normal - np.log(1 - np.tanh(u)**2), axis=-1)
Shift+Enter to run
NumericHalfCheetah target entropy
HalfCheetah actions lie in [−1,1]6[-1, 1]^6. Under Haarnoja et al.’s convention, what target entropy Hˉ\bar{\mathcal H} in nats does SAC use?
NumericThe box ceiling
What maximum differential entropy in nats can any policy with actions in [−1,1]6[-1, 1]^6 have over all possible distributions?
NumericPessimism of the minimum
Two critics estimate an action’s value with zero-mean Gaussian errors of deviation 2 and correlation 0.5. What is expected bias of min⁡(Q^1,Q^2)\min(\hat Q_1, \hat Q_2)?
NumericTarget network memory
With soft update θˉ←(1−τ)θˉ+τθ\bar\theta \leftarrow (1 - \tau)\bar\theta + \tau\theta and τ=0.005\tau = 0.005, what fraction of total weight is collectively retained by parameters from 200 or more updates ago? Ignore the initial term.
QuizWhy the minimum?
What justifies using the minimum of two critics in the SAC target?
QuizTwo endings with different observations
Two transitions have reward 1 and discount 0.9. The first truly terminates; the second truncates at a time limit. For the second, estimated soft value of the actual final observation is 4 and reset observation 10. What are the Bellman targets in order?
QuizWhich algorithm would you choose?
A simulator yields 200,000 steps per second across 4096 parallel GPU environments, and you have one hour. Which argument is correct?

Summary

Key idea
SAC learns off-policy a stochastic policy maximizing reward plus entropy: two critics with a minimum and slow copies estimate soft value from a buffer; the actor projects onto the critic’s Boltzmann distribution using reparameterized gradients through a tanh-squashed Gaussian; and temperature self-adjusts to maintain target entropy.
  • The optimal maximum-entropy policy at a state is Boltzmann, π∝eQ/α\pi \propto e^{Q/\alpha}, and any other policy’s objective gap is α KL⁡(π ∥ pQ)\alpha\,\KL(\pi\,\|\,p_Q). SAC projects onto a Gaussian family minimizing E[αlog⁡π−Q]\E[\alpha\log\pi - Q], and soft improvement guarantees QQ does not worsen in the tabular case.
  • Critic target uses a new current-policy action at s′s', the minimum of two target networks and −αlog⁡π-\alpha\log\pi; the minimum clips optimistic maximization bias at the cost of pessimism, equal to −σ(1−ρ)/π-\sigma\sqrt{(1-\rho)/\pi} without selection. Copies form an exponential average with mean delay (1−τ)/τ(1-\tau)/\tau.
  • Action b+c⊙tanh⁡(u)\vb{b} + \vb{c}\odot\tanh(\vb{u}) has log density ∑i[log⁡N(ui)−log⁡(1−tanh⁡2ui)−log⁡ci]\sum_i[\log\Normal(u_i) - \log(1 - \tanh^2 u_i) - \log c_i], evaluated at uu with 2(log⁡2−u−softplus⁡(−2u))2(\log 2 - u - \operatorname{softplus}(-2u)). Box entropy is bounded by dlog⁡2d\log 2 (0.684 d0.684\,d within the family).
  • Temperature is a Lagrange multiplier: its log⁡α\log\alpha gradient is H⁡−Hˉ\Ent - \bar{\mathcal H}. It makes behavior invariant to reward scale (α⋆∝k\alpha^\star \propto k); Hˉ=−dim⁡A\bar{\mathcal H} = -\dim\mathcal A is a convention.
  • Per step SAC yields several times PPO return on HalfCheetah; per minute each SAC step costs an order of magnitude more, and with small networks that cost is kernel-launch latency. An honest comparison has both axes.