QDpy
Loading...
Searching...
No Matches
domino.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""On-policy DOMiNO using QDpy's synchronous PPO learner."""
6
7from collections import Counter
8from dataclasses import dataclass
9from functools import partial
10from math import isfinite, prod
11
12from gymnasium import spaces
13import numpy as np
14from scipy.special import expit
15
16from .policy import (CategoricalPolicy, ContinuousPolicy, _action_layout, _flatten_observation,
17 _integer, _observation_shape)
18from .ppo import PPOConfig, _Learner
19from .rollout import TrainingStats, _Cursor, _StepBudget, _evaluate_episode, _open_environment, _seed
20
21__all__ = ["DOMiNO", "DOMiNOEvaluation", "DOMiNOSkill"]
22
23
24
25@dataclass(frozen=True)
27 """Report average episode return, reward per step, and mean timestep features."""
28
29 skill: int
30 return_mean: float
31 reward_rate: float
32 occupancy: tuple[float, ...]
33 satisfies_floor: bool
34
35
36
37@dataclass(frozen=True)
39 """Policy scores and Euclidean distances in occupancy feature space."""
40
41 skills: tuple[DOMiNOSkill, ...]
42 reward_floor: float
43 distances: tuple[tuple[float, ...], ...]
44 steps: int
45
46 @property
47 def satisfaction(self):
48 """Return the fraction of latent policies meeting the evaluated floor."""
49 return sum(row.satisfies_floor for row in self.skills) / len(self.skills)
50
51
53 """Attach an episode's fixed latent to each observation seen by PPO."""
54
55 def __init__(self, env, horizon, seeds, latent):
56 super().__init__(env, None, horizon, seeds)
57 original_observation = self._observe
58 self._observe = lambda observation: np.concatenate((original_observation(observation), latent))
59
60
61def _occupancy_direction(means, observed, skill, contact_distance):
62 if not observed[skill]:
63 return np.zeros(means.shape[1])
64 others = np.flatnonzero(observed & (np.arange(len(means)) != skill))
65 if not len(others):
66 return np.zeros(means.shape[1])
67 differences = means[skill] - means[others]
68 distances = np.linalg.norm(differences, axis=1)
69 nearest = int(np.argmin(distances))
70 scale = 1. if contact_distance is None else 1. - (distances[nearest] / contact_distance) ** 3
71 return scale * differences[nearest]
72
73
74
75class DOMiNO:
76 """Synchronous PPO variant of Diversity Optimization Maintaining Near Optimality.
77
78 Use one latent policy for reward alone and learn the remaining
79 policies with occupancy rewards and a sigmoid-bounded multiplier.
80 This implementation estimates average occupancy and extrinsic
81 reward from on-policy rollout blocks and trains PPO on their mixed
82 reward. It uses a single mixed-reward value baseline.
83
84 Feature receives (observation, action, info) per transition. Its
85 vector may encode one-hot state features or continuous features.
86 Pass reward_floor to set a fixed average reward per step. Otherwise
87 the floor is optimality_ratio times the reference policy's running
88 average reward. Use a fixed floor for negative reward scales.
89 """
90
91 def __init__(self, env_factory, *, feature, feature_dimension, num_skills=4,
92 reward_floor=None, optimality_ratio=.9, mean_decay=.9, dual_rate=.05,
93 diversity_weight=1., contact_distance=None, max_episode_steps=200,
94 policy=None, config=None, seed=0, device="cpu"):
95 if not callable(env_factory) or not callable(feature):
96 raise TypeError("env_factory and feature must be callable.")
97 if reward_floor is not None and not isfinite(reward_floor):
98 raise ValueError("reward_floor must be finite.")
99 if not (0 <= optimality_ratio <= 1 and 0 <= mean_decay < 1 and 0 <= dual_rate < np.inf
100 and 0 <= diversity_weight < np.inf):
101 raise ValueError("Invalid optimality ratio, occupancy decay, dual rate, or diversity weight.")
102 if contact_distance is not None and not 0 < contact_distance < np.inf:
103 raise ValueError("contact_distance must be finite and positive.")
104 self.config = PPOConfig() if config is None else config
105 if not isinstance(self.config, PPOConfig):
106 raise TypeError("config must be a PPOConfig.")
107 self._factory, self._feature = env_factory, feature
108 self._horizon = _integer(max_episode_steps, "max_episode_steps")
109 self.num_skills = _integer(num_skills, "num_skills", 2)
110 self._feature_width = _integer(feature_dimension, "feature_dimension")
111 self._fixed_floor, self._ratio = reward_floor, optimality_ratio
112 self._decay, self._dual_rate = mean_decay, dual_rate
113 self._diversity_weight, self._contact_distance = diversity_weight, contact_distance
114 self._latents = np.eye(self.num_skills, dtype=np.float32)
115 self._means = np.zeros((self.num_skills, self._feature_width))
116 self._rates = np.zeros(self.num_skills)
117 self._observed = np.zeros(self.num_skills, dtype=bool)
118 self._logits = np.zeros(self.num_skills)
119 self._queue = []
120 self._counts = Counter()
121 streams = np.random.SeedSequence(_integer(seed, "seed", 0)).spawn(4)
122 self._rollout_rng, self._skill_rng, actor_rng, learner_rng = map(np.random.default_rng, streams)
123 with _open_environment(env_factory) as env:
124 self._obs_shape = _observation_shape(env.observation_space)
125 self._obs_width = prod(self._obs_shape)
126 augmented = spaces.Box(-np.inf, np.inf, (self._obs_width + self.num_skills,), dtype=np.float32)
127 options = dict(config=policy, seed=_seed(actor_rng), device=device)
128 if isinstance(env.action_space, spaces.Box):
129 actor = ContinuousPolicy(augmented, env.action_space, stochastic=True, **options)
130 else:
131 actor = CategoricalPolicy(augmented, env.action_space, **options)
132 self._actor = actor
133 self._learner = _Learner(actor, self.config, _seed(learner_rng))
134
135 @property
136 def stats(self):
137 """Return cumulative training interactions and optimiser steps."""
138 return TrainingStats(**self._counts)
139
140 @property
141 def multipliers(self):
142 """Return the extrinsic reward weights, with the reference fixed at one."""
143 return (1., *map(float, expit(self._logits[1:])))
144
145 @property
146 def reward_floor(self):
147 """Return the fixed floor or the current estimate from the reference policy."""
148 return float(self._ratio * self._rates[0] if self._fixed_floor is None else self._fixed_floor)
149
150 def _cursor(self, env, skill, rng):
151 if (_observation_shape(env.observation_space) != self._obs_shape
152 or _action_layout(env.action_space) != self._actor._actions):
153 raise ValueError("The environment factory changed its observation or action space.")
154 return _SkillCursor(env, self._horizon, rng, self._latents[skill])
155
156 def _measure(self, observation, action, info):
157 state = observation[:self._obs_width].reshape(self._obs_shape)
158 features = np.asarray(self._feature(state, action, info), dtype=float)
159 if features.shape != (self._feature_width,) or not np.isfinite(features).all():
160 raise ValueError("feature must return a finite vector of feature_dimension values.")
161 return features.copy()
162
163 def _rewards(self, skill, observations, actions, _successors, rewards, _ended, infos):
164 features = np.stack([self._measure(obs, action, info) for obs, action, info
165 in zip(observations, actions, infos)])
166 external = np.asarray(rewards, dtype=float)
167 direction = _occupancy_direction(self._means, self._observed, skill, self._contact_distance)
168 weight = 1. if skill == 0 else float(expit(self._logits[skill]))
169 mixed = (external if skill == 0 else
170 weight * external + (1. - weight) * self._diversity_weight * (features @ direction))
171 decay = self._decay if self._observed[skill] else 0.
172 self._means[skill] = decay * self._means[skill] + (1. - decay) * features.mean(axis=0)
173 self._rates[skill] = decay * self._rates[skill] + (1. - decay) * external.mean()
174 self._observed[skill] = True
175 if skill and (self._fixed_floor is not None or self._observed[0]):
176 gap = self.reward_floor - self._rates[skill]
177 step = self._dual_rate * weight * (1. - weight) * gap
178 self._logits[skill] = np.clip(self._logits[skill] + step, -30., 30.)
179 return mixed
180
181
182 def act(self, observation, skill, *, deterministic=True):
183 """Decode an action for the requested skill in the native Gymnasium space."""
184 skill = _integer(skill, "skill", 0)
185 if skill >= self.num_skills:
186 raise ValueError("skill must be smaller than num_skills.")
187 augmented = np.concatenate((_flatten_observation(observation, self._obs_shape), self._latents[skill]))
188 return self._actor.act(augmented, deterministic=deterministic)
189
190
191 def train(self, max_env_steps):
192 """Collect synchronous rollout blocks and return cumulative training costs."""
193 budget = _StepBudget(max_env_steps, self._counts)
194 with _open_environment(self._factory) as env:
195 while budget.remaining:
196 if not self._queue:
197 self._queue = list(self._skill_rng.permutation(self.num_skills))
198 skill = self._queue.pop(0)
199 cursor = self._cursor(env, skill, self._rollout_rng)
200 self._learner.update(cursor, budget, budget.remaining, reward_transform=partial(self._rewards, skill))
201 return self.stats
202
203
204 def evaluate(self, *, episodes_per_skill=4, seed=1337):
205 """Report return, features, and floor satisfaction without updating training."""
206 repetitions = _integer(episodes_per_skill, "episodes_per_skill")
207 seed = _integer(seed, "seed", 0)
208 count = Counter()
209 budget = _StepBudget(self._horizon * repetitions * self.num_skills, count)
210 results = []
211 with _open_environment(self._factory) as env:
212 for skill in range(self.num_skills):
213 cursor = self._cursor(env, skill, np.random.default_rng(seed))
214 observed, returns, rewards = [], [], []
215
216 def record(obs, action, reward, successor, terminated, truncated, info):
217 observed.append(self._measure(obs, action, info))
218
219 for _ in range(repetitions):
220 episode = _evaluate_episode(cursor, self._actor, budget, transition_info=record)
221 returns.append(episode.return_)
222 rewards.extend(episode.rewards)
223 results.append((float(np.mean(returns)), float(np.mean(rewards)),
224 tuple(map(float, np.mean(observed, axis=0)))))
225 floor = (self._ratio * results[0][1] if self._fixed_floor is None else self._fixed_floor)
226 skills = tuple(DOMiNOSkill(i, reward, rate, features, rate >= floor)
227 for i, (reward, rate, features) in enumerate(results))
228 points = np.asarray([record.occupancy for record in skills])
229 distances = np.linalg.norm(points[:, None] - points[None, :], axis=2)
230 return DOMiNOEvaluation(skills, float(floor), tuple(tuple(map(float, row)) for row in distances),
231 count["evaluation_steps"])
Compare all learned policies on independent complete evaluation episodes.
Definition domino.py:38
Held-out quality and occupancy of one latent policy.
Definition domino.py:26
Train a shared actor for distinct policies subject to a task reward floor.
Definition domino.py:75
act(self, observation, skill, *, deterministic=True)
Choose an action for one latent policy using the original observation.
Definition domino.py:182
_measure(self, observation, action, info)
Definition domino.py:156
_cursor(self, env, skill, rng)
Definition domino.py:150
evaluate(self, *, episodes_per_skill=4, seed=1337)
Audit deterministic policies under common, held-out reset seeds.
Definition domino.py:204
_rewards(self, skill, observations, actions, _successors, rewards, _ended, infos)
Definition domino.py:163
train(self, max_env_steps)
Continue all policies on an additional environment-step budget.
Definition domino.py:191
A categorical actor that can run independently of its training environment.
Definition policy.py:222
A bounded Box actor for evolutionary, on-policy, and deterministic control.
Definition policy.py:337
Sampling and minibatch settings for the clipped PPO update.
Definition ppo.py:21
Cumulative search costs and evaluated-candidate counts.
Definition rollout.py:51