78 """Own one actor, a task critic, and a trajectory descriptor baseline."""
80 def __init__(self, actor, config, context_width, descriptor_width, rng):
82 self.
value = _mlp(prod(actor._obs_shape), 1, actor.config, _seed(rng), actor.device)
83 self.
behavior = _mlp(context_width, descriptor_width, actor.config, _seed(rng), actor.device)
86 self.
rng = torch.Generator(device=actor.device).manual_seed(_seed(rng))
87 self.
reset_rng = np.random.default_rng(_seed(rng))
88 self.
quality = self.summary =
None
89 self.
steps = self.episodes = 0
92 def learn(self, rows, contexts, descriptors, mask, direction, counts):
94 states, successors, samples, old_logps, rewards, terminals, truncations = zip(*rows)
95 obs, next_obs = actor._tensor(np.stack(states)), actor._tensor(np.stack(successors))
96 actions, old_logps = torch.stack(samples), torch.stack(old_logps)
97 ctx = actor._tensor(np.asarray(contexts))
98 targets = actor._tensor(descriptors)
99 complete = torch.as_tensor(mask, dtype=torch.bool, device=actor.device)
100 direction = actor._tensor(direction)
101 with torch.no_grad():
102 values = self.
value(obs).flatten()
103 task_advantage = _advantages(actor._tensor(rewards), values, self.
value(next_obs).flatten(),
104 torch.as_tensor(terminals, device=actor.device),
105 torch.as_tensor(truncations, device=actor.device),
106 config.gamma, config.gae_lambda)
107 returns = task_advantage + values
111 task_advantage = (task_advantage - task_advantage.mean()) / (task_advantage.std(unbiased=
False) + 1e-8)
112 behavior_advantage = ((targets - self.
behavior(ctx)) @ direction).masked_fill(~complete, 0.)
113 advantage = task_advantage + self.
weight * behavior_advantage
115 for _
in range(config.epochs):
116 order = torch.randperm(len(rows), generator=self.
rng, device=actor.device)
117 for batch
in order.split(config.batch_size):
118 logps, entropy = actor._ppo_statistics(obs[batch], actions[batch], self.
rng)
119 policy_loss = _surrogate_loss(logps, old_logps[batch], advantage[batch], config.clip_ratio)
120 value_loss = .5 * (self.
value(obs[batch]).flatten() - returns[batch]).square().mean()
121 valid = batch[complete[batch]]
123 value_loss = value_loss + .5 * (self.
behavior(ctx[valid]) - targets[valid]).square().mean()
124 loss = policy_loss + config.value_coef * value_loss - config.entropy_coef * entropy.mean()
125 if not torch.isfinite(loss):
126 raise ValueError(
"QSD-PBT produced a nonfinite loss.")
127 self.
optimizer.zero_grad(set_to_none=
True)
129 torch.nn.utils.clip_grad_norm_(self.
parameters, config.max_grad_norm, error_if_nonfinite=
True)
131 counts[
"optimizer_steps"] += 1
136 """Synchronous PPO variant of Quality-Similar Diversity with independent actors.
138 :param env_factory: Return a fresh single Gymnasium environment with Discrete or MultiDiscrete actions.
139 :param descriptor: Read a complete Episode and return a fixed finite descriptor vector.
140 :param descriptor_size: Number of descriptor coordinates.
141 :param population_size: Number of independent policies and critics.
142 :param ppo: PPOConfig for task advantages, minibatches, and learning rate.
143 Its rollout length must cover max_episode_steps.
144 :param policy: PolicyConfig for portable actors and the critic networks.
145 :param initial_weight: Starting strength of the diversity advantage.
146 :param decay_steps: Weight decay timescale in per-policy training steps.
147 :param quality_offset: Add this constant to observed episode returns in the
148 adaptive schedule. Choose an offset giving nonnegative adjusted quality.
149 :param ema: Moving average rate for measured episode return and descriptors.
150 :param history: Optional callback (observation, past_actions, past_rewards) returning
151 a finite descriptor-critic context with history_size entries. Omit it
152 to use the flattened state and normalized episode time.
153 :param history_size: Context width when a custom history callback is supplied.
154 :param max_episode_steps: Maximum duration of a complete episode.
155 :param seed: Independent actor, optimizer, and reset streams.
156 :param device: Torch device.
159 def __init__(self, env_factory, *, descriptor, descriptor_size, population_size=4, ppo=None,
160 policy=None, initial_weight=1., decay_steps=10_000, quality_offset=0.,
161 ema=.1, history=None, history_size=None, max_episode_steps=128, seed=0, device="cpu"):
162 if not callable(env_factory)
or not callable(descriptor):
163 raise TypeError(
"Provide an environment factory and an episode descriptor.")
164 if (history
is None) != (history_size
is None)
or (history
is not None and not callable(history)):
165 raise ValueError(
"Provide history and history_size together.")
166 if not (0. <= initial_weight < np.inf
and 0. < decay_steps < np.inf
167 and np.isfinite(quality_offset)
and 0. < ema <= 1.):
168 raise ValueError(
"Use finite weights, a positive decay timescale, and ema in (0, 1].")
170 self.
_width = _integer(descriptor_size,
"descriptor_size")
171 self.
_horizon = _integer(max_episode_steps,
"max_episode_steps")
172 size = _integer(population_size,
"population_size", 2)
175 raise ValueError(
"Use a PPOConfig with rollout_steps at least max_episode_steps.")
176 self.
_schedule = initial_weight, decay_steps, quality_offset
179 with _open_environment(env_factory)
as env:
180 if not isinstance(env.action_space, (spaces.Discrete, spaces.MultiDiscrete)):
181 raise ValueError(
"QSD-PBT requires a Discrete or MultiDiscrete action space.")
182 for stream
in np.random.SeedSequence(_integer(seed,
"seed", 0)).spawn(size):
183 rng = np.random.default_rng(stream)
184 actor =
CategoricalPolicy(env.observation_space, env.action_space, config=policy,
185 seed=_seed(rng), device=device)
186 self.
_context_width = (prod(actor._obs_shape) + 1
if history_size
is None
187 else _integer(history_size,
"history_size"))
189 agent.weight = initial_weight
194 """Return cumulative interactions and the current population estimates."""
196 completed_episodes=tuple(agent.episodes
for agent
in self.
_agents),
197 returns=tuple(agent.quality
for agent
in self.
_agents),
198 diversity_weights=tuple(agent.weight
for agent
in self.
_agents))
200 def _descriptor(self, episode):
201 vector = np.asarray(self.
_describe(episode), dtype=np.float32)
202 if vector.shape != (self.
_width,)
or not np.isfinite(vector).all():
203 raise ValueError(
"descriptor must return descriptor_size finite coordinates.")
206 def _context(self, observation, actions, rewards):
208 return np.r_[observation, len(actions) / self.
_horizon]
209 vector = np.asarray(self.
_history(observation, tuple(actions), tuple(rewards)), dtype=np.float32)
210 if vector.shape != (self.
_context_width,)
or not np.isfinite(vector).all():
211 raise ValueError(
"history must return history_size finite coordinates.")
214 def _collect(self, cursor, agent, count, budget, *, audit=False, deterministic=False, rng=None):
216 rows, contexts, episodes, ends = [], [], [], []
218 for _
in range(count):
220 if audit
and episodes:
222 initial = deepcopy(cursor.reset())
223 states, actions, rewards = [cursor.observation], [], []
224 observation = cursor.observation.reshape(actor._obs_shape)
225 if audit
and deterministic:
226 action = actor._greedy(cursor.observation)
228 action, sample, logp = actor._draw(cursor.observation,
False, agent.rng
if not audit
else rng)
230 contexts.append(self.
_context(observation.flatten()
if self.
_history is None else observation,
232 actions.append(action.copy()
if isinstance(action, np.ndarray)
else action)
233 phase =
"evaluation_steps" if audit
else "training_steps"
236 reward, terminal, truncated, info = cursor.step(action, budget, phase)
237 successors = cursor.observation
239 rows.append((states[-1], successors, sample, logp, reward, terminal, truncated))
240 states.append(successors)
241 rewards.append(reward)
243 episode =
Episode(np.stack(states).reshape(-1, *actor._obs_shape), tuple(actions), tuple(rewards),
244 initial, deepcopy(dict(info)), terminal, truncated)
245 episodes.append(episode)
246 ends.append((start, len(rows)))
251 targets = np.zeros((len(rows), self.
_width), dtype=np.float32)
252 mask = np.zeros(len(rows), dtype=bool)
253 for episode, (start, end)
in zip(episodes, ends):
255 quality = episode.return_
256 if not 0. <= quality + self.
_schedule[2] < np.inf:
257 raise ValueError(
"Use a quality_offset giving finite nonnegative adjusted episode returns.")
258 alpha = 1.
if agent.episodes == 0
else self.
_ema
259 agent.quality = quality
if agent.quality
is None else (1. - alpha) * agent.quality + alpha * quality
260 agent.summary = vector
if agent.summary
is None else (1. - alpha) * agent.summary + alpha * vector
262 targets[start:end] = vector
263 mask[start:end] =
True
264 return rows, contexts, targets, mask
266 def _update_population(self):
268 known = [index
for index, agent
in enumerate(self.
_agents)
if agent.episodes]
271 points = np.asarray([self.
_agents[index].summary
for index
in known], dtype=float)
272 directions[known] = _directions(points)
273 adjusted = [max(0., self.
_agents[index].quality + offset)
for index
in known]
275 for index, value
in zip(known, adjusted):
276 ratio = best / value
if value
else (np.inf
if best
else 1.)
278 agent.weight = initial * np.exp(-(agent.steps / scale) * ratio)
283 """Use balanced synchronous blocks. Episode prefixes train only the task critic and actor."""
286 with _open_environment(self.
_factory)
as env:
287 _check_spaces(env, self.
_agents[0].actor)
288 while budget.remaining:
289 count = min(budget.remaining, size * self.
_config.rollout_steps)
290 each, extra = divmod(count, size)
292 for position
in range(size):
293 index = (self.
_next + position) % size
295 steps = each + (position < extra)
298 batches.append((index, self.
_collect(cursor, agent, steps, budget)))
301 for index, batch
in batches:
302 self.
_agents[index].learn(*batch, directions[index], self.
_counts)
307 """Return one portable CategoricalPolicy per population member."""
308 rng = np.random.default_rng(_integer(seed,
"seed", 0))
311 actor = agent.actor._new(_seed(rng), device)
312 actor._set_parameters(agent.actor._parameters())
317 def evaluate(self, *, episodes_per_policy=8, seed=1337, deterministic=False):
318 """Evaluate complete episodes with independent reset and action streams."""
319 repetitions = _integer(episodes_per_policy,
"episodes_per_policy")
320 seed = _integer(seed,
"seed", 0)
323 returns, descriptors = [], []
324 with _open_environment(self.
_factory)
as env:
325 _check_spaces(env, self.
_agents[0].actor)
327 rng = torch.Generator(device=agent.actor.device).manual_seed(seed)
328 cursor =
_Cursor(env, agent.actor, self.
_horizon, np.random.default_rng(seed))
330 deterministic=deterministic, rng=rng)
331 for _
in range(repetitions)]
332 returns.append(float(np.mean([episode.return_
for episode
in episodes])))
333 descriptors.append(tuple(map(float, np.mean([self.
_descriptor(episode)
for episode
in episodes],
334 axis=0, dtype=float))))
335 return QSDPBTEvaluation(tuple(returns), tuple(descriptors), counts[
"evaluation_steps"])