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 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 and the Stable-Baselines3 zoo . 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:
- 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.
- Two critics and target networks. Bellman target uses the minimum of two estimates and slow-moving copies so the actor does not exploit optimistic critic errors.
- A Gaussian squashed by
tanh. Actions live in a box; policy is a Gaussian transformed bytanh, whose log density needs Jacobian correction. - 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: excludes the current step’s entropy (action is already chosen) but includes all future entropy because accumulates it. Term is a one-sample unbiased estimator of : its expectation is exactly . 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 ? A classical statistical-physics result answers.
Proof
Since , we have . Take expectation under and add :
Kullback-Leibler divergence is nonnegative and zero only when the densities coincide almost everywhere (Gibbs inequality).
∎Two immediate readings. Optimal-policy state value is , a soft maximum: as it tends to and the distribution concentrates on the argmax (recovering classical control); as 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 .
The practical problem is that cannot be sampled: with actions in and a network-defined , constant is an intractable integral. SAC settles for the best policy in a tractable family (squashed Gaussians here), defining improvement as projection:
By the theorem, minimizing that divergence equals maximizing , and disappears: it does not depend on . The figure shows what projection means when the family is too limited.
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 is never zero unless is Gaussian: the family limits what can be reached.
Proof
Since , the projection cannot be worse than it under the minimized objective. By Gibbs’ principle this means, in every state,
Expand the soft Bellman equation of and apply that inequality at each next state:
Repeating for and so on turns the upper bound into discounted reward and entropy sum of starting at , which is . The series remainder is multiplied by and tends to zero because values are bounded.
∎Alternating soft evaluation (iterating ’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 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.
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 <= cotaWith the policy places 98% of mass on the best action and the bound lies from maximum ; with 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 , where if the episode truly terminated in , soft evaluation becomes regression. Sample a new action from the current policy (not the buffer) and fit each critic to target
without propagating gradients through . Sampling the next action from the current policy makes this target valid off-policy: the buffer only supplies pairs where the function is fitted, just as in Q-learning, and the expectation over defining is estimated using the policy being evaluated. No importance ratio is needed. Buffer pair distribution only determines where regression fits best.
This extends DQN experience replay to continuous actions. Two pieces remain: the minimum and bars over .
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 equal-true-value actions and independent errors , the chosen action’s estimated value is by Jensen applied to convex . At bias is . Bellman target feeds it back: overestimated enters , the critic learns it and error accumulates over effective horizon 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.
The minimum does not remove optimism; it clips it. With actions and independent critics, bias of one critic’s maximum is and maximum of the minimum ; at 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 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, . Difference is Gaussian with mean 0 and variance , and for we have . Therefore .
∎With independent critics and , the minimum underestimates by ; at by ; at 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.
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 uses critic copies not updated by gradient: after each step they mix with live parameters, , with . Expanding the recurrence,
an exponential moving average of recent parameters. Weights sum to 1, mean delay is updates and parameters from 200 or more updates ago collectively retain of weight. As with DQN’s target network, if 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 zeroes future value only if 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 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 , sometimes only ) 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,
The inner expectation depends on through the distribution of . PPO handled this with the score-function estimator times a weight. Here there is a better option: the critic is differentiable in action, so express action deterministically in and noise independent of , with , and differentiate inside the expectation:
This is the variational autoencoder reparameterization trick. The critic term uses slope : 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 critic rather than just .
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 is a differentiable bijection from into the box interior with differentiable inverse, acting componentwise, so its Jacobian is diagonal with entries . By change of variables in densities, with . 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 components are independent, 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 , and a wide latent Gaussian accumulates mass against box walls.
Three observations. Initially and , the latent Gaussian is an ordinary bell but action density already peaks at near a boundary. With and the peak, pressed against , reaches density near 18, and raising to 3 gives two boundary peaks and a central valley: more latent variance does not mean more action randomness. Entropy confirms it: grows without bound with , but rises, peaks and falls. At naive float32 already gives the wrong number ( instead of ); from , .
The Jacobian without cancellation
In float32, tanh(u) is exactly 1 for , and log(1 - tanh(u)**2) returns ; before then subtraction has already lost nearly all digits. One in a batch makes actor loss NaN. The stable form comes from writing using exponentials:
and taking logarithms,
The expression is exact for every real and never subtracts nearly equal numbers: for large , softplus(-2u) is tiny and result is ; for very negative , softplus(-2u) and result is : and , numbers of different magnitudes, are subtracted without catastrophic cancellation, provided softplus is stably implemented (as in PyTorch and np.logaddexp). It is evaluated at , 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 gives a useful per-dimension formula:
because the second term is negative. There is also an absolute ceiling: maximum-entropy distribution on is uniform with nats. No squashed Gaussian reaches it: the family maximum is nats at and . This constrains reasonable target entropies.
Finally the deterministic evaluation action 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.
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 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 . Haarnoja and colleagues (2018b) reformulate: maximize return subject to mean entropy staying above a minimum,
Temperature appears as a Lagrange multiplier for the constraint. The dual alternates maximization in with fixed (already done by actor and critics) and minimization over of
The multiplier sign works as follows: if entropy is below target, , loss falls as increases and gradient descent raises it; the policy widens with more entropy reward. With excess entropy falls. To avoid projection onto optimize ; this lesson uses that variable’s loss , whose gradient is exactly batch-estimated . CleanRL uses , whose gradient carries factor : same fixed point, different step scale, which Adam nearly equalizes by normalizing gradient magnitude.
The key experiment is reward scale . With and , temperature converges to ; with to : one hundred times larger. Final entropy is the same nats in both. This is the goal: fix behavior (randomness) while temperature absorbs reward units. Without tanh it takes one line: with , , whose optimum is and ; imposing gives
proportional to . For it is , close to found by the figure with tanh (policy is at , where tanh contraction is moderate).
The other two experiments are practical failures. Too high a temperature learning rate makes the system oscillate because changes faster than the policy can follow: the loops need separate timescales. A target above nats is unattainable for the family, so grows without bound and the policy becomes as uniform as possible, forgetting reward.
The convention
The paper uses with action dimension, copied by almost all implementations; for HalfCheetah and . What does it mean? Per dimension it is nats, entropy of a uniform distribution on an interval of length (in a width-2 box), or a Gaussian of deviation . It is moderate exploration, well below the family ceiling nats. It is not a law: this default depends on action scale because differential entropy changes by on rescaling. If robot actions live in , the same behavior has more nats per dimension.
The complete algorithm
Putting the pieces together, our SAC implementation maintains actor , two critics with targets , temperature and a circular buffer. At each environment step:
- Act. For the first
iniciosteps, uniform action in the box (filling the buffer with diverse data before the critic is meaningful); then sampled , not deterministic. - Store with the actual next observation.
- Critics. With 256 uniformly sampled buffer transitions, compute with new current-policy actions at , the target-copy minimum and term; one Adam step on .
- Actor. Same batch of states, new reparameterized actions; one Adam step on with frozen critics.
- Temperature. One Adam step on with the previous step’s detached log density.
- Target copies. .
| Hyperparameter | Paper (2018b, Appendix D) | CleanRL | This lab |
|---|---|---|---|
| Hidden layers | 2 of 256, ReLU | 2 of 256, ReLU | 2 of 256, ReLU |
| Batch | 256 | 256 | 256 |
| Buffer | (20,000 in short run) | ||
| , | 0.99, 0.005 | 0.99, 0.005 | 0.99, 0.005 |
| Adam: critics, actor, | for all | , , | , , |
| Target entropy | |||
| Actor updates | 1 per step | 2 every 2 steps | 1 per step |
| Initial uniform steps | not stated in table | 5000 | 5000 |
The left table comes from Appendix D of Haarnoja et al. (2018b); CleanRL values are script defaults. The actor bounds to using a smooth tanh, like CleanRL: without bounds, rare buffer states can make the network request 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 for four Gaussians, including a very wide one and a very narrow one near the boundary, and compare naive with stable float32 Jacobian.
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()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 the naive formula is already wrong in the fourth digit, at in the first ( versus ), and at it returns .
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 ( 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.
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, _mnpm 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 , the learning rate) is .
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.
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()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.
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')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 ( fused, standard) and clearly positive at 20,000 ( and ), with temperature between and and batch entropy approaching target (fused: at 10,000 and 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 has much higher entropy than target . 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.
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, _optsnpm 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:
| Source | Algorithm | Environment | Return at steps | Measurement |
|---|---|---|---|---|
| CleanRL | SAC | HalfCheetah-v2 | training return, 3 seeds | |
| CleanRL, reading paper figure | SAC (2018b) | HalfCheetah | deterministic evaluation | |
| SB3 Zoo | SAC | HalfCheetah-v3 | deterministic evaluation, 1 run | |
| SB3 Zoo | PPO | HalfCheetah-v3 | deterministic evaluation, 1 run | |
| p09-l04 | Custom PPO | HalfCheetah-v5 | IQM | deterministic 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.
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')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.
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')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
Step 1 of 4. How is expressed in terms of ?
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)
Summary
- The optimal maximum-entropy policy at a state is Boltzmann, , and any other policy’s objective gap is . SAC projects onto a Gaussian family minimizing , and soft improvement guarantees does not worsen in the tabular case.
- Critic target uses a new current-policy action at , the minimum of two target networks and ; the minimum clips optimistic maximization bias at the cost of pessimism, equal to without selection. Copies form an exponential average with mean delay .
- Action has log density , evaluated at with . Box entropy is bounded by ( within the family).
- Temperature is a Lagrange multiplier: its gradient is . It makes behavior invariant to reward scale (); 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.