QDpy
Loading...
Searching...
No Matches
sac.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Continuous Soft Actor-Critic for caller-supplied Gymnasium environments."""
6
7from collections import Counter
8from copy import deepcopy
9from dataclasses import dataclass
10from math import isfinite, log, pi, prod
11
12import numpy as np
13import torch
14from torch.nn import functional as F
15
16from .policy import ContinuousPolicy, PolicyConfig, _BoxLayout, _integer, _read_actor, _save_actor
17from .rollout import _Cursor, _StepBudget, _check_spaces, _open_environment, _seed
18from .td3 import OffPolicyStats, _Replay, _checked_step, _critic, _polyak, _twin_critics
19
20
21
22@dataclass(frozen=True)
24 """Configure the actor, two reward critics, and learned entropy temperature.
25
26 :param replay_capacity: Maximum transitions in the FIFO replay.
27 :param batch_size: Uniform replay minibatch size, sampled with replacement.
28 :param learning_starts: Exploration steps before the first possible update.
29 :param critic_hidden_sizes: Hidden ReLU layers of each independent critic.
30 :param actor_learning_rate: Adam learning rate for the actor.
31 :param critic_learning_rate: Adam learning rate for both reward critics.
32 :param temperature_learning_rate: Adam learning rate for log temperature.
33 :param gamma: Reward discount in [0, 1).
34 :param tau: Fraction of online critic weights mixed into each target.
35 :param initial_temperature: Initial positive entropy weight.
36 :param target_entropy: Target in normalized action coordinates, default
37 minus the number of flattened action coordinates for standalone SAC.
38 """
39
40 replay_capacity: int = 100_000
41 batch_size: int = 128
42 learning_starts: int = 256
43 critic_hidden_sizes: tuple[int, ...] = (128, 128)
44 actor_learning_rate: float = 3e-4
45 critic_learning_rate: float = 3e-4
46 temperature_learning_rate: float = 3e-4
47 gamma: float = 0.99
48 tau: float = 0.005
49 initial_temperature: float = 1.0
50 target_entropy: float | None = None
51
52 def __post_init__(self):
53 for name in ("replay_capacity", "batch_size"):
54 object.__setattr__(self, name, _integer(getattr(self, name), name))
55 object.__setattr__(self, "learning_starts", _integer(self.learning_starts, "learning_starts", 0))
56 object.__setattr__(self, "critic_hidden_sizes", PolicyConfig(self.critic_hidden_sizes).hidden_sizes)
57 if self.batch_size > self.replay_capacity:
58 raise ValueError("batch_size must not exceed replay_capacity.")
59 for name in ("actor_learning_rate", "critic_learning_rate", "temperature_learning_rate",
60 "initial_temperature"):
61 if not 0 < getattr(self, name) <= np.finfo(np.float32).max:
62 raise ValueError(f"{name} must be finite, positive and representable in float32.")
63 if self.initial_temperature < np.finfo(np.float32).tiny:
64 raise ValueError("initial_temperature must be at least the smallest normal float32.")
65 if not 0 <= self.gamma < 1 or not 0 < self.tau <= 1:
66 raise ValueError("gamma must be in [0, 1) and tau in (0, 1].")
67 if self.target_entropy is not None and not abs(self.target_entropy) <= np.finfo(np.float32).max:
68 raise ValueError("target_entropy must be finite and representable in float32.")
69
70
71def _actor_metadata(actor, kind, shape):
72 return dict(version=1, kind=kind, observation_shape=shape, action_shape=actor._actions.shape,
73 low=actor._actions.low, high=actor._actions.high, dtype=actor._actions.dtype,
74 hidden_sizes=actor.config.hidden_sizes)
75
76
77def _load_actor_layout(path, kind):
78 metadata, parameters = _read_actor(path)
79 if metadata.get("version") != 1 or metadata.get("kind") != kind:
80 raise ValueError(f"Unsupported {kind} policy artifact.")
81 shape = tuple(_integer(size, "Observation extent") for size in metadata["observation_shape"])
82 actions = _BoxLayout(tuple(_integer(size, "Action extent") for size in metadata["action_shape"]),
83 tuple(metadata["low"]), tuple(metadata["high"]), metadata["dtype"])
84 return metadata, parameters, shape, actions, PolicyConfig(tuple(metadata["hidden_sizes"]))
85
86
87
89 """Map fixed Box observations to continuous actions with a squashed Gaussian.
90
91 The actor predicts a diagonal Gaussian mean and scale from the observation.
92 The act method uses the squashed mean by default. Set deterministic=False
93 to sample. Both paths restore the original Box shape, dtype and bounds.
94
95 :param observation_space: Fixed-shape numeric Gymnasium Box.
96 :param action_space: Finite floating-point Gymnasium Box.
97 :param config: Optional actor architecture as a PolicyConfig.
98 :param seed: Nonnegative seed for initialization and stochastic inference.
99 :param device: Torch CPU or CUDA device.
100 """
101
102 def __init__(self, observation_space, action_space, *, config=None, seed=0, device="cpu"):
103 super().__init__(observation_space, action_space, config=config, seed=seed, device=device)
104
105 @staticmethod
106 def _output_size(actions):
107 return 2 * prod(actions.shape)
108
109 def _normalized(self, observations):
110 mean, _ = self._network(observations).chunk(2, dim=-1)
111 return mean.tanh()
112
113 def _sample_actions(self, observations, generator):
114 """Return reparameterized normalized actions and their joint log density."""
115 mean, scale = self._network(observations).chunk(2, dim=-1)
116 scale = F.softplus(scale) + 0.001
117 noise = torch.randn(mean.shape, generator=generator, dtype=mean.dtype, device=mean.device)
118 latent = mean + scale * noise
119 normal = -0.5 * (noise.square() + log(2 * pi)) - scale.log()
120 log_jacobian = 2 * (log(2.) - latent - F.softplus(-2 * latent))
121 return latent.tanh(), (normal - log_jacobian).sum(dim=-1)
122
123 @torch.no_grad()
124 def _draw(self, observation, deterministic, generator):
125 tensor = self._tensor(observation)
126 if deterministic:
127 normalized, log_prob = self._normalized(tensor), None
128 else:
129 normalized, log_prob = self._sample_actions(tensor, generator)
130 return self._decode(normalized.cpu().numpy()), normalized, log_prob
131
132
133 def save(self, path):
134 """Write the architecture, bounds, and weights to a versioned NPZ file."""
135 _save_actor(path, _actor_metadata(self, "sac", self._obs_shape), self._parameters())
136
137
138 @classmethod
139 def load(cls, path, *, device="cpu", seed=0):
140 """Load a SAC actor with a fresh stochastic inference generator."""
141 _, parameters, shape, actions, config = _load_actor_layout(path, "sac")
142 actor = cls._from_layout(shape, actions, config, seed, device, stochastic=False)
143 actor._set_parameters(parameters)
144 return actor
145
146
147
148@dataclass(frozen=True)
150 """Report cumulative updates and the current learned temperature.
151
152 Each SAC minibatch performs one reward-critic, one temperature, and one
153 actor optimizer step. Optimizer steps exclude target network averaging.
154 """
155
156 temperature_updates: int = 0
157 temperature: float = 1.0
158
159
160def _reward_target(rewards, terminated, values, log_prob, temperature, gamma):
161 return rewards + gamma * (values.min(dim=0).values - temperature * log_prob).masked_fill(terminated, 0.)
162
163
164def _twin_loss(values, target, ignore=None):
165 residual = values - target
166 if ignore is not None:
167 residual = residual.masked_fill(ignore, 0.)
168 return 0.5 * residual.square().mean()
169
170
172 """Own replay, optimizers and online and target reward networks."""
173
174 def __init__(self, actor, config, seed, counts, *, replay=None, entropy_per_action=-1.):
175 self.actor, self.config, self.counts = actor, config, counts
176 self.device = actor.device
177 seeds = np.random.SeedSequence(seed).spawn(4)
178 self.sample_rng, noise_seed, first_seed, second_seed = map(np.random.default_rng, seeds)
179 self.noise_rng = torch.Generator(device=self.device).manual_seed(_seed(noise_seed))
180 action_size = prod(actor._actions.shape)
181 self.replay = (_Replay(config.replay_capacity, prod(actor._obs_shape), action_size)
182 if replay is None else replay)
183 self.critics = _twin_critics(actor, config, first_seed, second_seed)
184 self.critic_targets = deepcopy(self.critics).requires_grad_(False)
185 self.critic_optimizer = torch.optim.Adam(self.critics.parameters(), lr=config.critic_learning_rate)
186 self.actor_optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=config.actor_learning_rate)
187 self.log_temperature = torch.nn.Parameter(actor._tensor(log(config.initial_temperature)))
188 self.temperature_optimizer = torch.optim.Adam([self.log_temperature], lr=config.temperature_learning_rate)
189 self.target_entropy = (entropy_per_action * action_size if config.target_entropy is None
190 else config.target_entropy)
191
192 @property
193 def temperature(self):
194 return self.log_temperature.detach().exp()
195
196 def record(self, observation, action, reward, successor, terminated):
197 self.replay.add(observation, self.actor._encode(action), reward, successor, terminated)
198
199 def ready(self, env_steps):
200 return env_steps >= self.config.learning_starts and self.replay.size >= self.config.batch_size
201
202 def _update(self, loss, optimizer, name, parameters=None):
203 if not torch.isfinite(loss):
204 raise ValueError(f"Produced a nonfinite {name} loss.")
205 optimizer.zero_grad(set_to_none=True)
206 if parameters is None:
207 loss.backward()
208 else:
209 # Differentiate through the critics without writing their gradients.
210 for parameter, grad in zip(parameters, torch.autograd.grad(loss, parameters)):
211 parameter.grad = grad
212 _checked_step(optimizer)
213 self.counts[name + "_updates"] += 1
214 self.counts["optimizer_steps"] += 1
215
216 def _temperature_step(self, observations):
217 with torch.no_grad():
218 _, log_prob = self.actor._sample_actions(observations, self.noise_rng)
219 error = -log_prob - self.target_entropy
220 self._update((self.log_temperature.exp() * error).mean(), self.temperature_optimizer, "temperature")
221
222 def _reward_step(self, observations, actions, rewards, successors, terminated, ignore=None):
223 with torch.no_grad():
224 next_actions, log_prob = self.actor._sample_actions(successors, self.noise_rng)
225 values = self._values(self.critic_targets, successors, next_actions)
226 targets = _reward_target(rewards, terminated, values, log_prob, self.temperature, self.config.gamma)
227 values = self._values(self.critics, observations, actions)
228 self._update(_twin_loss(values, targets, ignore), self.critic_optimizer, "critic")
229 _polyak(self.critics, self.critic_targets, self.config.tau)
230
231 @staticmethod
232 def _values(networks, observations, actions):
233 return torch.stack([_critic(critic, observations, actions) for critic in networks])
234
235 def _batch(self):
236 return self.replay.sample(self.config.batch_size, self.sample_rng, self.device)
237
238 def update(self):
239 batch = self._batch()
240 observations = batch[0]
241 self._temperature_step(observations)
242 self._reward_step(*batch)
243 actions, log_prob = self.actor._sample_actions(observations, self.noise_rng)
244 values = self._values(self.critics, observations, actions).min(dim=0).values
245 self._update((self.temperature * log_prob - values).mean(),
246 self.actor_optimizer, "actor", self.actor._trainable_parameters())
247
248
249
250class SAC:
251 """Learn a stochastic Box actor from one Gymnasium environment at a time.
252
253 The standalone learner uses uniform actions for the first learning_starts
254 steps. Subsequent exploration samples the learned Gaussian. The reward
255 critic bootstraps time limits from their final observation. It never
256 bootstraps a termination.
257
258 :param env_factory: Callable creating fresh single Gymnasium environments.
259 :param policy: Actor architecture as a PolicyConfig.
260 :param config: Replay and optimizer settings as a SACConfig.
261 :param max_episode_steps: External horizon treated as a truncation.
262 :param seed: Nonnegative initialization, interaction, and replay seed.
263 :param device: Torch CPU or CUDA device.
264 """
265
266 _config_type = SACConfig
267 _stats_type = SACStats
268
269 def __init__(self, env_factory, *, policy=None, config=None, max_episode_steps=300, seed=0, device="cpu"):
270 if not callable(env_factory):
271 raise TypeError("env_factory must be callable.")
272 self._factory = env_factory
273 self._horizon = _integer(max_episode_steps, "max_episode_steps")
274 self.config = self._config_type() if config is None else config
275 if not isinstance(self.config, self._config_type):
276 raise TypeError(f"config must be a {self._config_type.__name__}.")
277 seeds = np.random.SeedSequence(_integer(seed, "seed", 0)).spawn(5)
278 self._reset_rng, self._exploration_rng, actor_rng, learner_rng, rollout_rng = map(np.random.default_rng, seeds)
279 with _open_environment(env_factory) as env:
280 self.policy = self._make_policy(env, policy, _seed(actor_rng), device)
281 self._rollout_rng = torch.Generator(device=self.policy.device).manual_seed(_seed(rollout_rng))
282 self._counts = Counter()
283 self._learner = self._make_learner(_seed(learner_rng))
284
285 def _make_policy(self, env, policy, seed, device):
286 return SACPolicy(env.observation_space, env.action_space, config=policy, seed=seed, device=device)
287
288 def _make_learner(self, seed):
289 return _SACLearner(self.policy, self.config, seed, self._counts)
290
291 @property
292 def stats(self):
293 """Return cumulative training costs and the current replay and temperature."""
294 temperature = self._learner.temperature.item()
295 if not isfinite(temperature) or temperature <= 0:
296 raise ValueError("The entropy temperature must stay finite and positive.")
297 return self._stats_type(**self._counts, replay_size=self._learner.replay.size, temperature=temperature)
298
299 def _start_episode(self):
300 return None
301
302 def _action(self, observation, context):
303 if self._counts["training_steps"] < self.config.learning_starts:
304 return self.policy._decode(self._exploration_rng.uniform(-1, 1, size=prod(self.policy._actions.shape)))
305 return self.policy._draw(observation, False, self._rollout_rng)[0]
306
307 def _feature(self, observation, action, info):
308 return None
309
310 def _record(self, observation, action, reward, successor, terminated, truncated, feature, context):
311 self._learner.record(observation, action, reward, successor, terminated)
312
313
314 def train(self, max_env_steps):
315 """Train in a fresh environment and return cumulative statistics."""
316 budget = _StepBudget(max_env_steps, self._counts)
317 with _open_environment(self._factory) as env:
318 _check_spaces(env, self.policy)
319 cursor = _Cursor(env, self.policy, self._horizon, self._reset_rng)
320 while budget.remaining:
321 if cursor.ended:
322 info = cursor.reset()
323 context = self._start_episode()
324 observation = cursor.observation
325 action = self._action(observation, context)
326 saved_action = action.copy()
327 feature = self._feature(observation, saved_action, info)
328 reward, terminated, truncated, info = cursor.step(action, budget, "training_steps")
329 self._record(observation, saved_action, reward, cursor.observation,
330 terminated, truncated, feature, context)
331 if self._learner.ready(self._counts["training_steps"]):
332 self._learner.update()
333 return self.stats
A bounded Box actor for evolutionary, on-policy, and deterministic control.
Definition policy.py:337
_normalized(self, observations)
Definition policy.py:384
_decode(self, normalized)
Definition policy.py:387
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
_from_layout(cls, obs_shape, actions, config, seed, device, **kwargs)
Definition policy.py:161
_tensor(self, observation)
Definition policy.py:187
Replay, network, optimizer, and entropy settings for Soft Actor-Critic.
Definition sac.py:23
float target_entropy
Definition sac.py:50
float initial_temperature
Definition sac.py:49
tuple critic_hidden_sizes
Definition sac.py:43
Portable bounded Gaussian actor with an observation-dependent mean and scale.
Definition sac.py:88
save(self, path)
Save a portable numeric actor without a simulator or optimizer.
Definition sac.py:133
_sample_actions(self, observations, generator)
Definition sac.py:113
load(cls, path, *, device="cpu", seed=0)
Restore the actor without constructing a learner or environment.
Definition sac.py:139
Cumulative SAC budget, replay, optimizer, and entropy statistics.
Definition sac.py:149
Train a reusable standalone Soft Actor-Critic policy.
Definition sac.py:250
_start_episode(self)
Definition sac.py:299
_action(self, observation, context)
Definition sac.py:302
_feature(self, observation, action, info)
Definition sac.py:307
_make_learner(self, seed)
Definition sac.py:288
train(self, max_env_steps)
Spend an additional environment-step budget, retaining replay and optimizers.
Definition sac.py:314
_make_policy(self, env, policy, seed, device)
Definition sac.py:285
_record(self, observation, action, reward, successor, terminated, truncated, feature, context)
Definition sac.py:310
stats(self)
Definition sac.py:292
_reward_step(self, observations, actions, rewards, successors, terminated, ignore=None)
Definition sac.py:222
_values(networks, observations, actions)
Definition sac.py:232
_update(self, loss, optimizer, name, parameters=None)
Definition sac.py:202
_temperature_step(self, observations)
Definition sac.py:216
Cumulative optimizer, offspring, and replay counts for off-policy learners.
Definition td3.py:76