50 """Single-environment variant of Lim et al.'s Reset-Free QD.
52 Each round refits the dynamics ensemble from actual transitions and
53 builds a fresh imagined repertoire from the current state. Only
54 candidates with a full imagined path inside the safety margin can
55 be transferred. Rank eligible niches by descriptor novelty relative
56 to the measured archive, then by quality and lower disagreement.
57 If search cannot transfer, predict the measured skills from the
58 current state and try the one that improves the final safety margin
59 most. Use the fallback controller during model warm-up and when there
60 is no viable recovery skill. Predictions are heuristics.
62 :param env_factory: Factory for a single continuing Gymnasium environment.
63 :param archive: Empty best-only Grid or CVTGrid with one maximized fitness.
64 :param safety_margin: Callback (observation) returning a finite signed distance
65 or score. Negative values mark unsafe states, zero lies on the boundary.
66 :param fallback_action: Callback (observation) returning a physical Box action
67 for warm-up or recovery. It should help return to a region with positive margin.
68 :param warmup_action: Optional action callback for collecting diverse initial
69 transitions inside the safe region. Defaults to fallback_action.
70 :param safety_buffer: Nonnegative minimum predicted margin at all skill steps.
71 :param skill_steps: Number of environment steps per completed skill.
72 :param kwargs: DynamicsAwareQD model, policy, fitness, descriptor, and seed
73 settings. Evaluation uses one continuous execution per transfer.
75 Open the search with a context manager or call close() after training.
76 Consecutive train calls share the same simulator and observation.
77 Terminated or truncated environments end the session.
80 def __init__(self, env_factory, archive, *, safety_margin, fallback_action, skill_steps,
81 safety_buffer=0., warmup_action=None, **kwargs):
82 if not callable(safety_margin)
or not callable(fallback_action):
83 raise TypeError(
"safety_margin and fallback_action must be callable.")
84 if warmup_action
is not None and not callable(warmup_action):
85 raise TypeError(
"warmup_action must be callable when supplied.")
86 self.
_buffer = float(safety_buffer)
88 raise ValueError(
"safety_buffer must be finite and nonnegative.")
90 self.
_warmup = fallback_action
if warmup_action
is None else warmup_action
96 super().__init__(env_factory, archive, max_episode_steps=skill_steps,
97 evaluation_episodes=1, max_transfers=1, **kwargs)
101 """Return an immutable snapshot of live and imagined interaction costs."""
105 """Allow the continuing session to be closed on context exit."""
107 raise RuntimeError(
"The reset-free search session is closed.")
110 def __exit__(self, exc_type, exc, traceback):
115 """Close the live environment once. Archived policies remain available."""
123 _check_spaces(env, self.
_actor)
125 self.
_counts[
"initial_resets"] += 1
128 def _margin(self, observation):
130 if not isfinite(value):
131 raise ValueError(
"safety_margin must return a finite scalar.")
134 def _predict(self, genome, state):
135 self.
_actor._set_parameters(genome)
137 self.
_counts[
"imagined_policies"] += 1
140 def _imagined_archive(self, state):
142 seen = {tuple(elite)
for elite
in self.
archive}
145 parents = tuple(imagined.values())
146 first, second = self.
_selection_rng.integers(len(parents), size=2)
147 genome = iso_line_dd(parents[first].genome, parents[second].genome,
152 genome = np.asarray(genome, dtype=np.float32)
157 dream, disagreement = self.
_predict(genome, state)
159 for obs
in dream.observations[1:])):
161 fitness, features, _ = self.
_score_dreams([(dream, disagreement)])
162 if (
not self.
archive.in_bounds(features, self.
archive.features_domain)
163 or not self.
archive.in_bounds((fitness,), self.
archive.fitness_domain)):
165 cell = self.
archive.index_grid(features)
166 incumbent = imagined.get(cell)
167 if incumbent
is None or (fitness, -disagreement) > (incumbent.fitness, -incumbent.disagreement):
168 imagined[cell] =
_ImaginedSkill(genome, fitness, features, disagreement)
171 def _choose(self, state):
175 occupied = np.asarray([tuple(self.
archive.get_ind_features(elite))
for elite
in self.
archive])
178 novelty = np.linalg.norm(occupied - skill.features, axis=1).min()
if occupied.size
else 0.
179 return novelty, skill.fitness, -skill.disagreement
181 return max(imagined.values(), key=rank).genome
183 def _recovery(self, state, margin):
186 dream, disagreement = self.
_predict(elite, state)
189 margins = tuple(self.
_margin(obs)
for obs
in dream.observations[1:])
190 if margin >= 0.
and min(margins) < self.
_buffer:
192 priority = margins[-1], -disagreement
193 if margins[-1] > margin
and (best
is None or priority > best[0]):
194 best = priority, elite
195 return None if best
is None else best[1]
197 def _advance(self, action, budget, phase):
198 observation = self.
_cursor.observation
199 reward, terminated, truncated, info = self.
_cursor.step(action, budget, phase)
200 successor = self.
_cursor.observation
201 self.
_observe(observation, action, reward, successor, terminated)
202 self.
_info = dict(info)
203 self.
_counts[
"environment_ended"] = terminated
or truncated
204 unsafe = self.
_margin(successor) < 0.
205 self.
_counts[
"unsafe_steps"] += int(unsafe)
206 return reward, unsafe
208 def _controller_step(self, controller, budget, *, recovery):
209 observation = self.
_cursor.observation.reshape(self.
_actor._obs_shape).copy()
210 action = np.asarray(controller(observation), dtype=self.
_actor._actions.dtype)
211 if not self.
_cursor.env.action_space.contains(action):
212 raise ValueError(
"The action callback must return a finite action inside the Box.")
213 self.
_counts[
"recovery_steps"] += int(recovery)
214 self.
_advance(action, budget,
"training_steps")
216 def _execute(self, genome, budget, *, recovery):
217 self.
_actor._set_parameters(genome)
218 shape = self.
_actor._obs_shape
219 observations = [self.
_cursor.observation]
220 initial_info = deepcopy(self.
_info)
if not recovery
else {}
221 actions, rewards = [], []
222 self.
_counts[
"candidate_attempts"] += int(
not recovery)
225 actions.append(action.copy())
226 self.
_counts[
"recovery_steps"] += int(recovery)
227 phase =
"training_steps" if recovery
else "evaluation_steps"
228 reward, unsafe = self.
_advance(action, budget, phase)
229 if self.
_cursor.ended
or (unsafe
and not recovery):
230 self.
_counts[
"rejected_transfers"] += int(
not recovery)
232 rewards.append(reward)
233 observations.append(self.
_cursor.observation)
235 episode =
Episode(np.stack(observations).reshape(-1, *shape), tuple(actions),
236 tuple(rewards), initial_info, deepcopy(self.
_info),
False,
True)
237 self.
_counts[
"evaluated_policies"] += 1
239 self.
_offer([episode],
"transfer", parameters=genome)
245 """Return cumulative statistics and leave the session open for the next call.
247 Reserve a full skill horizon before model-based selection. An
248 insufficient remainder stays unused. Warm-up and fallback actions
249 are recorded in transitions and training costs but have no archive
250 score. A failed step or callback closes the session and propagates.
253 raise RuntimeError(
"The reset-free search session is closed.")
258 while budget.remaining
and not self.
_cursor.ended:
259 state = self.
_cursor.observation
269 if budget.remaining < self.
_horizon:
272 genome = self.
_choose(state)
if margin >= 0.
else None
273 if genome
is not None:
274 self.
_execute(genome, budget, recovery=
False)
280 self.
_execute(recovery, budget, recovery=
True)
282 except BaseException: