SAC & TD3: Continuous Control RL
Up to now, actions were simple choices: left, right, jump. But a legged robot in MuJoCo, a robot arm, a drone, they all need precise continuous control: exact joint torques, smooth velocities, microsecond timing. SAC and TD3 are the algorithms purpose-built for that world, and they are standard choices for robot learning research.
After this lesson, you will be able to:
- Understand maximum entropy RL: the SAC objective maximizes reward PLUS entropy at every step (J = E[Σ γ^t (r_t + α·H(π(·|s_t)))]), making the policy as random as possible while still collecting reward
- See SAC's twin-critic trick: two independent Q-networks trained together prevent the Q-value overestimation that made DDPG unstable, using min(Q1, Q2) as a pessimistic target
- Understand why continuous action spaces require fundamentally different algorithms than discrete ones, and why PPO, SAC, and TD3 occupy distinct niches in the algorithm zoo
- Know how SAC's automatic entropy tuning treats α as a Lagrange multiplier to maintain a target entropy level, removing the biggest hyperparameter from the algorithm
Before you start
#The Continuous Control Problem
Now consider a robot arm with 7 joints. Each joint needs a torque command, a continuous real number, say in [-1, 1]. The action space is a 7-dimensional continuous space. You cannot enumerate "all possible actions" and compute Q-values for each. There are infinitely many.
SAC (Soft Actor-Critic) and TD3 (Twin Delayed DDPG) are off-policy algorithms specifically designed for continuous control. They are more sample efficient than PPO because they reuse data in a replay buffer, and they handle the instabilities that plagued earlier off-policy continuous control algorithms.
#Maximum Entropy RL: The Core Framework
Standard RL maximizes expected cumulative reward:
Maximum entropy RL adds an entropy bonus at every time step:
The entropy term H(π(·|s)) = -∫ π(a|s) log π(a|s) da measures how spread out the policy is. A deterministic policy has zero entropy. A uniform random policy has maximum entropy.
- Better exploration: The agent is incentivized to try many different actions, naturally discovering diverse strategies
- Robustness: Policies that maximize entropy tend to generalize across variations in the environment (they haven't over-committed to one path)
- Multiple optimal policies: If two strategies achieve the same reward, MaxEnt prefers the one that remains more uncertain: maintaining optionality
- Automatic entropy tuning: α can be treated as a Lagrange multiplier and automatically tuned to maintain a target entropy level
#The Soft Value and the Best Policy for a Given Q
The entropy bonus changes what "value" means. The soft state value V is the expected sum of discounted reward plus entropy bonus, started from state s. Entropy is minus the expected log-probability, so V needs only one log term, and the matching Q-function obeys a Bellman equation that looks just like the ordinary one.
Open the derivation to see where both equations come from.
For a fixed Q, which policy does the objective prefer at one state? The answer is a softmax of Q with temperature alpha. This is exactly the shape the slider above draws: small alpha sharpens it, large alpha flattens it.
Plugging the best policy back in gives a closed form for the soft value. Its two limits show what alpha does.
SAC cannot solve the softmax exactly when actions are continuous, so it trains the policy network to be close to it. The policy loss used in the algorithm below is that closeness, measured as a KL divergence.
#Continuous Actions: Gaussian Policy
The correction term is a result, not a convention. It comes from the rule for how a probability density changes when the variable is transformed.
SAC trains the policy by gradient descent on the loss above. The loss is an average over actions that the policy itself produces, so the gradient has to pass through the sampling step. Write the action as a function of the weights and an outside noise draw epsilon, as in the sampling code above, and it can. For one scalar action, with Q'(a) meaning the slope of Q in the action, the result is:
#The Overestimation Bug: Why One Critic Is Not Enough
In practice, DDPG Q-values would spike upward during training and then catastrophically crash, producing an unstable policy.
#The Twin-Critic Trick
TD3 and SAC both solve this with the same elegant fix: train two independent Q-networks and use the minimum of their predictions as the target.
Why does this work? Each Q-network has independent random initialization and samples different mini-batches for training, so their errors are only partly correlated. For one fixed state-action pair the minimum is not closer to the truth than either critic: it is biased low, as the derivation below shows. The benefit appears when a maximisation follows, because a policy that maximises Q seeks out the actions where a critic's error is positive, and the minimum of two critics removes much of that selection effect:
- If Q1 overestimates an action: min(Q1, Q2) = Q2, which is less likely to be inflated at that same action
- If Q2 overestimates an action: min(Q1, Q2) = Q1, with the same benefit
- If both overestimate: min is still less extreme than either individually
The minimum biases the estimate downward (pessimistic), but slight underestimation is far preferable to the divergent overestimation that destroyed DDPG.
How low does the minimum sit? The size of the downward bias is worth knowing, because it is the price paid for the protection. The upward bias of a maximum over noisy estimates is derived in Deep Q-Networks (DQN).
The soft update makes the target network an exponential moving average of the live weights. Unrolling the update shows exactly how the target remembers the past.
#SAC: The Full Algorithm
SAC trains four networks simultaneously (plus two target networks):
- Policy network π_θ: maps states to Gaussian parameters (μ, σ)
- Q-network 1 Q_φ1(s,a): estimates Q-value for state-action pairs
- Q-network 2 Q_φ2(s,a): estimates Q-value (independent from Q1)
- Target Q-networks Q_φ1_target, Q_φ2_target: slow-moving copies for stable targets
SAC does not have a separate value network V(s) in the modern version (Haarnoja et al. 2019 simplified the original formulation, V(s) can be computed analytically from Q and the policy entropy).
SAC Training Loop
#Step 1: Collect Experience into Replay Buffer
Run the current policy in the environment, storing (state, action, reward, next_state, done) transitions in a replay buffer (typically 1M capacity). At the start of training, explore randomly for a warmup period (e.g., 10,000 steps) before using the policy.
Unlike PPO (which discards data after each update), SAC keeps ALL collected experience. A transition from 500,000 steps ago can still be sampled and used for training today.
#Step 2: Sample Mini-Batch from Replay Buffer
Sample a random mini-batch of B=256 transitions from the replay buffer. Random sampling breaks temporal correlations between consecutive transitions, which stabilizes training. This is the same insight as DQN's experience replay.
The mini-batch contains diverse transitions from different stages of training, some from early random exploration, some from the current near-optimal policy. This diversity is what makes off-policy learning powerful.
#Step 3: Compute Q-Targets with Twin Critics
For each transition, compute the target value: y = reward + gamma * min(Q1_target(s', a'), Q2_target(s', a')) - alpha * log_pi(a'|s')
where a' is sampled fresh from the current policy at the next state. The entropy term (-alpha * log_pi) is SAC's key addition, it penalizes low-entropy targets, incentivizing exploration.
The min of twin critics prevents Q-value overestimation. The target networks (not the live networks) are used here, this prevents the "chasing your own tail" instability.
#Step 4: Update Both Q-Networks
Train Q1 and Q2 independently to minimize MSE against target y: L_Q = (Q(s,a) - y)^2
Both networks receive the same target y. Their independent random initializations and mini-batch sampling ensure their errors remain uncorrelated, keeping the min trick effective.
#Step 5: Update the Policy
The policy is updated to maximize Q-value plus entropy: L_pi = E[alpha * log_pi(a|s) - Q(s,a)]
where a is sampled from pi(.|s) using the reparameterization trick (so gradients flow back to the policy network). The policy is trained to produce actions that Q-networks rate highly AND maintain high entropy.
Use the minimum of the two Q-networks here too, as the SAC paper does (Haarnoja et al., 2018, section 4.2): the same pessimism that protects the targets stops the policy from exploiting one network's errors. The live networks are used here, not the target networks.
#Step 6: Update Alpha (Automatic Entropy Tuning)
Optionally, tune alpha automatically by treating it as a Lagrange multiplier with target entropy H_target = -dim(A): L_alpha = alpha * (-log_pi(a|s) - H_target)
If the policy's entropy is below H_target (too deterministic), increase alpha to encourage more exploration. If above H_target (too random), decrease alpha. This removes the need to manually tune the exploration-exploitation balance.
#Step 7: Soft-Update Target Networks
Slowly blend the live Q-network weights into the target networks with rate tau=0.005: phi_target = tau * phi + (1-tau) * phi_target
The target networks move slowly and smoothly, preventing the training target from oscillating. This is Polyak averaging, the same technique used in DDPG and TD3.
#TD3: The Deterministic Alternative
The noise is not decoration. Averaging the target over a small neighbourhood of actions smooths the value estimate, which the next derivation makes exact for small noise.
#SAC vs TD3 vs PPO: When to Use What
A robot arm needs to control 7 joint angles simultaneously. You try PPO with discrete action bins (3 bins per joint = 3^7 = 2,187 action combinations). It fails to learn anything useful. Why is SAC a better fit?
The combinatorial explosion is the primary issue: 2,187 discrete actions means the Q-function has to learn precise values for thousands of action bins, most of which are never visited. SAC outputs a continuous 7-dimensional Gaussian directly. The policy gradient flows through the continuous action space smoothly, without the need to enumerate all possible actions.
Additionally, joint angles are physically continuous, a torque of 0.501 Nm and 0.500 Nm are nearly identical. Discrete bins throw away this structure. SAC's Gaussian policy exploits it naturally.
| Algorithm | Action Space | Policy Type | Sample Efficiency | Key Strength |
|---|---|---|---|---|
| PPO | Discrete or continuous | Stochastic | Medium | Stability, simplicity, RLHF |
| SAC | Continuous | Stochastic (Gaussian) | High | Sample efficiency, robustness |
| TD3 | Continuous | Deterministic | High | Simpler to tune than SAC |
| DDPG | Continuous | Deterministic | Medium | Predecessor to TD3/SAC |
Use PPO when
- Action space is discrete (Atari, board games, text tokens)
- You need a well-understood algorithm with minimal hyperparameter tuning
- Training in massively parallel environments (thousands of game copies)
- Alignment/RLHF pipelines
Use SAC when
- Continuous action space (robot joints, motor torques, steering angles)
- Sample efficiency is critical (real robot, expensive simulator)
- You want automatic exploration without manual tuning of exploration parameters
- Standard benchmark: MuJoCo locomotion (HalfCheetah, Ant, Humanoid)
Use TD3 when
- Continuous action space, deterministic policy is preferred (predictable behavior)
- You need a simpler implementation than SAC (no entropy term, no reparameterization)
- Stable-Baselines3 TD3 as a drop-in baseline
#The Overestimation Experiment
Tests: After 500 steps, single Q average should be significantly above 1.0 (overestimation). Twin Q average should stay within 0.1 of 1.0. Print the percentage error: (avg_q - 1.0) / 1.0 * 100 for both methods.
#Automatic Entropy Tuning
We want the policy entropy to be at least H_target = -dim(A) (a rule of thumb: the negative of the number of action dimensions). α is adjusted to enforce this constraint:
The loss looks like a trick. It is the gradient step of a Lagrangian dual, which the derivation below unrolls.
In practice, automatic entropy tuning removes the biggest hyperparameter from SAC, you no longer need to search over α values. This makes SAC easier to apply to new tasks.
#Production Context
#Key Takeaways
- Maximum entropy RL adds an entropy bonus at every step. SAC maximizes reward PLUS entropy, incentivizing the policy to remain stochastic and exploratory rather than collapsing to a brittle deterministic strategy; this is what makes SAC robust to environment variations and local optima
- Twin critics prevent the Q-value overestimation that caused DDPG to diverge. Two independently initialized Q-networks have uncorrelated estimation errors; using min(Q1_target, Q2_target) as the TD target introduces a conservative downward bias that cancels the systematic upward bias from the max operator in the policy update
- SAC is off-policy: it reuses experience from a large replay buffer. Unlike PPO which discards data after each update, SAC stores all transitions and samples random mini-batches; in the SAC paper's MuJoCo experiments, SAC learned considerably faster than PPO, with the gap largest on the high-dimensional tasks (the paper reports learning curves, not a single speedup factor)
- Choose SAC for continuous control, PPO for discrete actions and RLHF. The two algorithms occupy complementary niches: SAC's Gaussian policy and off-policy replay shine in robotics and physics simulation; PPO's simplicity, stability, and on-policy nature make it the standard for LLM alignment and massively parallel discrete environments
#Quick Check
What does the entropy term in SAC's objective function accomplish?