QDpy
Loading...
Searching...
No Matches
td3.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Bounded continuous TD3 for a single Gymnasium environment."""
6
7from collections import Counter
8from copy import deepcopy
9from dataclasses import dataclass
10from math import prod
11
12import numpy as np
13import torch
14from torch import nn
15from torch.nn import functional as F
16
17from .policy import ContinuousPolicy, PolicyConfig, _integer, _mlp
18from .rollout import TrainingStats, _Cursor, _StepBudget, _check_spaces, _open_environment, _seed
19
20_get_total_norm = getattr(torch.nn.utils, "get_total_norm", None)
21
22
23
24@dataclass(frozen=True)
26 """Configure TD3 for standalone learning or PGA-MAP-Elites.
27
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.
42 """
43
44 replay_capacity: int = 100_000
45 batch_size: int = 128
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
50 gamma: float = 0.99
51 tau: float = 0.005
52 policy_delay: int = 2
53 exploration_noise: float = 0.1
54 target_noise: float = 0.2
55 noise_clip: float = 0.5
56
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))
61 object.__setattr__(self, "critic_hidden_sizes", PolicyConfig(self.critic_hidden_sizes).hidden_sizes)
62 if self.batch_size > self.replay_capacity:
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].")
72
73
74
75@dataclass(frozen=True)
77 """Extend environment-step statistics with replay-based update counts.
78
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.
85 """
86
87 critic_updates: int = 0
88 actor_updates: int = 0
89 policy_gradient_steps: int = 0
90 pg_offspring: int = 0
91 actor_injections: int = 0
92 replay_size: int = 0
93
94
95class _Replay:
96 """Store actual post-step observations independently of environment resets."""
97
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)
101 self.next_observations = np.empty_like(self.observations)
102 self.rewards = np.empty(capacity, dtype=np.float32)
103 self.terminated = np.empty(capacity, dtype=bool)
104 self.capacity = capacity
105 self.position = self.size = 0
106
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.")
110 i = self.position
111 self.observations[i] = observation
112 self.actions[i] = action
113 self.rewards[i] = reward
114 self.next_observations[i] = next_observation
115 self.terminated[i] = terminated
116 self.position = (i + 1) % self.capacity
117 self.size = min(self.size + 1, self.capacity)
118
119 def sample(self, count, rng, device):
120 return self.batch(rng.integers(self.size, size=count), device)
121
122 def batch(self, rows, device):
123 return tuple(torch.as_tensor(field[rows], device=device) for field in (
124 self.observations, self.actions, self.rewards, self.next_observations, self.terminated,
125 ))
126
127 def sample_observations(self, count, rng, device):
128 return torch.as_tensor(self.observations[rng.integers(self.size, size=count)], device=device)
129
130
131def _critic(network, observations, actions):
132 return network(torch.cat((observations, actions), dim=-1)).squeeze(-1)
133
134
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.)
138
139
140@torch.no_grad()
141def _polyak(online, target, tau):
142 for current, averaged in zip(online.parameters(), target.parameters()):
143 averaged.lerp_(current, tau)
144
145
146def _twin_critics(actor, config, first_seed, second_seed):
147 inputs = prod(actor._obs_shape) + prod(actor._actions.shape)
148 widths = PolicyConfig(config.critic_hidden_sizes)
149 return nn.ModuleList([
150 _mlp(inputs, 1, widths, _seed(rng), actor.device, nn.ReLU) for rng in (first_seed, second_seed)
151 ])
152
153
154@torch.no_grad()
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)
162
163
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.")
168 return loss
169
170
171def _checked_step(optimizer):
172 # Reject nonfinite gradients before the optimizer can write its state.
173 # The L2 norm also catches magnitudes that overflow float32 when squared.
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)
177 else:
178 _get_total_norm([p.grad for p in parameters if p.grad is not None], error_if_nonfinite=True)
179 optimizer.step()
180
181
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()
189 # Differentiate through Q1 to the actions while leaving critic
190 # parameters, gradients, and optimizer state untouched.
191 for parameter, grad in zip(parameters, torch.autograd.grad(loss, parameters)):
192 parameter.grad = grad
193 _checked_step(optimizer)
194
195
197 """Own the persistent replay, TD3 networks, and optimizer state."""
198
199 def __init__(self, actor, config, seed, counts, *, replay=None):
200 self.actor, self.config, self.counts = actor, config, counts
201 sample_seed, noise_seed, first_seed, second_seed = map(np.random.default_rng,
202 np.random.SeedSequence(seed).spawn(4))
203 self.sample_rng = sample_seed
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)
209 self.critic_targets = deepcopy(self.critics).requires_grad_(False)
210 self.critic_optimizer = torch.optim.Adam(self.critics.parameters(), lr=config.critic_learning_rate)
211 self.actor_optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=config.actor_learning_rate)
212
213 def record(self, observation, action, reward, next_observation, terminated):
214 self.replay.add(observation, self.actor._encode(action), reward, next_observation, terminated)
215
216 def ready(self, env_steps):
217 return env_steps >= self.config.learning_starts and self.replay.size >= self.config.batch_size
218
219 def _targets(self, actions, rewards, successors, terminated):
220 return _td3_targets(self.actor_target, self.critic_targets, self.config, self.noise_rng,
221 actions, rewards, successors, terminated)
222
223 def _improve(self, actor, optimizer, observations):
224 _step_actor(actor, optimizer, self.critics[0], observations)
225 self.counts["optimizer_steps"] += 1
226
227 def update(self):
228 config = self.config
229 batch = self.replay.sample(config.batch_size, self.sample_rng, self.actor.device)
230 observations, actions = batch[:2]
231 target = self._targets(*batch[1:])
232 loss = _critic_loss(self.critics, observations, actions, target)
233 self.critic_optimizer.zero_grad(set_to_none=True)
234 loss.backward()
235 _checked_step(self.critic_optimizer)
236 self.counts["critic_updates"] += 1
237 self.counts["optimizer_steps"] += 1
238
239 if self.counts["critic_updates"] % config.policy_delay == 0:
240 self._improve(self.actor, self.actor_optimizer, observations)
241 self.counts["actor_updates"] += 1
242 _polyak(self.actor._network, self.actor_target, config.tau)
243 _polyak(self.critics, self.critic_targets, config.tau)
244
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):
248 observations = self.replay.sample_observations(self.config.batch_size, self.sample_rng, actor.device)
249 self._improve(actor, optimizer, observations)
250 self.counts["policy_gradient_steps"] += 1
251
252
253
254class TD3:
255 """Train with Gaussian exploration and uniform experience replay.
256
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.
264 """
265
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.")
269 self._factory = env_factory
270 self._horizon = _integer(max_episode_steps, "max_episode_steps")
271 self.config = TD3Config() if config is None else config
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)
275 self._reset_rng, self._exploration_rng, actor_rng, learner_rng = map(np.random.default_rng, seeds)
276 with _open_environment(env_factory) as env:
277 self.policy = ContinuousPolicy(env.observation_space, env.action_space, config=policy,
278 seed=_seed(actor_rng), device=device)
279 self._counts = Counter()
280 self._learner = _TD3Learner(self.policy, self.config, _seed(learner_rng), self._counts)
281
282 @property
283 def stats(self):
284 """Return cumulative training costs and current replay size."""
285 return OffPolicyStats(**self._counts, replay_size=self._learner.replay.size)
286
287 def _action(self, observation):
288 size = prod(self.policy._actions.shape)
289 if self._counts["training_steps"] < self.config.learning_starts:
290 normalized = self._exploration_rng.uniform(-1, 1, size=size)
291 else:
292 with torch.no_grad():
293 mean = self.policy._normalized(self.policy._tensor(observation)).cpu().numpy()
294 normalized = mean + self._exploration_rng.normal(0, self.config.exploration_noise, size=size)
295 return self.policy._decode(np.clip(normalized, -1, 1))
296
297
298 def train(self, max_env_steps):
299 """Train in a fresh environment and return cumulative statistics."""
300 budget = _StepBudget(max_env_steps, self._counts)
301 with _open_environment(self._factory) as env:
302 _check_spaces(env, self.policy)
303 cursor = _Cursor(env, self.policy, self._horizon, self._reset_rng)
304 while budget.remaining:
305 if cursor.ended:
306 cursor.reset()
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)
312 if self._learner.ready(self._counts["training_steps"]):
313 self._learner.update()
314 return self.stats
A bounded Box actor for evolutionary, on-policy, and deterministic control.
Definition policy.py:337
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
Cumulative search costs and evaluated-candidate counts.
Definition rollout.py:51
Cumulative optimizer, offspring, and replay counts for off-policy learners.
Definition td3.py:76
Settings for the shared TD3 actor, critics, and replay buffer.
Definition td3.py:25
tuple critic_hidden_sizes
Definition td3.py:47
Train a deterministic Box policy using the twin delayed DDPG algorithm.
Definition td3.py:254
_action(self, observation)
Definition td3.py:287
train(self, max_env_steps)
Spend an additional environment-step budget, retaining replay and optimizers.
Definition td3.py:298
stats(self)
Definition td3.py:283
batch(self, rows, device)
Definition td3.py:122
_improve(self, actor, optimizer, observations)
Definition td3.py:223
_targets(self, actions, rewards, successors, terminated)
Definition td3.py:219