5"""Bounded continuous TD3 for a single Gymnasium environment."""
7from collections
import Counter
8from copy
import deepcopy
9from dataclasses
import dataclass
17from .policy
import ContinuousPolicy, PolicyConfig, _integer, _mlp
18from .rollout
import TrainingStats, _Cursor, _StepBudget, _check_spaces, _open_environment, _seed
20_get_total_norm = getattr(torch.nn.utils,
"get_total_norm",
None)
24@dataclass(frozen=True)
26 """Configure TD3 for standalone learning or PGA-MAP-Elites.
28 :param replay_capacity: Maximum transitions kept in the FIFO replay ring.
29 :param batch_size: Uniform replay sample size, sampled with replacement.
30 :param learning_starts: Minimum transitions before the first critic update.
31 Standalone TD3 also uses this many uniformly random exploration steps.
32 :param critic_hidden_sizes: Hidden layer widths of each independent ReLU critic.
33 :param actor_learning_rate: Adam step size for the shared actor.
34 :param critic_learning_rate: Adam step size for the critics.
35 :param gamma: Reward discount in [0, 1].
36 :param tau: Fraction of online weights mixed into targets on delayed updates.
37 :param policy_delay: Critic updates between actor and Polyak updates.
38 :param exploration_noise: Gaussian standard deviation in normalized
39 action coordinates for standalone TD3.
40 :param target_noise: Standard deviation of TD3's normalized target noise.
41 :param noise_clip: Absolute per-coordinate limit for target smoothing noise.
44 replay_capacity: int = 100_000
46 learning_starts: int = 256
47 critic_hidden_sizes: tuple[int, ...] = (128, 128)
48 actor_learning_rate: float = 3e-4
49 critic_learning_rate: float = 3e-4
53 exploration_noise: float = 0.1
54 target_noise: float = 0.2
55 noise_clip: float = 0.5
57 def __post_init__(self):
58 for name
in (
"replay_capacity",
"batch_size",
"policy_delay"):
59 object.__setattr__(self, name, _integer(getattr(self, name), name))
60 object.__setattr__(self,
"learning_starts", _integer(self.
learning_starts,
"learning_starts", 0))
63 raise ValueError(
"batch_size must not exceed replay_capacity.")
64 for name
in (
"actor_learning_rate",
"critic_learning_rate"):
65 if not 0 < getattr(self, name) < float(
"inf"):
66 raise ValueError(f
"{name} must be finite and positive.")
67 for name
in (
"exploration_noise",
"target_noise",
"noise_clip"):
68 if not 0 <= getattr(self, name) < float(
"inf"):
69 raise ValueError(f
"{name} must be finite and nonnegative.")
70 if not 0 <= self.
gamma <= 1
or not 0 < self.
tau <= 1:
71 raise ValueError(
"gamma must be in [0, 1] and tau in (0, 1].")
75@dataclass(frozen=True)
77 """Extend environment-step statistics with replay-based update counts.
79 :param critic_updates: Joint twin-critic minibatch updates.
80 :param actor_updates: Delayed updates of the shared TD3 actor.
81 :param policy_gradient_steps: Adam steps taken on copies of archived actors.
82 :param pg_offspring: Candidates started using policy-gradient variation.
83 :param actor_injections: Shared greedy actor snapshots started as candidates.
84 :param replay_size: Number of transitions currently retained in the ring.
87 critic_updates: int = 0
88 actor_updates: int = 0
89 policy_gradient_steps: int = 0
91 actor_injections: int = 0
96 """Store actual post-step observations independently of environment resets."""
98 def __init__(self, capacity, observation_size, action_size):
99 self.
observations = np.empty((capacity, observation_size), dtype=np.float32)
100 self.
actions = np.empty((capacity, action_size), dtype=np.float32)
102 self.
rewards = np.empty(capacity, dtype=np.float32)
103 self.
terminated = np.empty(capacity, dtype=bool)
107 def add(self, observation, action, reward, next_observation, terminated):
108 if abs(reward) > np.finfo(np.float32).max:
109 raise ValueError(
"Replay requires rewards representable in float32.")
119 def sample(self, count, rng, device):
120 return self.
batch(rng.integers(self.
size, size=count), device)
122 def batch(self, rows, device):
123 return tuple(torch.as_tensor(field[rows], device=device)
for field
in (
127 def sample_observations(self, count, rng, device):
128 return torch.as_tensor(self.
observations[rng.integers(self.
size, size=count)], device=device)
131def _critic(network, observations, actions):
132 return network(torch.cat((observations, actions), dim=-1)).squeeze(-1)
135def _bellman_target(rewards, terminated, first, second, gamma):
136 """Use the lower target critic estimate and bootstrap only nonterminals."""
137 return rewards + gamma * torch.minimum(first, second).masked_fill(terminated, 0.)
141def _polyak(online, target, tau):
142 for current, averaged
in zip(online.parameters(), target.parameters()):
143 averaged.lerp_(current, tau)
146def _twin_critics(actor, config, first_seed, second_seed):
147 inputs = prod(actor._obs_shape) + prod(actor._actions.shape)
149 return nn.ModuleList([
150 _mlp(inputs, 1, widths, _seed(rng), actor.device, nn.ReLU)
for rng
in (first_seed, second_seed)
155def _td3_targets(actor_target, critic_targets, config, rng, actions, rewards, successors, terminated):
156 noise = torch.randn(actions.shape, device=actions.device, generator=rng, dtype=actions.dtype)
157 noise *= config.target_noise
158 next_actions = (actor_target(successors).tanh()
159 + noise.clamp(-config.noise_clip, config.noise_clip)).clamp(-1, 1)
160 first, second = (_critic(network, successors, next_actions)
for network
in critic_targets)
161 return _bellman_target(rewards, terminated, first, second, config.gamma)
164def _critic_loss(critics, observations, actions, target):
165 loss = sum(F.mse_loss(_critic(network, observations, actions), target)
for network
in critics)
166 if not torch.isfinite(loss):
167 raise ValueError(
"TD3 produced a nonfinite critic loss.")
171def _checked_step(optimizer):
174 parameters = [parameter
for group
in optimizer.param_groups
for parameter
in group[
"params"]]
175 if _get_total_norm
is None:
176 torch.nn.utils.clip_grad_norm_(parameters, float(
"inf"), error_if_nonfinite=
True)
178 _get_total_norm([p.grad
for p
in parameters
if p.grad
is not None], error_if_nonfinite=
True)
182def _step_actor(actor, optimizer, critic, observations, *, critic_observations=None):
183 if critic_observations
is None:
184 critic_observations = observations
185 loss = -_critic(critic, critic_observations, actor._normalized(observations)).mean()
186 if not torch.isfinite(loss):
187 raise ValueError(
"TD3 produced a nonfinite actor loss.")
188 parameters = actor._trainable_parameters()
191 for parameter, grad
in zip(parameters, torch.autograd.grad(loss, parameters)):
192 parameter.grad = grad
193 _checked_step(optimizer)
197 """Own the persistent replay, TD3 networks, and optimizer state."""
199 def __init__(self, actor, config, seed, counts, *, replay=None):
201 sample_seed, noise_seed, first_seed, second_seed = map(np.random.default_rng,
202 np.random.SeedSequence(seed).spawn(4))
204 self.
noise_rng = torch.Generator(device=actor.device).manual_seed(_seed(noise_seed))
205 obs_size, action_size = prod(actor._obs_shape), prod(actor._actions.shape)
206 self.
replay =
_Replay(config.replay_capacity, obs_size, action_size)
if replay
is None else replay
207 self.
critics = _twin_critics(actor, config, first_seed, second_seed)
208 self.
actor_target = deepcopy(actor._network).requires_grad_(
False)
211 self.
actor_optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=config.actor_learning_rate)
213 def record(self, observation, action, reward, next_observation, terminated):
214 self.
replay.add(observation, self.
actor._encode(action), reward, next_observation, terminated)
216 def ready(self, env_steps):
217 return env_steps >= self.
config.learning_starts
and self.
replay.size >= self.
config.batch_size
219 def _targets(self, actions, rewards, successors, terminated):
221 actions, rewards, successors, terminated)
223 def _improve(self, actor, optimizer, observations):
224 _step_actor(actor, optimizer, self.
critics[0], observations)
225 self.
counts[
"optimizer_steps"] += 1
230 observations, actions = batch[:2]
232 loss = _critic_loss(self.
critics, observations, actions, target)
236 self.
counts[
"critic_updates"] += 1
237 self.
counts[
"optimizer_steps"] += 1
239 if self.
counts[
"critic_updates"] % config.policy_delay == 0:
241 self.
counts[
"actor_updates"] += 1
245 def improve_offspring(self, actor, steps, learning_rate):
246 optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=learning_rate)
247 for _
in range(steps):
249 self.
_improve(actor, optimizer, observations)
250 self.
counts[
"policy_gradient_steps"] += 1
255 """Train with Gaussian exploration and uniform experience replay.
257 :param env_factory: Callable returning a fresh Gymnasium environment with
258 finite floating-point Box actions and fixed numeric Box observations.
259 :param policy: Actor architecture as a :class:`PolicyConfig`.
260 :param config: Replay and training settings as a :class:`TD3Config`.
261 :param max_episode_steps: External episode horizon, treated as truncation.
262 :param seed: Nonnegative seed for initial weights, rollouts, and replay.
263 :param device: Torch CPU or CUDA device.
266 def __init__(self, env_factory, *, policy=None, config=None, max_episode_steps=300, seed=0, device="cpu"):
267 if not callable(env_factory):
268 raise TypeError(
"env_factory must be callable.")
270 self.
_horizon = _integer(max_episode_steps,
"max_episode_steps")
272 if not isinstance(self.
config, TD3Config):
273 raise TypeError(
"config must be a TD3Config.")
274 seeds = np.random.SeedSequence(_integer(seed,
"seed", 0)).spawn(4)
276 with _open_environment(env_factory)
as env:
278 seed=_seed(actor_rng), device=device)
284 """Return cumulative training costs and current replay size."""
287 def _action(self, observation):
288 size = prod(self.
policy._actions.shape)
289 if self.
_counts[
"training_steps"] < self.
config.learning_starts:
292 with torch.no_grad():
293 mean = self.
policy._normalized(self.
policy._tensor(observation)).cpu().numpy()
295 return self.
policy._decode(np.clip(normalized, -1, 1))
299 """Train in a fresh environment and return cumulative statistics."""
301 with _open_environment(self.
_factory)
as env:
302 _check_spaces(env, self.
policy)
304 while budget.remaining:
307 observation = cursor.observation
308 action = self.
_action(observation)
309 saved_action = action.copy()
310 reward, terminated, _, _ = cursor.step(action, budget,
"training_steps")
311 self.
_learner.record(observation, saved_action, reward, cursor.observation, terminated)
A bounded Box actor for evolutionary, on-policy, and deterministic control.
Architecture of the actor and, for PPO, the separate value network.
Cumulative search costs and evaluated-candidate counts.
Cumulative optimizer, offspring, and replay counts for off-policy learners.
Settings for the shared TD3 actor, critics, and replay buffer.
tuple critic_hidden_sizes
Train a deterministic Box policy using the twin delayed DDPG algorithm.
_action(self, observation)
train(self, max_env_steps)
Spend an additional environment-step budget, retaining replay and optimizers.
batch(self, rows, device)
_improve(self, actor, optimizer, observations)
_targets(self, actions, rewards, successors, terminated)