QDpy
Loading...
Searching...
No Matches
reset_free_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Reset-Free QD with current-state imagination and learned-model recovery."""
7
8from contextlib import ExitStack
9from copy import deepcopy
10from dataclasses import dataclass
11from math import isfinite
12
13import numpy as np
14
15from qdpy.tools import iso_line_dd
16
17from .dynamics_aware import DynamicsAwareQD, DynamicsAwareQDStats
18from .rollout import Episode, _Cursor, _StepBudget, _check_spaces, _open_environment
19
20
21
22@dataclass(frozen=True)
24 """Cumulative counts for a single continuing session.
25
26 :param initial_resets: Calls to initialize the training environment, at most one.
27 :param unsafe_steps: Real steps whose successor has a negative safety margin.
28 :param recovery_steps: Real steps spent on recovery or the fallback action.
29 :param rejected_transfers: Selected skills cut short by safety or environment end.
30 :param environment_ended: Whether Gymnasium returned termination or truncation.
31 """
32
33 initial_resets: int = 0
34 unsafe_steps: int = 0
35 recovery_steps: int = 0
36 rejected_transfers: int = 0
37 environment_ended: bool = False
38
39
40@dataclass(frozen=True)
42 genome: np.ndarray
43 fitness: float
44 features: tuple
45 disagreement: float
46
47
48
50 """Single-environment variant of Lim et al.'s Reset-Free QD.
51
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.
61
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.
74
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.
78 """
79
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)
87 if not isfinite(self._buffer) or self._buffer < 0.:
88 raise ValueError("safety_buffer must be finite and nonnegative.")
89 self._margin_callback, self._fallback = safety_margin, fallback_action
90 self._warmup = fallback_action if warmup_action is None else warmup_action
91 self._session = ExitStack()
92 self._closed = False
93 self._cursor = None
94 self._info = {}
95 self._recovery_stalled = False
96 super().__init__(env_factory, archive, max_episode_steps=skill_steps,
97 evaluation_episodes=1, max_transfers=1, **kwargs)
98
99 @property
100 def stats(self):
101 """Return an immutable snapshot of live and imagined interaction costs."""
102 return ResetFreeQDStats(**self._counts)
103
104 def __enter__(self):
105 """Allow the continuing session to be closed on context exit."""
106 if self._closed:
107 raise RuntimeError("The reset-free search session is closed.")
108 return self
109
110 def __exit__(self, exc_type, exc, traceback):
111 self.close()
112
113
114 def close(self):
115 """Close the live environment once. Archived policies remain available."""
116 self._closed = True
117 self._cursor = None
118 self._info = {}
119 self._session.close()
120
121 def _start(self):
122 env = self._session.enter_context(_open_environment(self._factory))
123 _check_spaces(env, self._actor)
124 self._cursor = _Cursor(env, self._actor, np.inf, self._evaluation_rng)
125 self._counts["initial_resets"] += 1
126 self._info = self._cursor.reset()
127
128 def _margin(self, observation):
129 value = float(self._margin_callback(observation.reshape(self._actor._obs_shape).copy()))
130 if not isfinite(value):
131 raise ValueError("safety_margin must return a finite scalar.")
132 return value
133
134 def _predict(self, genome, state):
135 self._actor._set_parameters(genome)
136 result = self._dream_from(state.copy())
137 self._counts["imagined_policies"] += 1
138 return result
139
140 def _imagined_archive(self, state):
141 imagined = {}
142 seen = {tuple(elite) for elite in self.archive}
143 for _ in range(self._imagined):
144 if imagined:
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,
148 iso_sigma=self._iso_sigma, line_sigma=self._line_sigma,
149 rng=self._selection_rng)
150 else:
151 genome = self._genetic_parameters()
152 genome = np.asarray(genome, dtype=np.float32)
153 key = tuple(genome)
154 if key in seen:
155 continue
156 seen.add(key)
157 dream, disagreement = self._predict(genome, state)
158 if (dream.terminated or any(self._margin(obs) < self._buffer
159 for obs in dream.observations[1:])):
160 continue
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)):
164 continue
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)
169 return imagined
170
171 def _choose(self, state):
172 imagined = self._imagined_archive(state)
173 if not imagined:
174 return None
175 occupied = np.asarray([tuple(self.archive.get_ind_features(elite)) for elite in self.archive])
176
177 def rank(skill):
178 novelty = np.linalg.norm(occupied - skill.features, axis=1).min() if occupied.size else 0.
179 return novelty, skill.fitness, -skill.disagreement
180
181 return max(imagined.values(), key=rank).genome
182
183 def _recovery(self, state, margin):
184 best = None
185 for elite in self.archive:
186 dream, disagreement = self._predict(elite, state)
187 if dream.terminated:
188 continue
189 margins = tuple(self._margin(obs) for obs in dream.observations[1:])
190 if margin >= 0. and min(margins) < self._buffer:
191 continue
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]
196
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
207
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")
215
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)
223 for _ in range(self._horizon):
224 action = self._actor._greedy(self._cursor.observation)
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)
231 return
232 rewards.append(reward)
233 observations.append(self._cursor.observation)
234 if not recovery:
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
238 self._record_transfer("transfer")
239 self._offer([episode], "transfer", parameters=genome)
240 if self._on_step is not None:
241 self._on_step(self.archive, self.stats)
242
243
244 def train(self, max_env_steps):
245 """Return cumulative statistics and leave the session open for the next call.
246
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.
251 """
252 if self._closed:
253 raise RuntimeError("The reset-free search session is closed.")
254 budget = _StepBudget(max_env_steps, self._counts)
255 try:
256 if self._cursor is None:
257 self._start()
258 while budget.remaining and not self._cursor.ended:
259 state = self._cursor.observation
260 margin = self._margin(state)
261 if self._replay.size < self._min_model_steps:
262 controller = self._fallback if margin < 0. else self._warmup
263 self._controller_step(controller, budget, recovery=margin < 0.)
264 continue
265 if self._recovery_stalled:
266 self._controller_step(self._fallback, budget, recovery=True)
267 self._recovery_stalled = False
268 continue
269 if budget.remaining < self._horizon:
270 break
271 self._fit_dynamics()
272 genome = self._choose(state) if margin >= 0. else None
273 if genome is not None:
274 self._execute(genome, budget, recovery=False)
275 continue
276 recovery = self._recovery(state, margin)
277 if recovery is None:
278 self._controller_step(self._fallback, budget, recovery=True)
279 else:
280 self._execute(recovery, budget, recovery=True)
281 self._recovery_stalled = not self._cursor.ended and self._margin(self._cursor.observation) <= margin
282 except BaseException:
283 self.close()
284 raise
285 if self._cursor.ended:
286 self._session.close()
287 return self.stats
Distinguish model work from actual environment calls in Dynamics-Aware QD.
Discover policies with an imagined repertoire and verify them in the environment.
_observe(self, obs, action, reward, successor, terminated)
Report real safety outcomes, recovery work, and model work.
Build and screen an imagined repertoire from the live state before executing skills.
close(self)
Release the continuing environment and end this search session.
train(self, max_env_steps)
Advance the continuing environment by at most the additional step budget.
_advance(self, action, budget, phase)
_controller_step(self, controller, budget, *, recovery)
_execute(self, genome, budget, *, recovery)
Measurements from a completed evaluation episode.
Definition rollout.py:20
_offer(self, episodes, emitter, *, descriptors=None, quality=None, parameters=None, candidate_id=None)
Definition search.py:119