43 """Sample changing replay priorities in logarithmic time via a binary sum tree."""
45 def __init__(self, capacity, observations, actions, exponent):
46 super().__init__(capacity, observations, actions)
47 self.
_leaves = 1 << (capacity - 1).bit_length()
52 def _set(self, row, priority):
54 self.
_tree[i] = priority
59 def add(self, observation, action, reward, next_observation, terminated):
61 super().add(observation, action, reward, next_observation, terminated)
65 def draw(self, count, rng):
67 return rng.integers(self.
size, size=count)
68 indices = np.ones(count, dtype=np.intp)
69 values = rng.random(count) * self.
_tree[1]
70 while indices[0] < self.
_leaves:
72 left_sum = self.
_tree[left]
73 right = values >= left_sum
74 values -= np.where(right, left_sum, 0.)
75 indices = left + right
78 def update_priorities(self, rows, errors):
82 for row, value
in zip(rows, errors):
83 priority = (float(value) + 1e-6) ** self.
exponent
84 grouped[row] = max(priority, grouped.get(row, 0.))
85 for row, priority
in grouped.items():
87 self.
_set(row, priority)
102 """Reuse the SAC policy and entropy updates with an online categorical critic."""
104 def __init__(self, actor, config, seed, counts, support, priority_exponent):
106 self.
device = actor.device
109 observations, actions = prod(actor._obs_shape), prod(actor._actions.shape)
111 self.
support = actor._tensor(support)
112 self.
critic = _make_critic(observations, actions, config.critic_hidden_sizes, len(support),
115 self.
actor_optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=config.actor_learning_rate)
116 self.
log_temperature = nn.Parameter(actor._tensor(log(config.initial_temperature)))
118 self.
target_entropy = -actions
if config.target_entropy
is None else config.target_entropy
120 def _actor_loss(self, actor, observations):
121 actions, log_prob = actor._sample_actions(observations, self.
noise_rng)
122 inputs = torch.cat((observations, actions), dim=-1)
124 return (self.
temperature * log_prob - values).mean()
128 observations, actions, rewards, successors, terminated = self.
replay.batch(rows, self.
device)
129 with torch.no_grad():
130 next_actions, _ = self.
actor._sample_actions(successors, self.
noise_rng)
131 pair = torch.cat((torch.cat((observations, actions), dim=-1),
132 torch.cat((successors, next_actions), dim=-1)), dim=0)
134 current, successor = self.
critic(pair).chunk(2)
135 projected = _project_categorical(successor.detach().softmax(dim=-1), rewards, terminated,
137 log_probs = current.log_softmax(dim=-1)
139 with torch.no_grad():
140 errors = ((projected - log_probs.exp()) @ self.
support).abs().cpu().numpy()
141 self.
replay.update_priorities(rows, errors)
145 "actor", self.
actor._trainable_parameters())
147 def improve_offspring(self, actor, steps, learning_rate):
149 optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=learning_rate)
150 for _
in range(steps):
153 if not torch.isfinite(loss):
154 raise ValueError(
"QDHUAC produced a nonfinite offspring loss.")
155 optimizer.zero_grad(set_to_none=
True)
156 parameters = actor._trainable_parameters()
157 for parameter, grad
in zip(parameters, torch.autograd.grad(loss, parameters)):
158 parameter.grad = grad
159 _checked_step(optimizer)
160 self.
counts[
"policy_gradient_steps"] += 1
161 self.
counts[
"optimizer_steps"] += 1
175 """Evolve a population of continuous policies using replay-based updates.
177 The same critic processes current and successor state-action pairs in
178 one batch. It bootstraps categorical returns from the detached
179 successor predictions, then uses its mean return in the SAC actor loss.
180 Replay priorities use errors in the expected return. Each generation
181 combines genetic mutation, policy gradients, and a shared actor
182 snapshot. Complete measured candidates compete by dominated novelty.
184 :param env_factory: Factory for a single Gymnasium Box environment.
185 :param descriptor: Callable mapping a complete Episode to a finite descriptor vector.
186 :param config: SACConfig for replay, entropy, and network settings.
187 :param policy: PolicyConfig for the Gaussian actors.
188 :param return_bounds: Finite lower and upper values of the categorical support.
189 :param atoms: Number of support values.
190 :param updates_per_transition: Critic updates per recorded step after warm-up.
191 :param priority_exponent: Prioritized replay exponent. Zero gives uniform replay.
192 :param population_size: Maximum number of measured DNS survivors.
193 :param batch_size: Number of rollouts contributing to a population update.
194 :param novelty_neighbors: Number of fitter neighbors for dominated novelty.
195 :param gradient_steps: Learner updates on each gradient offspring.
196 :param iso_sigma: Independent Gaussian variation scale.
197 :param line_sigma: Shared Iso+LineDD direction scale.
198 :param max_episode_steps: Per-episode cap, treated as truncation.
199 :param seed: Seed for actor initialization, rollouts, replay, and variation.
200 :param device: CPU or CUDA.
203 def __init__(self, env_factory, *, descriptor, config=None, policy=None, return_bounds=(-50., 50.),
204 atoms=51, updates_per_transition=4, priority_exponent=.6, population_size=64,
205 batch_size=8, novelty_neighbors=5, gradient_steps=4, iso_sigma=.025,
206 line_sigma=.2, max_episode_steps=300, seed=0, device=
"cpu"):
207 if not callable(env_factory)
or not callable(descriptor):
208 raise TypeError(
"env_factory and descriptor must be callable.")
209 config =
SACConfig()
if config
is None else config
210 if not isinstance(config, SACConfig):
211 raise TypeError(
"config must be a SACConfig.")
212 low, high = return_bounds
213 if (
not -np.finfo(np.float32).max / 2 <= low < high <= np.finfo(np.float32).max / 2
214 or not 0. <= priority_exponent <= 1.
215 or not 0 <= iso_sigma < np.inf
or not 0 <= line_sigma < np.inf):
216 raise ValueError(
"Use finite support and mutation scales and a priority exponent in [0, 1].")
217 support = np.linspace(low, high, _integer(atoms,
"atoms", 2), dtype=np.float32)
218 if np.any(np.diff(support) <= 0.):
219 raise ValueError(
"Categorical support atoms must be distinct in float32.")
222 self.
batch_size = _integer(batch_size,
"batch_size", 3)
226 self.
_horizon = _integer(max_episode_steps,
"max_episode_steps")
229 np.random.SeedSequence(_integer(seed,
"seed", 0)).spawn(2))
231 with _open_environment(env_factory)
as env:
233 learner_actor = self.
_actor._new(_seed(self.
_rng))
239 def _make_actor(self, env, config, device, seed):
240 return SACPolicy(env.observation_space, env.action_space, config=config, device=device, seed=seed)
242 def _make_learner(self, actor, config, support, priority_exponent):
247 """Return cumulative training cost and learner activity."""
248 temperature = getattr(self.
_learner,
"temperature",
None)
249 value = 0.
if temperature
is None else float(temperature)
250 if temperature
is not None and (
not isfinite(value)
or value <= 0.):
251 raise ValueError(
"The entropy temperature must stay finite and positive.")
256 """Return detached copies of measured policies for reporting or export."""
257 return tuple(
Individual(list(ind), fitness=
Fitness(ind.fitness.values, weights=(1.,)),
260 def _record(self, observation, action, reward, successor, terminal):
261 self.
_learner.record(observation, action, reward, successor, terminal)
269 self.
_queue.extend((self.
_actor._new(_seed(self.
_rng))._parameters(),
"random")
272 self.
_queue.append((learner.actor._parameters(),
"injection"))
276 if i % 2 == 1
and self.
_counts[
"critic_updates"]:
278 learner.improve_offspring(actor, self.
gradient_steps, learner.config.actor_learning_rate)
279 self.
_queue.append((actor._parameters(),
"gradient"))
283 self.
_queue.append((parameters,
"genetic"))
288 records.setdefault(tuple(individual), individual)
289 candidates = tuple(records.values())
290 quality = [ind.fitness.values[0]
for ind
in candidates]
291 features = [ind.features.values
for ind
in candidates]
294 retained = {id(individual)
for individual
in self.
_population}
295 self.
_population = tuple(candidates[i]
for i
in order)
296 self.
_counts[
"archive_updates"] += sum(id(individual)
not in retained
for individual
in self.
_population)
298 self.
_counts[
"generations"] += 1
302 """Retain replay for a cut prefix and retry its candidate at the next call."""
304 with _open_environment(self.
_factory)
as env:
305 _check_spaces(env, self.
_actor)
307 while budget.remaining:
310 weights, operator = self.
_queue[0]
311 self.
_actor._set_parameters(weights)
312 self.
_counts[
"candidate_attempts"] += 1
313 before = budget.remaining
314 episode = _evaluate_episode(cursor, self.
_actor, budget, on_transition=self.
_record)
316 self.
_counts[
"prefix_steps"] += before - budget.remaining
318 features = np.asarray(self.
_descriptor(episode), dtype=float)
319 score = episode.return_
320 if (features.ndim != 1
or not len(features)
or not np.isfinite(features).all()
321 or not isfinite(score)
or self.
_descriptor_size not in (
None, len(features))):
322 raise ValueError(
"QDHUAC requires finite returns and a fixed finite descriptor vector.")
325 features=
Features(tuple(features))))
326 self.
_counts[
"evaluated_policies"] += 1
327 self.
_counts[
"pg_offspring"] += operator ==
"gradient"
328 self.
_counts[
"actor_injections"] += operator ==
"injection"
336 """The returned actor supports the standard numeric save/load interface."""
337 actor = self.
_actor._new(0, device)
338 actor._set_parameters(individual)
343 """Return an independent actor from the last completed generation."""
345 raise RuntimeError(
"Complete a generation before choosing its best policy.")