104 """Run RefQD with continuous Box actions and replay-based variation.
106 Reuse a caller's empty Grid or CVTGrid as reporting geometry. The
107 training archive stores ranked heads according to their last measured
108 returns. Periodic refreshes replace selected measurements using the
109 current shared encoder. Use audit() to measure current performance.
111 :param env_factory: Callable returning a fresh single environment.
112 :param archive: Empty, parentless, best-only reporting geometry.
113 :param descriptor: Function of a completed episode returning descriptor coordinates.
114 :param policy: ContinuousPolicy configuration with at least one hidden layer.
115 :param td3: Optional TD3Config.
116 :param depth: Maximum decision heads in each cell.
117 :param refresh_top: Number of highest-ranked heads to reevaluate per occupied cell.
118 :param refresh_every: Number of generations between re-evaluations.
119 :param batch_size: Offspring per generation.
120 :param critic_steps: TD3 updates per eligible generation.
121 :param pg_steps: Updates for each gradient offspring.
122 :param pg_learning_rate: Adam step size for gradient offspring.
123 :param encoder_decay: Per-generation multiplier for the encoder learning rate.
124 :param max_episode_steps: Hard horizon for one evaluation.
125 :param seed: Local root random seed.
126 :param device: CPU or CUDA for policy and learner networks.
129 def __init__(self, env_factory, archive, *, descriptor, policy=None, td3=None, depth=4, refresh_top=1,
130 refresh_every=50, batch_size=8, critic_steps=16, pg_steps=4, pg_learning_rate=.001, encoder_decay=.995,
131 max_episode_steps=300, seed=0, device="cpu"):
132 _validate_grid(archive)
133 if archive.fitness_score_names
or archive.features_score_names
or (
134 archive.fitness_weights
is not None and archive.fitness_weights[0] <= 0):
135 raise ValueError(
"Use a maximizing grid with ordinary fitness and descriptors.")
136 if not callable(env_factory)
or not callable(descriptor):
137 raise TypeError(
"Supply environment and descriptor callables.")
138 self.
depth = _integer(depth,
"depth")
139 self.
refresh_top = _integer(refresh_top,
"refresh_top")
140 self.
refresh_every = _integer(refresh_every,
"refresh_every")
141 self.
batch_size = _integer(batch_size,
"batch_size", 2)
142 self.
critic_steps = _integer(critic_steps,
"critic_steps")
143 self.
pg_steps = _integer(pg_steps,
"pg_steps")
144 if not 0 < pg_learning_rate < np.inf:
145 raise ValueError(
"Use a finite positive policy-gradient step size.")
147 self.
_horizon = _integer(max_episode_steps,
"max_episode_steps")
149 raise ValueError(
"refresh_top must fit the archive depth, and encoder_decay must be in (0, 1].")
150 self.
_decay = encoder_decay
153 self.
_geometry._set_fitness_weights((1.,))
160 np.random.default_rng(s)
for s
in np.random.SeedSequence(seed).spawn(3))
162 if not isinstance(self.
td3, TD3Config):
163 raise TypeError(
"td3 must be a TD3Config.")
164 with _open_environment(env_factory)
as env:
166 config=policy, seed=_seed(self.
_selection), device=device)
167 if len(self.
_actor._network) == 1:
168 raise ValueError(
"RefQD requires at least one hidden layer for the shared encoder.")
170 encoder = tuple(self.
_actor._network[:-1].parameters())
171 head = tuple(self.
_actor._network[-1].parameters())
172 self.
_encoder_bytes = sum(p.numel() * p.element_size()
for p
in encoder)
174 self.
_learner.actor_optimizer = torch.optim.Adam(
175 [{
"params": encoder}, {
"params": head}], lr=self.
td3.actor_learning_rate)
179 """Snapshot training counters, including the TD3 updates."""
181 for field
in RefQDStats.__dataclass_fields__})
185 """Read an immutable snapshot of the ranked heads in occupied cells."""
186 return MappingProxyType({cell: tuple(front)
for cell, front
in self.
_cells.items()})
190 """Return the version shared by candidates in the current generation."""
195 """Count the encoder once and the stored float32 decision vectors."""
196 return self.
_encoder_bytes + sum(e.parameters.nbytes
for front
in self.
_cells.values()
for e
in front)
198 def _random_head(self):
200 radius = layer.in_features ** -0.5
201 return self.
_selection.uniform(-radius, radius, size=layer.weight.numel() + layer.bias.numel())
203 def _proposals(self):
204 pool = [entry.parameters
for front
in self.
_cells.values()
for entry
in front]
207 self.
_learner.actor_optimizer.param_groups[0][
"lr"] = (
209 before = self.
_learner.counts[
"actor_updates"]
213 proposals = [self.
_actor._parameters()[-len(pool[0]):]]
215 a, b = self.
_selection.integers(len(pool), size=2)
216 proposals.append(iso_line_dd(pool[a], pool[b], rng=self.
_selection))
220 proposals.append(self.
_candidate._parameters())
223 def _location(self, episode):
224 descriptor = tuple(map(float, self.
_descriptor(episode)))
225 fitness = episode.return_
226 if (len(descriptor) != len(self.
_geometry.features_domain)
or not all(map(isfinite, descriptor))
227 or not isfinite(fitness)):
228 raise ValueError(
"Expected finite fitness and one descriptor per grid axis.")
230 descriptor, self.
_geometry.features_domain):
232 return self.
_geometry.index_grid(descriptor), fitness, descriptor
234 def _measure(self, episode):
238 cell, fitness, descriptor = location
239 weights = np.frombuffer(self.
_candidate._parameters().tobytes(), dtype=np.float32)
242 def _refresh(self, cursor, budget):
244 for front
in self.
_cells.values():
246 self.
_candidate._set_parameters(entry.parameters)
248 phase=
"refresh_steps")
251 self.
_counts[
"refreshed_heads"] += 1
253 if measured
is not None:
254 _insert(staged, *measured, self.
depth)
255 self.
_cells = {cell: front
for cell, front
in staged.items()
if front}
261 """Return cumulative stats. A budget-cut refresh leaves the archive intact."""
263 with _open_environment(self.
_factory)
as env:
264 _check_spaces(env, self.
_actor)
267 while budget.remaining:
269 if not self.
_refresh(refresh, budget):
272 if not budget.remaining:
277 self.
_counts[
"candidate_attempts"] += 1
279 if episode
is not None:
280 self.
_counts[
"evaluated_policies"] += 1
282 if measured
is not None:
285 self.
_counts[
"generations"] += 1
291 """Reconstruct a policy that can be saved with ContinuousPolicy.save()."""
292 head = self.
_cells[cell][_integer(rank,
"rank", 0)].parameters
293 actor = self.
_actor._new(0, device)
294 actor._set_parameters(np.concatenate((self.
_actor._parameters()[:-len(head)], head)))
298 def audit(self, max_env_steps, *, seed=0):
299 """Return a fresh grid of measured results without changing training state."""
300 archive, counts = deepcopy(self.
_geometry), Counter()
302 candidate = _DecisionActor.borrow(self.
_actor)
304 with _open_environment(self.
_factory)
as env:
305 _check_spaces(env, self.
_actor)
306 cursor =
_Cursor(env, candidate, self.
_horizon, np.random.default_rng(seed))
307 for front
in self.
_cells.values():
309 candidate._set_parameters(head.parameters)
310 episode = _evaluate_episode(cursor, candidate, budget)
315 if location
is not None:
316 cell, fitness, descriptor = location
317 if archive.free >= 1
or archive.solutions[cell]:
319 fitness=
Fitness((fitness,), weights=(1.,))))
320 return RefQDAudit(archive, counts[
"evaluation_steps"], completed)