5"""Continuous Soft Actor-Critic for caller-supplied Gymnasium environments."""
7from collections
import Counter
8from copy
import deepcopy
9from dataclasses
import dataclass
10from math
import isfinite, log, pi, prod
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
22@dataclass(frozen=True)
24 """Configure the actor, two reward critics, and learned entropy temperature.
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.
40 replay_capacity: int = 100_000
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
49 initial_temperature: float = 1.0
50 target_entropy: float |
None =
None
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))
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.")
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].")
68 raise ValueError(
"target_entropy must be finite and representable in float32.")
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)
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"]))
89 """Map fixed Box observations to continuous actions with a squashed Gaussian.
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.
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.
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)
106 def _output_size(actions):
107 return 2 * prod(actions.shape)
109 def _normalized(self, observations):
110 mean, _ = self.
_network(observations).chunk(2, dim=-1)
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)
124 def _draw(self, observation, deterministic, generator):
125 tensor = self.
_tensor(observation)
127 normalized, log_prob = self.
_normalized(tensor),
None
130 return self.
_decode(normalized.cpu().numpy()), normalized, log_prob
134 """Write the architecture, bounds, and weights to a versioned NPZ file."""
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)
148@dataclass(frozen=True)
150 """Report cumulative updates and the current learned temperature.
152 Each SAC minibatch performs one reward-critic, one temperature, and one
153 actor optimizer step. Optimizer steps exclude target network averaging.
156 temperature_updates: int = 0
157 temperature: float = 1.0
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.)
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()
172 """Own replay, optimizers and online and target reward networks."""
174 def __init__(self, actor, config, seed, counts, *, replay=None, entropy_per_action=-1.):
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)
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)))
189 self.
target_entropy = (entropy_per_action * action_size
if config.target_entropy
is None
190 else config.target_entropy)
193 def temperature(self):
196 def record(self, observation, action, reward, successor, terminated):
197 self.
replay.add(observation, self.
actor._encode(action), reward, successor, terminated)
199 def ready(self, env_steps):
200 return env_steps >= self.
config.learning_starts
and self.
replay.size >= self.
config.batch_size
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:
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
216 def _temperature_step(self, observations):
217 with torch.no_grad():
218 _, log_prob = self.
actor._sample_actions(observations, self.
noise_rng)
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)
226 targets = _reward_target(rewards, terminated, values, log_prob, self.
temperature, self.
config.gamma)
232 def _values(networks, observations, actions):
233 return torch.stack([_critic(critic, observations, actions)
for critic
in networks])
240 observations = batch[0]
243 actions, log_prob = self.
actor._sample_actions(observations, self.
noise_rng)
244 values = self.
_values(self.
critics, observations, actions).min(dim=0).values
251 """Learn a stochastic Box actor from one Gymnasium environment at a time.
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.
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.
266 _config_type = SACConfig
267 _stats_type = SACStats
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.")
273 self.
_horizon = _integer(max_episode_steps,
"max_episode_steps")
276 raise TypeError(f
"config must be a {self._config_type.__name__}.")
277 seeds = np.random.SeedSequence(_integer(seed,
"seed", 0)).spawn(5)
279 with _open_environment(env_factory)
as env:
281 self.
_rollout_rng = torch.Generator(device=self.
policy.device).manual_seed(_seed(rollout_rng))
285 def _make_policy(self, env, policy, seed, device):
286 return SACPolicy(env.observation_space, env.action_space, config=policy, seed=seed, device=device)
288 def _make_learner(self, seed):
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.")
299 def _start_episode(self):
302 def _action(self, observation, context):
303 if self.
_counts[
"training_steps"] < self.
config.learning_starts:
307 def _feature(self, observation, action, info):
310 def _record(self, observation, action, reward, successor, terminated, truncated, feature, context):
311 self.
_learner.record(observation, action, reward, successor, terminated)
315 """Train in a fresh environment and return cumulative statistics."""
317 with _open_environment(self.
_factory)
as env:
318 _check_spaces(env, self.
policy)
320 while budget.remaining:
322 info = cursor.reset()
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)
A bounded Box actor for evolutionary, on-policy, and deterministic control.
_normalized(self, observations)
_decode(self, normalized)
Architecture of the actor and, for PPO, the separate value network.
_from_layout(cls, obs_shape, actions, config, seed, device, **kwargs)
_tensor(self, observation)
Replay, network, optimizer, and entropy settings for Soft Actor-Critic.
float initial_temperature
tuple critic_hidden_sizes
Portable bounded Gaussian actor with an observation-dependent mean and scale.
save(self, path)
Save a portable numeric actor without a simulator or optimizer.
_sample_actions(self, observations, generator)
load(cls, path, *, device="cpu", seed=0)
Restore the actor without constructing a learner or environment.
Cumulative SAC budget, replay, optimizer, and entropy statistics.
Train a reusable standalone Soft Actor-Critic policy.
_action(self, observation, context)
_feature(self, observation, action, info)
_make_learner(self, seed)
train(self, max_env_steps)
Spend an additional environment-step budget, retaining replay and optimizers.
_make_policy(self, env, policy, seed, device)
_record(self, observation, action, reward, successor, terminated, truncated, feature, context)
_reward_step(self, observations, actions, rewards, successors, terminated, ignore=None)
_values(networks, observations, actions)
_update(self, loss, optimizer, name, parameters=None)
_temperature_step(self, observations)
Cumulative optimizer, offspring, and replay counts for off-policy learners.