Soft Actor-Critic

Dive into Deep Learning · §15.5

Continuous Control: DDPG, TD3, and Soft Actor–Critic
maximum-entropy RL · pathwise gradients · squashed Gaussian Jacobian · twin critics · automatic temperature · update-to-data ratio

Why Continuous Control Needs Replay and Pathwise Slopes

Motivation

  • Why DQN Cannot Apply Directly: With continuous torques u \in [-2, 2], evaluating \max_{u'} Q_w(s', u') inside every Bellman target requires an inner optimization problem at every step.
  • Pathwise Actor + Replay: We keep DQN’s replay buffer and target networks, and train an actor \tilde{a}_\theta(s, z) to climb \partial Q_w(s, a)/\partial a directly—cutting Pendulum’s sample cost from \sim 300{,}000 to \sim 3{,}000 steps.

From DDPG and TD3 to Soft Actor–Critic (SAC)

Algorithmic Evolution

  • DDPG (2016): Deterministic actor \mu_\theta(s) + single critic Q_{w^-}; brittle because the actor exploits narrow peaks of critic error.
  • TD3 (2018): Adds twin critics \min_{j=1,2} Q_{w_j^-}(s', \tilde{a}') to eliminate upward maximization bias, but still relies on ad-hoc exploration noise.
  • SAC (2018): Pairs twin critics with a stochastic squashed Gaussian actor and maximum-entropy reward -\beta \log \pi_\theta.

The Maximum-Entropy Reinforcement Learning Objective

Maximum-Entropy RL

J(\pi) = \mathbb{E}_{\pi}\Big[\sum_{t \ge 0} \gamma^t \big(r_t + \beta\, H(\pi(\cdot \mid s_t))\big)\Big]

  • Temperature \beta > 0: Sets the exchange rate in units of reward per nat of differential entropy H(\pi) = -\mathbb{E}[\log \pi(a \mid s)].
  • Future entropy credit: Paying \beta H(\pi(\cdot \mid s')) inside the critic target rewards actions that lead to high-entropy, multi-option future states.

Two Actions by Hand: Exact Single-Sample Soft Values

Concrete Intuition

Consider a single state with two actions of value Q = (1, 0) at temperature \beta = 0.5. By §15.3, the tilted optimum is \pi^\star \propto e^{Q/\beta} = (e^2, 1)/(e^2 + 1) = (0.88, 0.12) with soft value \beta \log(e^2 + 1) = 1.063:

       tilted: pi = [0.88 0.12], E[Q] + beta H = 1.063, bracket = [1.06 1.06]
      uniform: pi = [0.5 0.5], E[Q] + beta H = 0.847, bracket = [1.35 0.35]
nearly greedy: pi = [0.99 0.01], E[Q] + beta H = 1.018, bracket = [1.01 2.3 ]
beta log Z = 1.063

Zero-Variance Property at \pi^\star: At the tilted optimum \pi^\star(a) = e^{Q(a)/\beta}/Z, the soft bracket Q(a) - \beta \log \pi^\star(a) = \beta \log Z = 1.063 takes the exact same value for every action a.

Soft Policy Evaluation: One Fresh Action in the Target

Soft Policy Evaluation

y = r + \gamma\,(1 - \textrm{term})\Big(Q_{w^-}(s', \tilde{a}') - \beta \log \pi_\theta(\tilde{a}' \mid s')\Big)

  • Zero importance ratios needed: Transition (s, a, r, s') is drawn from replay, while continuation \tilde{a}' \sim \pi_\theta(\cdot \mid s') is sampled freshly from the live policy.
  • Contraction guarantee: Exact soft policy evaluation is a \gamma-contraction for bounded rewards and entropies.

Soft Policy Improvement via Reverse-KL Projection

Soft Policy Improvement

At each state s, maximizing \mathbb{E}_{a \sim \pi}[Q_w(s, a)] + \beta H(\pi(\cdot \mid s)) is equivalent to minimizing the reverse KL divergence to the Boltzmann distribution e^{Q_w(s, \cdot)/\beta} / Z(s):

L_\pi(\theta) = \mathbb{E}_{s \sim \mathcal{D},\, z \sim \mathcal{N}(0, I)}\Big[\beta \log \pi_\theta\big(\tilde{a}_\theta(s, z) \mid s\big) - Q_w\big(s, \tilde{a}_\theta(s, z)\big)\Big]

  • Mode-Seeking Behavior: When Q_w(s, \cdot) has two separated peaks, minimizing reverse KL D_{\textrm{KL}}(\pi_\theta \Vert e^{Q/\beta}/Z) penalizes placing probability mass in the valley between them, so a unimodal policy cleanly locks onto one peak.
  • Reparameterization (Pathwise Gradient): Writing \tilde{a}_\theta(s, z) = c \tanh\big(\mu_\theta(s) + \sigma_\theta(s) z\big) allows \nabla_\theta L_\pi(\theta) to flow directly through \partial Q_w(s, a) / \partial a via the chain rule.
  • Soft Policy Improvement Theorem: If each state’s reverse-KL projection improves on \pi_{\textrm{old}}, then V^{\pi_{\textrm{new}}}(s) \ge V^{\pi_{\textrm{old}}}(s) holds across all states s.

Why Hard Clipping Breaks the Pathwise Gradient

Bounded Continuous Actions

  • Why hard clipping fails: For |u| > c, \frac{d}{du}\textrm{clip}(u, -c, c) = 0 kills the pathwise actor gradient, and piling tail mass at \pm c makes the continuous density \log \pi(a \mid s) undefined.
  • Smooth squashed Gaussian: Sampling u \sim \mathcal{N}(\mu_\theta(s), \sigma_\theta(s)^2) and setting a = c\tanh(u) \in (-c, c) keeps da/du = c(1 - \tanh^2 u) > 0 everywhere.

The Tanh Change-of-Variables Jacobian

Density Derivation

  • Because a_i = c \tanh(u_i) compresses intervals near the boundaries \pm c by the Jacobian factor da_i / du_i = c(1 - \tanh^2 u_i), conservation of probability \pi(a)\,da = \mathcal{N}(u; \mu, \sigma)\,du yields: \log \pi(a \mid s) = \sum_{i=1}^d \Big[\log \mathcal{N}(u_i; \mu_i, \sigma_i) - \log(1 - \tanh^2 u_i) - \log c\Big]
  • Near a = \pm 2, compressing the upper tail of u produces a boundary density spike; omitting the Jacobian misses this pile-up and integrates to 1.13 \neq 1.

Implementing the Squashed Gaussian Policy

Policy Implementation

SquashedGaussianPolicy wraps a 2-layer ReLU trunk and state-dependent mean and log-std heads (state_std=True), computing \log \pi(a \mid s) directly from the pre-squash draw u without ever calling arctanh:

class SquashedGaussianPolicy(nn.Module):
    """d2l.GaussianHead with SAC's network (two ReLU layers and a
    state-dependent standard deviation), squashed through
    a = scale * tanh(u)."""
    def __init__(self, obs_dim, act_dim, hidden=64, scale=2.0, seed=None):
        super().__init__()
        with d2l.seeded(seed):
            trunk = nn.Sequential(nn.Linear(obs_dim, hidden), nn.ReLU(),
                                  nn.Linear(hidden, hidden), nn.ReLU())
            self.policy = d2l.GaussianHead(obs_dim, act_dim, hidden,
                                           state_std=True, trunk=trunk)
        self.scale = scale

Implementing the Squashed Gaussian Policy (cont.)

Policy Implementation

The change of variables: log_prob_u scores the pre-squash draw u, and sample draws a reparameterized action with its log-probability:

    def log_prob_u(self, u, mean, std):
        """log pi at a = scale tanh(u), from the pre-squash u the sampler
        keeps."""
        logdet = 2 * (np.log(2) - u - nn.functional.softplus(-2 * u))
        return (torch.distributions.Normal(mean, std).log_prob(u)
                - logdet - np.log(self.scale)).sum(-1)

    def sample(self, obs):
        """A reparameterized action and its log-probability, differentiable."""
        mean, std = self.policy(obs)
        u = mean + std * torch.randn_like(std)
        return self.scale * torch.tanh(u), self.log_prob_u(u, mean, std)

Implementing the Squashed Gaussian Policy (acting)

Policy Implementation

Acting in the environment takes numpy states: _draw samples u from the head with the noise of rng, and act squashes it:

    @torch.inference_mode()
    def _draw(self, obs, rng):
        """A pre-squash sample u with the head's mean and std, from numpy
        states and the noise of rng."""
        mean, std = self.policy(torch.as_tensor(obs))
        noise = rng.standard_normal(mean.shape, dtype=np.float32)
        return mean + std * torch.as_tensor(noise), mean, std

    def act(self, obs, rng):
        """A sampled action, numpy in and out."""
        return self.scale * np.tanh(self._draw(obs, rng)[0].numpy())

Implementing the Squashed Gaussian Policy (acting, cont.)

Policy Implementation

act_logp also returns \log \pi(a \mid s), and act_greedy squashes the mean for evaluation:

    @torch.inference_mode()
    def act_logp(self, obs, rng):
        """A sampled action and its log-probability, numpy in and out."""
        u, mean, std = self._draw(obs, rng)
        return (self.scale * np.tanh(u.numpy()),
                self.log_prob_u(u, mean, std).numpy())

    @torch.inference_mode()
    def act_greedy(self, obs, rng=None):
        """The squashed mean scale * tanh(mean), numpy in and out."""
        mean = self.policy(torch.as_tensor(obs))[0].numpy()
        return self.scale * np.tanh(mean)

Numerically Stable Log-Determinant and Quadrature Check

Numerical Precision

In float32, \tanh(u) rounds to 1.000000 for |u| \ge 10, making \log(1 - \tanh^2 u) = -\infty (while a naive +10^{-6} guard freezes at -13.82 and kills the restoring gradient -2\tanh u). Algebraic rewriting eliminates the catastrophic cancellation:

\log\big(1 - \tanh^2 u\big) = \log \frac{4 e^{-2u}}{(1 + e^{-2u})^2} = 2\big(\log 2 - u - \operatorname{softplus}(-2u)\big)

   u      naive    guarded     stable
   0     0.0000     0.0000     0.0000
   3    -4.6187    -4.6186    -4.6187
   8   -14.5561   -13.4256   -14.6137
  10       -inf   -13.8155   -18.6137
  20       -inf   -13.8155   -38.6137
mu = 0.0, sigma = 0.5: integrates to 1.000000 with the log-det, 1.653 without
mu = 0.7, sigma = 0.8: integrates to 1.000000 with the log-det, 1.132 without

Twin Critics and Polyak-Averaged Target Networks

Critic Architecture

  • Clipped Double-Q (Twin Critics): Because an actor climbing \nabla_a Q_w(s, a) systematically seeks out overestimated actions, SAC trains two independent critics Q_{w_1}, Q_{w_2} and takes their pointwise minimum in both the target and the actor loss: y = r + \gamma(1 - \textrm{term})\Big(\min_{j=1,2} Q_{w_j^-}(s', \tilde{a}') - \beta \log \pi_\theta(\tilde{a}' \mid s')\Big)
  • Polyak Averaging (\nu = 0.005): Instead of hard jumps every 250 steps, target weights drift after every update: w_j^- \leftarrow \nu w_j + (1 - \nu) w_j^- (half-life \ln 2 / \nu \approx 139 updates).

Automatic Temperature Tuning via Dual Gradient Descent

Entropy Constraint

J(\beta) = -\log \beta\, \mathbb{E}_{s \sim \mathcal{D},\, a \sim \pi_\theta}\big[\log \pi_\theta(a \mid s) + \bar{H}\big]

  • Target entropy \bar{H} = -\dim(\mathcal{A}): Enforces -1.0\text{ nat} on Pendulum independently of reward scaling.
  • Automatic feedback loop: With \partial J / \partial \log\beta = \hat{H}_{\textrm{batch}} - \bar{H}, excess randomness (\hat{H} > \bar{H}) lowers \log\beta, while narrow entropy (\hat{H} < \bar{H}) raises \log\beta.

The SoftActorCritic Container and Loss Functions

Modular Components

SoftActorCritic packages the squashed Gaussian actor, the twin action-value critics Q_{w_1}, Q_{w_2} (taking concatenated [s, a] \in \mathbb{R}^4), their Polyak target copies, and \log \beta:

def soft_target(agent, rew, next_obs, term, beta, gamma):
    """eq_sac_target_twin at a fresh action from the live policy."""
    with torch.no_grad():                     # the critic target is data
        a2, logp2 = agent.actor.sample(next_obs)
        return rew + gamma * (1 - term) * (
            agent.min_q(next_obs, a2, agent.targets) - beta * logp2)

def critic_loss(qs, obs, act, y):
    """Squared error of every critic against the one shared target y."""
    x = torch.cat([obs, act], -1)
    return sum(((q(x).squeeze(-1) - y) ** 2).mean() for q in qs)

def actor_loss(actor, min_q, obs, beta):
    """beta log pi - min_j Q_j at a fresh reparameterized action; also
    returns log pi."""
    a, logp = actor.sample(obs)
    return (beta * logp - min_q(obs, a)).mean(), logp

Executing One Complete SAC Update Step

The Update Step

Each call to sac_step regresses both critics onto the shared twin-minimum soft target y, updates the actor via the pathwise gradient of \beta \log \pi_\theta - \min_j Q_{w_j}, updates \log \beta toward \bar{H} = -1, and blends the target networks by \nu = 0.005:

def descend(opt, loss):
    """One optimizer step on a loss."""
    opt.zero_grad()
    loss.backward()
    opt.step()

def sac_step(agent, obs, act, rew, next_obs, term, gamma, polyak,
             target_entropy):
    """One SAC update: soft critic regression, pathwise actor step, Polyak
    averaging, and, if the agent learns beta, one temperature step toward
    the target entropy. Returns the batch mean of log pi."""
    beta = agent.beta
    y = soft_target(agent, rew, next_obs, term, beta, gamma)
    descend(agent.opt_q, critic_loss(agent.qs, obs, act, y))
    loss_pi, logp = actor_loss(agent.actor, agent.min_q, obs, beta)
    descend(agent.opt_pi, loss_pi)

Executing One Complete SAC Update Step (cont.)

The Update Step

The temperature step moves \log \beta toward the target entropy, and Polyak averaging drifts the target critics:

    if agent.opt_beta is not None:   # entropy above target: beta falls
        descend(agent.opt_beta, -agent.log_beta * (logp.detach().mean()
                                                   + target_entropy))
    with torch.no_grad():                     # Polyak: the drifting copy
        for q, tnet in zip(agent.qs, agent.targets):
            for pt, pq in zip(tnet.parameters(), q.parameters()):
                pt.lerp_(pq, polyak)
    return logp.detach().mean()

The Off-Policy Continuous Training Loop

Training Loop

After warmup = 1000 uniformly random steps, train_sac executes utd (update-to-data ratio) gradient steps per environment step—allowing us to trade compute for real-world interaction:

def train_sac(seed, agent, buffer, num_env_steps, utd=1, warmup=1_000,
              batch_size=256, gamma=0.99, polyak=0.005, target_entropy=-1.0):
    """SAC on Pendulum: `warmup` uniformly random steps, then `utd` updates
    per environment step. Yields (env step, episode return, policy
    entropy, beta) at the end of every episode."""
    update = make_update(agent, seed, gamma=gamma, polyak=polyak,
                         target_entropy=target_entropy)
    rng, env = np.random.default_rng(seed), gym.make('Pendulum-v1')
    scale, act_dim = agent.actor.scale, buffer.act.shape[1]
    obs, ep_return = env.reset(seed=seed)[0], 0.0
    logp_sum, n_upd = 0.0, 0

The Off-Policy Continuous Training Loop (cont.)

Training Loop

Each environment step acts (uniformly during warm-up), stores the transition, and runs utd updates; episode ends report return, entropy, and \beta:

    for t in range(1, num_env_steps + 1):
        a = (rng.uniform(-scale, scale, act_dim).astype(np.float32)
             if t <= warmup else agent.actor.act(obs, rng))
        next_obs, rew, terminated, truncated, _ = env.step(a)
        buffer.add(obs, a, rew, next_obs, float(terminated))
        obs, ep_return = next_obs, ep_return + rew
        for _ in range(utd if t >= warmup else 0):
            logp_sum = logp_sum + update(buffer.sample(batch_size, rng))
            n_upd += 1
        if terminated or truncated:   # read the device sum once per episode
            yield (t, ep_return, float(-logp_sum / n_upd) if n_upd else np.nan,
                   float(agent.beta))
            obs, ep_return = env.reset()[0], 0.0
            logp_sum, n_upd = 0.0, 0

Sample Efficiency on Pendulum: UTD 1 vs. UTD 10

Sample Efficiency

  • 1 Update per Step (UTD 1): Crosses -200 in 5{,}400 to 11{,}200 steps over 20 seeds (5{,}400–6{,}600 on the three shown)—nearly 50\times fewer steps than REINFORCE.
  • 10 Updates per Step (UTD 10): Crosses -200 in 2{,}400 to 4{,}000 steps over 20 seeds (2{,}400–2{,}600 on the three shown, near the 2{,}000-step warm-up + window floor), paying \sim 3\times more gradient steps up to the crossing.

UTD 1: steps to a five-episode average of -200, per seed 6200, 5400, 6000
UTD 10: steps to a five-episode average of -200, per seed 2400, 2400, 2600

Diagnosing the Early Return Dip: Damping Before Pumping

Behavioral Analysis

Why do returns drop from the random policy’s -1{,}200 down to -1{,}700 around step 2{,}000 before climbing to -170? Comparing the 2{,}000-step actor against three analytic controllers explains the dip:

            policy   return  cos theta  |theta dot|
       zero torque    -1290      -0.49         2.50
              spin    -1610       0.04         6.83
              damp    -1886      -0.96         0.22
 SAC at 2k, seed 0    -1789      -0.93         0.55
 SAC at 2k, seed 1    -1769      -0.93         0.69
 SAC at 2k, seed 2    -1784      -0.93         0.63
SAC at 20k, seed 0     -167       0.83         0.58

Myopic Damping Phase: At 2{,}000 steps, the young critic has only propagated rewards a few steps ahead, where reducing angular velocity cost 0.1\dot\vartheta^2 dominates. The actor therefore damps motion (|\dot\vartheta| < 1\text{ rad/s}), leaving the pendulum hanging still at the bottom (\cos\vartheta \approx -0.93, costing \pi^2 \approx 9.9 per step) until multi-step swing-up value propagates.

Policy Entropy Dynamics: Learned vs. Fixed Beta

Entropy Trajectory

  • Learned \beta (blue): Smoothly brings policy entropy from +1.1\text{ nats} down onto the target \bar{H} = -1.0\text{ nat} and holds it flat from 15{,}000 steps onward.
  • Fixed \beta = 0.2 (orange): Entropy dips to -1.3\text{ nats} during swing-up learning, then rebounds upward once balancing is mastered—because a balanced critic has flat curvature h, and a quadratic critic’s optimal Gaussian variance scales as \sigma^2 = \beta / h.

learned beta: entropy over the last 20 episodes, per seed [-0.97 -0.99 -0.95]
beta = 0.2: entropy over the last 20 episodes, per seed [-0.15 -0.02  0.09]

Dual Temperature Trajectory and Sampling Cost

Temperature & Evaluation

  • Log-Linear Decay: While \hat{H} > -1, Adam steps \log \beta downward by its learning rate \approx 3 \times 10^{-4} per update, matching the predicted e^{-1.8} \approx 0.17 at 6{,}000 updates (7\text{k} env steps) before settling near 0.03.

learned beta, median over seeds at 2k, 7k and 20k steps: [0.744 0.212 0.03 ]

Dual Temperature Trajectory and Sampling Cost (cont.)

Temperature & Evaluation

  • Zero-Cost Exploration at Convergence: Evaluating the deterministic mean action c\tanh\mu_\theta(s) vs. stochastic sampling shows that state-dependent spread costs at most \sim 10 return points.
     UTD 1: mean action [-188. -147. -184.], cost of sampling [-5.9  0.2  0.1]
    UTD 10: mean action [-186. -139. -185.], cost of sampling [0.3 0.1 0. ]
beta = 0.2: mean action [-179. -142. -184.], cost of sampling [ 7.2  6.6 -0.8]

Critic Calibration: Twin Minimum vs. Single Critic

Value Calibration

Comparing the start-state prediction \min_j Q_{w_j}(s_0, a_0) against the realized 200-step discounted soft return \sum_{t=0}^{199} \gamma^t (r_t - \beta \log \pi_\theta(a_t \mid s_t)) reveals what the twin-critic minimum prevents:

   twin, UTD 1, seed 0: predicted  -154.6, realized  -114.3, gap  -40.3
   twin, UTD 1, seed 1: predicted  -113.2, realized   -94.8, gap  -18.4
   twin, UTD 1, seed 2: predicted  -172.0, realized  -138.7, gap  -33.3
  twin, UTD 10, seed 0: predicted  -136.7, realized  -116.4, gap  -20.3
  twin, UTD 10, seed 1: predicted   -88.3, realized   -93.1, gap   +4.8
  twin, UTD 10, seed 2: predicted  -158.9, realized  -140.4, gap  -18.5
single, UTD 10, seed 0: predicted   -68.1, realized  -119.7, gap  +51.6
single, UTD 10, seed 1: predicted   -57.5, realized   -94.9, gap  +37.4
single, UTD 10, seed 2: predicted  -105.9, realized  -143.4, gap  +37.5

While both reach -200 on Pendulum, the single critic systematically overestimates the true soft return on nearly every seed, whereas the twin minimum provides a conservative lower bound.

Concept Check: Limits, Curvature, and Jacobian Forces

Check Your Understanding

Test your understanding of SAC’s mathematical mechanics:

  1. Deterministic Limit: If you set both the temperature \beta = 0 and the policy standard deviation \sigma_\theta = 0 in SAC’s actor loss and twin-critic target, which algorithm do you recover, and how must it explore?
  2. Reward Rescaling: If you multiply all Pendulum rewards by 10, how must \beta change to leave the exact optimal policy \pi^\star unchanged, and how does automatic temperature tuning respond?
  3. Jacobian Restoring Force: Using \log(1 - \tanh^2 u) = 2(\log 2 - u - \operatorname{softplus}(-2u)), what is \frac{\partial}{\partial u}\big[-\beta \log(1 - \tanh^2 u)\big] in the actor loss, and what happens if you use the guarded formula \log(1 - \tanh^2 u + 10^{-6}) at u = 12 in float32?

Answers:

  1. The actor loss becomes -\min_{j=1,2} Q_{w_j}(s, c\tanh\mu_\theta(s)): DDPG with TD3’s twin critics. Because the policy is deterministic, external noise must be added to actions during collection.
  2. Scaling r \to 10r requires \beta \to 10\beta so r/\beta stays invariant; automatic temperature tuning automatically settles at a 10\times larger \beta because \partial J(\beta)/\partial \log\beta = \hat{H} - \bar{H} depends only on entropy.
  3. The exact derivative is +2\beta \tanh(u), which pulls saturated pre-squash activations u back toward 0; in float32 at u = 12, 1 - \tanh^2(12) underflows to 0, so the guarded formula’s derivative vanishes to 0.

Summary: Soft Actor–Critic Components and Roles

Key Takeaways

SAC Component Mathematical Expression Problem Solved Measured Effect on Pendulum
Soft Critic Target r + \gamma(1-\textrm{term})\big(\min_j Q_{w_j^-}(s', \tilde{a}') - \beta \log \pi_\theta(\tilde{a}' \mid s')\big) Off-policy value estimation without importance ratios Evaluates reward + future entropy from 1 fresh draw \tilde{a}'
Pathwise Actor Loss \mathbb{E}_{s, z}\big[\beta \log \pi_\theta(\tilde{a}_\theta \mid s) - \min_j Q_{w_j}(s, \tilde{a}_\theta)\big] High variance of score-function gradients Direct \partial Q / \partial a slope; \sim 50\times fewer steps than REINFORCE
Tanh Log-Det Jacobian -2\big(\log 2 - u - \operatorname{softplus}(-2u)\big) - \log c Undefined density & dead gradients of hard clipping Density integrates to 1.000000 without float32 underflow
Twin Critics + Polyak \min(Q_{w_1^-}, Q_{w_2^-}), w_j^- \leftarrow 0.005 w_j + 0.995 w_j^- Continuous maximization bias as actor climbs Q Keeps predicted soft values calibrated below realized returns
Dual Temperature (\beta) \min_{\log\beta} -\log\beta\, \mathbb{E}[\log \pi_\theta(a \mid s) + \bar{H}] Sensitivity of fixed \beta to reward scale and critic curvature Locks policy entropy at \bar{H} = -1\text{ nat} as critic flattens