QDpy
Loading...
Searching...
No Matches
rollout.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Shared synchronous environment interaction for PPO, TD3, and neural QD."""
6
7from contextlib import contextmanager
8from copy import deepcopy
9from dataclasses import dataclass
10from math import isfinite
11
12from gymnasium.vector import VectorEnv
13import numpy as np
14
15from .policy import _action_layout, _flatten_observation, _integer, _observation_shape
16
17
18
19@dataclass(frozen=True)
20class Episode:
21 """One episode with its initial observation and the actual final observation.
22
23 Observations have shape ``(steps + 1, *observation_shape)``. Actions
24 and rewards have one entry per environment step. The two info mappings
25 are independent copies of the reset and last step info. Use values
26 that support ``copy.deepcopy`` in these mappings. A budget-cut
27 episode is never reported as a completed evaluation.
28 """
29
30 observations: np.ndarray
31 actions: tuple
32 rewards: tuple[float, ...]
33 initial_info: dict
34 final_info: dict
35 terminated: bool
36 truncated: bool
37
38 @property
39 def steps(self):
40 """Return the number of environment steps in the episode."""
41 return len(self.rewards)
42
43 @property
44 def return_(self):
45 """Return the undiscounted sum of rewards."""
46 return sum(self.rewards)
47
48
49
50@dataclass(frozen=True)
52 """Report search interactions as separate training and archive evaluation costs.
53
54 :param training_steps: Environment steps collected for standalone training or PPO variation.
55 :param evaluation_steps: Steps used to score candidates for the live archive.
56 :param optimizer_steps: Total optimizer steps across all networks.
57 :param candidate_attempts: Candidates started, including partial evaluations.
58 :param evaluated_policies: Candidates with all requested episodes complete.
59 :param archive_updates: Insertions and replacements reported by QDpy.
60 :param out_of_domain: Completed candidates outside the archive bounds.
61 :param ppo_offspring: Candidates whose actors underwent PPO improvement.
62 """
63
64 training_steps: int = 0
65 evaluation_steps: int = 0
66 optimizer_steps: int = 0
67 candidate_attempts: int = 0
68 evaluated_policies: int = 0
69 archive_updates: int = 0
70 out_of_domain: int = 0
71 ppo_offspring: int = 0
72
73 @property
74 def env_steps(self):
75 """Return the total number of calls to the search environment's step."""
76 return self.training_steps + self.evaluation_steps
77
78
80 """Charge each step at the call site, before advancing the simulator."""
81
82 def __init__(self, limit, counts):
83 self.remaining = _integer(limit, "max_env_steps")
84 self.counts = counts
85
86 def take(self, phase):
87 if self.remaining <= 0:
88 raise RuntimeError("The environment step budget is exhausted.")
89 self.remaining -= 1
90 self.counts[phase] += 1
91
92
93@contextmanager
94def _open_environment(factory):
95 env = factory()
96 try:
97 if isinstance(env, VectorEnv):
98 raise ValueError("Use a factory for a single Gymnasium environment.")
99 yield env
100 finally:
101 env.close()
102
103
104def _seed(rng):
105 return int(rng.integers(0, 2**32, dtype=np.uint64))
106
107
108def _check_spaces(env, policy):
109 if (_observation_shape(env.observation_space) != policy._obs_shape
110 or _action_layout(env.action_space) != policy._actions):
111 raise ValueError("The environment factory changed its observation or action space.")
112
113
115 """Keep the true successor observation until the caller explicitly resets."""
116
117 def __init__(self, env, policy, max_episode_steps, seeds):
118 self.env, self.seeds = env, seeds
119 if policy is None:
120 shape = _observation_shape(env.observation_space)
121 self._observe = lambda observation: _flatten_observation(observation, shape)
122 else:
123 self._observe = policy._observation
124 self.horizon = max_episode_steps
125 self.observation = None
126 self.ended = True
127
128 def reset(self, *, seed=None):
129 observation, info = self.env.reset(seed=_seed(self.seeds) if seed is None else seed)
130 self.observation = self._observe(observation)
131 self.episode_steps = 0
132 self.ended = False
133 return dict(info)
134
135 def step(self, action, budget, phase):
136 budget.take(phase)
137 observation, reward, terminated, truncated, info = self.env.step(action)
138 reward = float(reward)
139 if not isfinite(reward):
140 raise ValueError("The environment returned a nonfinite reward.")
141 terminated = bool(terminated)
142 truncated = bool(truncated)
143 if (terminated or truncated) and "final_observation" in info:
144 observation = info["final_observation"]
145 info = info.get("final_info", info)
146 self.observation = self._observe(observation)
147 self.episode_steps += 1
148 truncated = truncated or (not terminated and self.episode_steps == self.horizon)
149 self.ended = terminated or truncated
150 return reward, terminated, truncated, info
151
152
153def _evaluate_episode(cursor, actor, budget, on_transition=None, state_descriptor=None, *,
154 phase="evaluation_steps", transition_info=None):
155 """Score one deterministic policy, returning None for a budget-cut prefix."""
156 if not budget.remaining:
157 return None
158 current_info = cursor.reset()
159 initial_info = deepcopy(current_info)
160 observations = [cursor.observation]
161 actions, rewards = [], []
162 while budget.remaining:
163 state_data = ()
164 if state_descriptor is not None:
165 state_data = (state_descriptor(cursor.observation.reshape(actor._obs_shape), current_info),)
166 action = actor._greedy(cursor.observation)
167 actions.append(action.copy() if isinstance(action, np.ndarray) else action)
168 reward, terminated, truncated, info = cursor.step(action, budget, phase)
169 if on_transition is not None:
170 on_transition(observations[-1], actions[-1], reward, cursor.observation, terminated, *state_data)
171 if transition_info is not None:
172 transition_info(observations[-1].reshape(actor._obs_shape), actions[-1], reward,
173 cursor.observation.reshape(actor._obs_shape), terminated, truncated, info)
174 current_info = info
175 rewards.append(reward)
176 observations.append(cursor.observation)
177 if cursor.ended:
178 return Episode(np.stack(observations).reshape(len(observations), *actor._obs_shape),
179 tuple(actions), tuple(rewards), initial_info, deepcopy(dict(info)), terminated, truncated)
180 return None
Measurements from a completed evaluation episode.
Definition rollout.py:20
Cumulative search costs and evaluated-candidate counts.
Definition rollout.py:51