SAC¶
Soft Actor-Critic learns a stochastic policy that maximises the reward plus
the policy's entropy, so it keeps exploring while it improves. Two critics
estimate the action value, the target takes the smaller of the two target
critics' values to curb over-estimation, and the entropy weight alpha
tunes itself towards a target entropy.
Papers: Haarnoja et al., Soft Actor-Critic, 2018
(arXiv:1801.01290), with the learned
temperature of Haarnoja et al., Soft Actor-Critic Algorithms and
Applications, 2018 (arXiv:1812.05905).
Ajax follows the authors' code for the latter, rail-berkeley/softlearning
at a1253bc.
When to use it¶
SAC is the default agent for continuous actions when environment steps are costly: it learns off-policy from a replay buffer and reuses each transition many times. It also runs more expert-guidance modules than any other agent. With many cheap parallel environments, PPO learns from fresh rollouts instead; for a deterministic policy, see TD3.
| Feature | SAC |
|---|---|
| Discrete actions | no |
| Continuous actions | yes, a tanh-squashed Gaussian, mapped onto the environment's bounds |
Memory (memory=) |
yes, on replayed sequences, without expert_policy or most extensions (Memory) |
| Environments | gymnax, Brax, MuJoCo Playground |
| Image observations | no |
| PID policy | yes, actor_architecture=PIDPolicy(...) (Networks) |
| Several seeds in one call | yes, train(seed=[...]) |
| Offline training | yes, train_offline (Training); also CQL and Cal-QL |
| Extension phases | pretrain, post_update, eval_metrics, observe, on_target, critic_loss, actor_loss, action, eval_action, transform_action, actuate, choose_warmup_action, choose_replay_action, track_memory (which extensions run) |
| Resume and checkpoints | yes; a run split by a checkpoint equals the run left whole |
Example¶
from ajax import SAC
from ajax.logging import LoggingConfig
agent = SAC("Pendulum-v1", n_envs=4, learning_starts=1_000)
logging = LoggingConfig(log_frequency=2_000, backends=())
state, evaluations = agent.train(seed=[0, 1], n_timesteps=4_000, logging_config=logging)
print(evaluations["timestep"][0]) # when each evaluation ran
print(evaluations["Eval/episodic mean reward"]) # one row per seed
train runs both seeds side by side in one compiled program. This budget
only shows the call: Pendulum needs more steps to be solved. See
Training for resuming, and
Logging for Weights & Biases or TensorBoard.
Key hyperparameters¶
The defaults are softlearning's; Coming from SB3 lists where they differ from Stable-Baselines3's. The API section lists every argument.
| Argument | Default | What it does |
|---|---|---|
n_envs |
1 |
parallel environments |
actor_learning_rate, critic_learning_rate, alpha_learning_rate |
3e-4 |
Adam step sizes (epsilon 1e-8, TensorFlow's) |
actor_architecture, critic_architecture |
("256", "relu", "256", "relu") |
hidden layers |
gamma |
0.99 |
discount |
tau |
0.005 |
Polyak rate of the target critics |
buffer_size |
1_000_000 |
replay capacity |
batch_size |
None |
rows per update: 256, or 64 sequences with memory= |
learning_starts |
10_000 |
steps of uniform random actions before the first update |
alpha_init |
1.0 |
initial entropy weight |
fixed_alpha |
False |
keep alpha at alpha_init |
target_entropy_per_dim |
-1.0 |
target entropy per action dimension: a number, or a schedule of the timestep |
num_critics |
2 |
critics; the target takes their minimum |
num_critic_updates |
1 |
critic steps per update, on the same batch |
n_step |
1 |
rewards each target sums before it bootstraps |
reward_scale |
1.0 |
multiplies the rewards in the target |
max_grad_norm |
None |
gradient clipping of the actor and the critics |
normalize_observations, normalize_rewards |
False |
running normalisation (Environments) |
memory, burn_in, sequence_length, stored_state |
None, 0, 64, False |
recurrent memory and its sequence replay (Memory) |
episode_length, action_repeat |
None, 1 |
simulator steps per episode and per agent step, on Brax and Playground; None is 1,000 steps, or a mujoco: task's own time limit (Environments) |
extensions |
() |
research features (Extensions) |
Expert options¶
| Argument | Default | What it does |
|---|---|---|
expert_policy |
None |
an expert, in the environment's units, that the run tracks and the expert extensions read; each evaluation logs its return |
eval_expert_policy |
None |
an expert whose return each evaluation logs, which takes no other part in the run |
SAC's other expert options are extensions now
(Expert guidance): ExpertPrefill writes
the expert's steps to the replay, ExpertWarmup lets it take part of the
warm-up, CloningPretrain clones it into the actor, ExpertGains makes the
actor output its PID's gains, and ExpertActionInput and ExpertStateInput
append its action and state to the observation. MCPretrain, an expert
critic fitted on its Monte-Carlo returns, runs on SAC alone.
Differences from the reference¶
- Update order. softlearning runs the critic, actor and temperature
steps in one
session.run(sac.py:348-353): every gradient reads the parameters from before the update, and the temperature reads the actor loss's own sample. Ajax makes the steps one after the other: the actor reads the stepped critics, and the temperature a fresh sample of the stepped actor, as softlearning's TensorFlow 2 port (13cf187,sac.py:277-281) and CleanRL do. - Output heads. The reference draws the mean and the log-std from one output layer; Ajax's two heads each take Glorot's bound for their own width (about 1% wider with 256 inputs).
- Ajax's own options, off by default:
n_stepreturns,policy_update_startandalpha_update_start(the timesteps from which the actor andalphaupdate), a schedule astarget_entropy_per_dim, and the expert options above.
Notes¶
- Actions. The warm-up's uniform actions cover the whole box, and the
replay stores the agent's
[-1, 1]action. Evaluation uses the mean action. - Initialisation. Glorot-uniform kernels and zero biases in every
layer, as in
haarnoja/sacand softlearning. Withmemory=, SAC is Ni et al. (2022)'s recurrent SAC, networks, losses and initialisation included (Memory). - Standard deviation. The log-std is clipped to
[-20, 2]and the standard deviation is its exponential, as inhaarnoja/sacand in softlearning at the time of the paper; later softlearning usessoftplus(x) + 1e-5. - Updates per step. Each iteration steps every environment once, then
makes one update:
num_critic_updatescritic steps, one actor step, one temperature step and one target update. Withn_envs=4that is one update per four environment steps. - Time limits. A transition cut by a time limit bootstraps on its final observation; only a termination stops the bootstrap.
- Temperature. The
alphastep is never gradient-clipped, even withmax_grad_normset, as in the reference: clipping would turn it into a sign step. - Memory. With
memory=, SAC replays 64 sequences of 64 steps, each from a zero memory, as Ni et al. (2022) do, with R2D2'sburn_inandstored_stateas options (Kapturowski et al. 2019). Of the extensions it then takes only the observation features andStorePolicyAction, refusing the others when training starts.
CQL and Cal-QL: offline¶
CQL (Kumar, Zhou, Tucker and Levine, Conservative Q-Learning for Offline
Reinforcement Learning, NeurIPS 2020,
arXiv:2006.04779) adds a critic term
that pushes the values down on actions away from the data's and up on the
data's. Cal-QL (Nakamoto et al., Cal-QL: Calibrated Offline RL
Pre-Training for Efficient Online Fine-Tuning, NeurIPS 2023,
arXiv:2303.05479) floors that push at
the data's Monte-Carlo returns, so that fine-tuning online does not start
from values far too low. Both are extensions of SAC, trained with
train_offline:
from ajax import SAC
from ajax.extensions.offline import CalQL, ConservativeQ
agent = SAC(
"Pendulum-v1",
actor_learning_rate=1e-4, # the references' policy rate
learning_starts=0, # online fine-tuning updates from the first step
extensions=(ConservativeQ(alpha=5.0),), # or CalQL(alpha=5.0)
)
# state, evaluations = agent.train_offline(dataset, n_updates=1_000_000)
The term is the authors' importance-sampled CQL(H)
(aviralkumar2907/CQL at d67dbe9, cql.py:234-264): for each critic,
the logsumexp of its values at 10 uniform actions and at 10 of the
policy's at s and at s', each less its log-density, minus its value at
the data's action, times alpha (5 in the references' gym runs). Cal-QL
first takes the larger of each policy action's value and the row's return
to go (nakamotoo/Cal-QL at ac6eafe,
JaxCQL/conservative_sac.py:227-240), which the transition dataset holds
at its gamma; collected rows have none and are not floored, where the
reference computes theirs as episodes end. Both need a policy with a
density, so TD3 refuses them. One more difference from the references:
SAC's target keeps its entropy term, which the CQL reference's
deterministic_backup drops.
Results¶
The reproduction results set SAC beside
Stable-Baselines3's and SBX's on Pendulum, with learning curves. The probes
(tests/probing) train it briefly on tiny environments with known answers:
the soft bootstrap, discounting, time limits, reward scale, memory, every
extension phase it folds, and a run split by a checkpoint matching the run
left whole. Performance compares its speed with
the other agents'.
API¶
ajax.agents.SAC.SAC.SAC
dataclass
¶
SAC(
env_id,
*,
n_envs=1,
env_params=None,
weight_decay=0.0,
episode_length=None,
action_repeat=1,
extensions=(),
buffer_size=int(1000000.0),
batch_size=None,
learning_starts=int(10000.0),
train_frequency=1,
memory=None,
burn_in=0,
sequence_length=NI_WINDOW_STEPS,
stored_state=False,
share_encoder=None,
expert_policy=None,
eval_expert_policy=None,
normalize_rewards=False,
reward_normalization_gamma=None,
normalize_observations=False,
observation_clip=None,
max_grad_norm=None,
policy_update_start=0,
alpha_learning_rate=0.0003,
alpha_init=1.0,
target_entropy_per_dim=-1.0,
alpha_update_start=0,
actor_learning_rate=0.0003,
critic_learning_rate=0.0003,
actor_architecture=("256", "relu", "256", "relu"),
critic_architecture=("256", "relu", "256", "relu"),
gamma=0.99,
tau=0.005,
reward_scale=1.0,
fixed_alpha=False,
num_critics=2,
num_critic_updates=1,
n_step=1,
)
Bases: EntropyTemperature, PolicyUpdateStart, GradientClipping, ObservationNormalization, RewardNormalization, ExpertGuided, EncoderSharing, RecurrentReplayAgent
Soft Actor-Critic with a learned temperature (the module's update).
Defaults are the learned-temperature version's (rail-berkeley/ softlearning): 256-256 ReLU networks, two critics, Adam at 3e-4 with TensorFlow's eps 1e-8, tau 0.005, gamma 0.99, a target entropy of -1 per action dimension, a 1e6 replay, batch 256 and 1e4 warm-up steps (softlearning@a1253bc examples/development/variants.py:92-95, ten episodes of 1,000 steps on its benchmark domains; its base value, :51, is 1e3). The actor and the temperature step with the critics from the first update, as softlearning's single session.run of all its training ops does (a1253bc sac.py:348-353); policy_update_start and alpha_update_start can delay them.
n_step above 1 is Ajax's and not SAC's: the critics' target sums n_step rewards before it bootstraps, gamma^n in place of gamma, stopping at an episode's end. The return is uncorrected, as Rainbow's is (Hessel et al. 2018): no importance weights for steps the current policy would not have taken, and no entropy bonus for the steps between. The first update waits for each env's replay to hold n_step rows, whatever learning_starts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tau
|
float
|
The target critics' Polyak rate. |
0.005
|
fixed_alpha
|
bool
|
Keep the temperature at alpha_init (SAC v1's fixed temperature); its loss is still computed for the logs. |
False
|
num_critics
|
int
|
The critics, whose minimum the targets and the actor read. |
2
|
num_critic_updates
|
int
|
The critic steps of each update, all on the same replay batch (REDQ's steps each sample a fresh one). |
1
|
n_step
|
int
|
The steps of the return each target sums (1: SAC's own). A run with memory refuses more than 1. |
1
|
init ¶
A squashed Gaussian actor, num_critics Q critics with their targets, and the temperature.
update ¶
num_critic_updates critic steps on one replay batch, then the actor's and the temperature's steps on it, each kept from its start, then the target critics' Polyak update.
update_critic ¶
The critics' step on SAC's soft target. Under a residual policy the bootstrap reads the executed next action, from the expert's stored action at s', so the critics are queried where they were trained.
update_actor ¶
The actor's step on SAC's soft policy loss, the critics scoring a residual policy's executed actions from the expert's stored ones, which the actor-loss extensions (OnlineBC, ImitationLoss) read as their clone target. Also returns the log-probs of a fresh sample of the stepped actor, which the temperature's step reads (CleanRL's order: vwxyzjn/cleanrl@fe8d8a0, cleanrl/sac_continuous_action.py:279-292); with memory, the mean of the loss's own, before the step, as Ni et al.'s recurrent SAC (policy_rnn.py:180-216).