76 """Synchronous PPO variant of Diversity Optimization Maintaining Near Optimality.
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.
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.
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.")
105 if not isinstance(self.
config, PPOConfig):
106 raise TypeError(
"config must be a PPOConfig.")
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")
121 streams = np.random.SeedSequence(_integer(seed,
"seed", 0)).spawn(4)
123 with _open_environment(env_factory)
as env:
124 self.
_obs_shape = _observation_shape(env.observation_space)
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)
137 """Return cumulative training interactions and optimiser steps."""
142 """Return the extrinsic reward weights, with the reference fixed at one."""
143 return (1., *map(float, expit(self.
_logits[1:])))
147 """Return the fixed floor or the current estimate from the reference policy."""
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.")
156 def _measure(self, observation, action, info):
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()
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)
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))
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()
177 step = self.
_dual_rate * weight * (1. - weight) * gap
178 self.
_logits[skill] = np.clip(self.
_logits[skill] + step, -30., 30.)
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)
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)
192 """Collect synchronous rollout blocks and return cumulative training costs."""
194 with _open_environment(self.
_factory)
as env:
195 while budget.remaining:
198 skill = self.
_queue.pop(0)
200 self.
_learner.update(cursor, budget, budget.remaining, reward_transform=partial(self.
_rewards, skill))
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)
211 with _open_environment(self.
_factory)
as env:
213 cursor = self.
_cursor(env, skill, np.random.default_rng(seed))
214 observed, returns, rewards = [], [], []
216 def record(obs, action, reward, successor, terminated, truncated, info):
217 observed.append(self.
_measure(obs, action, info))
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)))))
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"])