Overview
Most agents are rewarded only for what they collect. SAC is also rewarded for keeping its options open: among policies that earn similar reward, it prefers the one that acts most randomly. That preference is measured by entropy, which is large when many actions are likely. The effect is built-in exploration. The policy stays broad where it does not yet know which action is best and narrows where one action clearly wins. A temperature sets how much randomness is worth, and SAC adjusts it automatically to hold the entropy near a chosen level. Two critics, as in TD3, keep the value estimates from drifting upward. The template is a small NumPy version trained on a two-dimensional point task.
A short history
Tuomas Haarnoja, Aurick Zhou, Pieter Abbeel and Sergey Levine at UC Berkeley published Soft Actor-Critic in 2018. It grew out of maximum entropy reinforcement learning, where the agent is rewarded for staying random as well as for reward, and it answered two complaints about earlier methods: on-policy methods wasted data and DDPG was brittle. A follow-up the same year tuned the entropy weight automatically, and the same group showed it could learn to walk on a real four-legged robot in a few hours.
How it works
- The actor outputs a mean and a log standard deviation for each action dimension. An action is drawn from that Gaussian and squashed by tanh into .
- Store transitions in a replay buffer and sample a batch.
- For each next state, sample a fresh action from the current policy and record its log-probability.
- Build the target : reward plus the discounted smaller of the two target critics' values, minus times that log-probability.
- Regress both critics onto .
- Update the actor to lower minus the smaller critic value. The gradient passes through the sampled action because the sample is written as a function of the actor's outputs and fixed noise.
- Raise if the policy's entropy is below the target and lower it if above, then let the target critics drift toward the online ones.
Watch out for
- The log-probability must include the tanh correction. Leaving it out gives the density of the wrong variable, so the entropy and every quantity built on it are wrong.
- Near the term blows up. The template adds a small constant inside the logarithm and clips the log standard deviation to keep it finite.
- A fixed that is too large makes the agent prefer acting randomly over collecting reward, and one that is too small removes the exploration. Automatic tuning avoids choosing it by hand.
- The default target entropy, minus the action dimension, is a rule of thumb. On tasks that need very precise or very varied actions it may hold the policy too wide or too narrow.
Use cases
When to use it
A robust default for continuous control when data is expensive: it reuses old experience and its entropy term handles exploration without a hand-set noise scale. Use TD3 when the policy must be deterministic.
In industry
- Robotics
- Learning locomotion and manipulation skills with continuous motor commands, including training directly on physical robots where every sample is expensive.
- Autonomous systems research
- Training continuous steering and throttle policies in driving and flight simulators, where its exploration helps avoid getting stuck in poor behaviours.
- Industrial control
- Learning continuous setpoints for simulated energy or process systems when a replay buffer of past operation can be reused.
Choosing it: what must hold
- Actions are continuous, or you use the discrete-action variant on purpose.
- Memory for a large replay buffer, and compute for two critics plus an actor.
- A reward scale that is roughly stable, or automatic temperature tuning switched on.
When to choose something else
| If | Use instead |
|---|---|
| You want a deterministic policy and a simpler method | TD3 |
| Actions are discrete and few | DQN, Double DQN or Rainbow |
| You can run many environments in parallel and want a simple on-policy method | PPO |
Math foundations
The maximum-entropy objective
Reward plus a bonus for randomness at every step. The temperature is the exchange rate between the two.
Entropy of the policy
The average surprise of the policy's own actions. A policy that spreads probability widely has high entropy, one that always picks the same action has low entropy.
The reparameterised, squashed action
The randomness is moved into , which does not depend on the weights. The action is then a smooth function of the actor's outputs, so gradients can pass through the sample.
Its log-probability
The first three terms are the Gaussian density of . The last is the change-of-variables correction for tanh, whose slope is .
The soft critic target
The value of the next state now includes the entropy bonus. The next action is sampled from the current policy, not taken from a target actor.
The actor's loss
Minimising it raises the critic's score of the sampled action and lowers its log-probability, which spreads the policy. The two pulls balance at the temperature .
The temperature's loss
When entropy is below the target the bracket is positive on average and descent raises . The template steps on in the same direction, which keeps positive.
Symbols
- state, action, reward and next state
- done flag: 1 if the episode terminated at this step, else 0
- the stochastic policy (actor) with weights theta
- mean and standard deviation the actor outputs for each action dimension
- the Gaussian sample before the tanh squash
- standard normal noise, one draw per action dimension
- element-by-element multiplication
- the two critics, with target copies marked by a prime
- entropy temperature: how much one unit of entropy is worth in reward
- entropy of the policy in a state
- target entropy (target_entropy), by default minus the action dimension
- discount factor
- the replay buffer
- the regression target shared by both critics
Worked by hand
A replayed transition has and . For the sampled next action the target critics give and , and its log-probability is . Take and .
The target is . The entropy term added to the next state's value because the sampled action was fairly unlikely, which is what a broad policy produces.
Visual example
Loading the example.
Try this
- Run the training and watch the band: it stays wide, widest in the middle, where going left and going right are equally good.
- Switch the temperature to fixed and set α to 0.02, then train: the band collapses and the policy heads for one goal from everywhere.
- With automatic tuning on, lower the target entropy and watch α fall until the band is that narrow on average.
Code sample
from impl import SAC, PointReach
from config import SACConfig
env = PointReach(seed=0)
agent = SAC(env.obs_dim, env.act_dim, SACConfig(auto_alpha=True))
before = agent.evaluate(PointReach(seed=1), episodes=20)
agent.train(env)
after = agent.evaluate(PointReach(seed=1), episodes=20)
print(before, after) # mean return per episode, closer to 0 is better
print(agent.alpha) # entropy temperature after tuningRead the implementation (301 lines)
"""Soft Actor-Critic (SAC) in NumPy, with a tiny continuous-control task to learn on.
SAC maximises return plus the entropy of the policy. The actor outputs the mean and log standard
deviation of a Gaussian that is squashed by tanh into [-1, 1]; two critics score (observation, action)
pairs and the smaller one is used, minus alpha * log-probability, in both the bootstrap target and the
actor's objective. The temperature alpha is tuned so that the policy's entropy stays near a target.
The reparameterised actor gradient is written out by hand; the networks are small MLPs with Adam.
"""
from __future__ import annotations
import numpy as np
try:
from .config import SACConfig
except ImportError: # run from the template's own folder
from config import SACConfig
class PointReach:
"""Tiny continuous-control task: drive a point on the square [-1, 1]^2 to the origin.
Observation: the position, shape (2,). Action: shape (2,), each entry in [-1, 1]; the point moves
by 0.2 * action and is clipped to the square. Reward: minus the squared distance to the origin
after the move. An episode starts at a uniformly random position and is truncated after `horizon`
steps (there is no terminal state). `step` returns (obs, reward, terminated, truncated).
A policy that does not move scores about -13 per episode on average; the best possible one about -0.55.
"""
obs_dim = 2
act_dim = 2
def __init__(self, horizon: int = 20, seed: int = 0) -> None:
self.horizon = horizon
self.rng = np.random.default_rng(seed)
self.pos = np.zeros(2)
self.t = 0
def reset(self) -> np.ndarray:
self.pos = self.rng.uniform(-1.0, 1.0, size=2)
self.t = 0
return self.pos.copy()
def step(self, action: np.ndarray):
"""Apply one action, shape (2,). Returns (obs, reward, terminated, truncated)."""
action = np.clip(np.asarray(action, dtype=float), -1.0, 1.0)
self.pos = np.clip(self.pos + 0.2 * action, -1.0, 1.0)
self.t += 1
return self.pos.copy(), -float(self.pos @ self.pos), False, self.t >= self.horizon
class MLP:
"""Fully connected network with tanh hidden layers and a linear output, trained by manual backprop.
sizes: layer widths, for example (16, 32, 4) is 16 inputs, one hidden layer of 32 units, 4 outputs.
rng: NumPy generator used for the initial weights.
lr: Adam step size used by `step`.
"""
def __init__(self, sizes, rng: np.random.Generator, lr: float = 1e-3) -> None:
self.sizes = tuple(int(s) for s in sizes)
self.weights = [rng.normal(0.0, np.sqrt(1.0 / m), size=(m, n)) for m, n in zip(self.sizes[:-1], self.sizes[1:])]
self.biases = [np.zeros(n) for n in self.sizes[1:]]
self.lr = lr
self._m = [np.zeros_like(p) for p in self.params()]
self._v = [np.zeros_like(p) for p in self.params()]
self._t = 0
self._acts: list[np.ndarray] = []
def params(self) -> list[np.ndarray]:
"""All parameter arrays: the weight matrices, then the bias vectors."""
return self.weights + self.biases
def forward(self, x: np.ndarray) -> np.ndarray:
"""x: (batch, n_in) or (n_in,) -> (batch, n_out). Keeps the activations for `backward`."""
h = np.atleast_2d(np.asarray(x, dtype=float))
self._acts = [h]
last = len(self.weights) - 1
for i, (w, b) in enumerate(zip(self.weights, self.biases)):
h = h @ w + b
if i < last:
h = np.tanh(h)
self._acts.append(h)
return h
def backward(self, grad_out: np.ndarray):
"""Backpropagate through the most recent `forward` call.
grad_out: d loss / d output, shape (batch, n_out).
Returns (grads, grad_in): grads in the order of `params()`, grad_in = d loss / d input (batch, n_in).
"""
g = np.asarray(grad_out, dtype=float)
n_layers = len(self.weights)
grad_w: list = [None] * n_layers
grad_b: list = [None] * n_layers
for i in reversed(range(n_layers)):
if i < n_layers - 1:
g = g * (1.0 - self._acts[i + 1] ** 2)
grad_w[i] = self._acts[i].T @ g
grad_b[i] = g.sum(axis=0)
g = g @ self.weights[i].T
return grad_w + grad_b, g
def step(self, grads) -> None:
"""One Adam step that moves the parameters against `grads` (same order as `params()`)."""
self._t += 1
for p, g, m, v in zip(self.params(), grads, self._m, self._v):
m *= 0.9
m += 0.1 * g
v *= 0.999
v += 0.001 * g * g
p -= self.lr * (m / (1.0 - 0.9**self._t)) / (np.sqrt(v / (1.0 - 0.999**self._t)) + 1e-8)
def copy_from(self, other: "MLP", tau: float = 1.0) -> None:
"""Polyak update: params <- tau * other + (1 - tau) * params. tau = 1 is a plain copy."""
for p, q in zip(self.params(), other.params()):
p *= 1.0 - tau
p += tau * q
class ReplayBuffer:
"""Fixed-size ring buffer of transitions (obs, action, reward, next_obs, done).
capacity: number of transitions kept; the oldest is overwritten when the buffer is full.
obs_dim: length of an observation vector.
act_dim: 0 for integer (discrete) actions, otherwise the length of a continuous action vector.
"""
def __init__(self, capacity: int, obs_dim: int, act_dim: int = 0) -> None:
self.capacity = capacity
self.obs = np.zeros((capacity, obs_dim))
self.next_obs = np.zeros((capacity, obs_dim))
self.actions = np.zeros(capacity, dtype=int) if act_dim == 0 else np.zeros((capacity, act_dim))
self.rewards = np.zeros(capacity)
self.dones = np.zeros(capacity)
self.size = 0
self._next = 0
def __len__(self) -> int:
return self.size
def add(self, obs, action, reward: float, next_obs, done: bool) -> None:
"""Store one transition. `done` must be True only for a real terminal state, not a time limit."""
i = self._next
self.obs[i], self.actions[i], self.rewards[i] = obs, action, reward
self.next_obs[i], self.dones[i] = next_obs, float(done)
self._next = (i + 1) % self.capacity
self.size = min(self.size + 1, self.capacity)
def sample(self, batch_size: int, rng: np.random.Generator):
"""Uniform random batch: (obs, actions, rewards, next_obs, dones), each with leading size batch_size."""
idx = rng.integers(0, self.size, size=batch_size)
return self.obs[idx], self.actions[idx], self.rewards[idx], self.next_obs[idx], self.dones[idx]
LOG_STD_MIN, LOG_STD_MAX = -5.0, 2.0
_SQUASH_EPS = 1e-6
_HALF_LOG_2PI = 0.5 * np.log(2.0 * np.pi)
def squashed_gaussian_log_prob(log_std: np.ndarray, eps: np.ndarray, actions: np.ndarray) -> np.ndarray:
"""Log density of a = tanh(mu + exp(log_std) * eps), with eps the standard normal draw that produced it.
log_std, eps, actions: (batch, act_dim). Returns (batch,). The Gaussian term is the density of the
pre-squash sample; the last term is the change-of-variables correction for tanh.
"""
per_dim = -0.5 * eps**2 - log_std - _HALF_LOG_2PI - np.log(1.0 - actions**2 + _SQUASH_EPS)
return per_dim.sum(axis=1)
class SAC:
"""SAC agent for actions in [-1, 1]^act_dim.
obs_dim: length of an observation vector. act_dim: length of an action vector.
"""
def __init__(self, obs_dim: int, act_dim: int, config: SACConfig | None = None) -> None:
cfg = self.config = config or SACConfig()
self.obs_dim, self.act_dim = obs_dim, act_dim
self.rng = np.random.default_rng(cfg.seed)
critic_sizes = (obs_dim + act_dim, cfg.hidden_size, cfg.hidden_size, 1)
self.actor = MLP((obs_dim, cfg.hidden_size, cfg.hidden_size, 2 * act_dim), self.rng, cfg.actor_lr)
self.critics = [MLP(critic_sizes, self.rng, cfg.critic_lr) for _ in range(2)]
self.critic_targets = [MLP(critic_sizes, self.rng) for _ in range(2)]
for target, critic in zip(self.critic_targets, self.critics):
target.copy_from(critic)
self.log_alpha = float(np.log(cfg.alpha))
self.target_entropy = -float(act_dim) if cfg.target_entropy is None else cfg.target_entropy
self.buffer = ReplayBuffer(cfg.buffer_size, obs_dim, act_dim)
self.steps = 0
@property
def alpha(self) -> float:
"""Current entropy temperature."""
return float(np.exp(self.log_alpha))
def sample(self, obs: np.ndarray, eps: np.ndarray | None = None):
"""Sample actions from the policy.
obs: (batch, obs_dim) or (obs_dim,). eps: optional standard normal draws, (batch, act_dim).
Returns (actions (batch, act_dim), log_probs (batch,), info) where info holds mean, log_std, the
mask of log_std entries that were not clipped, and eps (used by the actor gradient).
"""
out = self.actor.forward(obs)
mean, raw_log_std = out[:, :self.act_dim], out[:, self.act_dim:]
log_std = np.clip(raw_log_std, LOG_STD_MIN, LOG_STD_MAX)
if eps is None:
eps = self.rng.normal(size=mean.shape)
actions = np.tanh(mean + np.exp(log_std) * eps)
info = {"mean": mean, "log_std": log_std, "eps": eps, "unclipped": raw_log_std == log_std}
return actions, squashed_gaussian_log_prob(log_std, eps, actions), info
def act(self, obs: np.ndarray, explore: bool = False) -> np.ndarray:
"""Action for one observation, shape (act_dim,): a sample if explore, else tanh of the mean."""
if explore:
return self.sample(obs)[0][0]
return np.tanh(self.actor.forward(obs)[0, :self.act_dim])
def actor_loss_and_grads(self, obs: np.ndarray, eps: np.ndarray):
"""Actor loss mean(alpha * log pi(a|s) - min(Q1, Q2)(s, a)) for a = policy sample with noise eps.
obs: (batch, obs_dim), eps: (batch, act_dim). Returns (loss, grads, log_probs): grads for
`actor.params()`, obtained through the reparameterised sample, and log_probs (batch,).
"""
n = len(obs)
alpha = self.alpha
actions, log_probs, info = self.sample(obs, eps)
x = np.concatenate([obs, actions], axis=1)
q1, q2 = self.critics[0].forward(x)[:, 0], self.critics[1].forward(x)[:, 0]
use_first = (q1 <= q2).astype(float)
loss = float(np.mean(alpha * log_probs - np.minimum(q1, q2)))
_, g1 = self.critics[0].backward((-use_first / n)[:, None])
_, g2 = self.critics[1].backward((-(1.0 - use_first) / n)[:, None])
grad_action = (g1 + g2)[:, self.obs_dim:] # d(-min Q) / d action
one_minus = 1.0 - actions**2
# pre-squash sample u = mean + std * eps: through the action and through the tanh correction of log pi
grad_u = grad_action * one_minus + (alpha / n) * 2.0 * actions * one_minus / (one_minus + _SQUASH_EPS)
grad_log_std = (grad_u * np.exp(info["log_std"]) * info["eps"] - alpha / n) * info["unclipped"]
grads, _ = self.actor.backward(np.concatenate([grad_u, grad_log_std], axis=1))
return loss, grads, log_probs
def update(self, batch) -> dict:
"""One step for both critics, the actor and alpha, then a soft target update.
batch: (obs, actions, rewards, next_obs, dones). Returns critic_loss, actor_loss, alpha and entropy.
"""
obs, actions, rewards, next_obs, dones = batch
cfg = self.config
n = len(rewards)
next_actions, next_log_probs, _ = self.sample(next_obs)
next_x = np.concatenate([next_obs, next_actions], axis=1)
next_q = np.minimum(self.critic_targets[0].forward(next_x)[:, 0], self.critic_targets[1].forward(next_x)[:, 0])
targets = rewards + cfg.gamma * (1.0 - dones) * (next_q - self.alpha * next_log_probs)
x = np.concatenate([obs, actions], axis=1)
critic_loss = 0.0
for critic in self.critics:
errors = critic.forward(x)[:, 0] - targets
grads, _ = critic.backward((2.0 * errors / n)[:, None])
critic.step(grads)
critic_loss += 0.5 * float(np.mean(errors**2))
actor_loss, grads, log_probs = self.actor_loss_and_grads(obs, self.rng.normal(size=(n, self.act_dim)))
self.actor.step(grads)
if cfg.auto_alpha: # loss -log_alpha * mean(log pi + target entropy): raise alpha when entropy is too low
self.log_alpha += cfg.alpha_lr * float(np.mean(log_probs + self.target_entropy))
for target, critic in zip(self.critic_targets, self.critics):
target.copy_from(critic, cfg.tau)
return {"critic_loss": critic_loss, "actor_loss": actor_loss, "alpha": self.alpha,
"entropy": float(-log_probs.mean())}
def train(self, env, total_steps: int | None = None) -> list[float]:
"""Interact with `env` for total_steps steps, learning from replay. Returns the episode returns."""
cfg = self.config
returns: list[float] = []
obs, episode_return = env.reset(), 0.0
for _ in range(cfg.total_steps if total_steps is None else total_steps):
if self.steps < cfg.learning_starts:
action = self.rng.uniform(-1.0, 1.0, size=self.act_dim)
else:
action = self.act(obs, explore=True)
next_obs, reward, terminated, truncated = env.step(action)
self.buffer.add(obs, action, reward, next_obs, terminated)
self.steps += 1
episode_return += reward
obs = next_obs
if terminated or truncated:
returns.append(episode_return)
obs, episode_return = env.reset(), 0.0
if self.steps >= cfg.learning_starts and len(self.buffer) >= cfg.batch_size:
self.update(self.buffer.sample(cfg.batch_size, self.rng))
return returns
def evaluate(self, env, episodes: int = 10) -> float:
"""Mean return of the deterministic policy (no exploration noise) over `episodes` episodes."""
total = 0.0
for _ in range(episodes):
obs, done = env.reset(), False
while not done:
obs, reward, terminated, truncated = env.step(self.act(obs, explore=False))
total += reward
done = terminated or truncated
return total / episodes- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 11, run with
python3 -m unittest -v
Practice
Using the template, call agent.sample on one observation with a fixed eps and check that squashed_gaussian_log_prob returns the same log-probability. Then train SAC on PointReach(seed=0) once with SACConfig(auto_alpha=True) and once with auto_alpha=False, and compare evaluate on PointReach(seed=1), the final agent.alpha and the entropy value returned by update.
Check on learning
- Why can the gradient pass through a sampled action here, when sampling is normally a step that has no derivative?
A way to think about it
Write the action as a function of the actor's outputs and of . Ask which of those depends on the weights, and whether the function is smooth in that part once is held fixed.
- During training you see fall steadily toward zero. What does that say about the policy's entropy relative to the target, and what would the agent be turning into?
A way to think about it
Read the temperature loss. falls when the entropy stays above the target. Then consider the actor loss with near zero and compare it with a method you already know.
- The evaluation action is tanh of the mean, not a sample. Why is it reasonable to train a random policy and then test a deterministic one?
A way to think about it
Separate the two jobs randomness does. During training it gathers varied data. At test time ask whether added noise would raise or lower the expected reward on a task like reaching a point.
- SAC samples the next action from the current policy when building the target, where TD3 uses a target actor plus clipped noise. In what sense do the two tricks do the same job?
A way to think about it
In both, the target is an average of the critic over a spread of next actions instead of its value at one point. Compare where the spread comes from and who sets its width.