QDpy
Loading...
Searching...
No Matches
smerl.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Structured maximum-entropy RL with a discrete skill prior."""
7
8from collections import Counter
9from dataclasses import dataclass
10from math import fsum, isfinite, log, prod
11
12import numpy as np
13import torch
14from torch import nn
15from torch.nn import functional as F
16
17from qdpy.containers import Grid
18
19from .policy import PolicyConfig, _BoxLayout, _flatten_observation, _integer, _mlp, _observation_shape, _save_actor
20from .rollout import _Cursor, _StepBudget, _check_spaces, _evaluate_episode, _open_environment, _seed
21from .sac import SAC, SACConfig, SACPolicy, SACStats, _SACLearner, _actor_metadata, _load_actor_layout
22from .td3 import _Replay
23
24__all__ = ["SMERL", "SMERLConfig", "SMERLStats", "SMERLPolicy", "DiscoveredSkill",
25 "SkillDiscoveryAudit", "evaluate_discovered_skills"]
26
27
28
29@dataclass(frozen=True)
31 """Train a skill-conditioned SAC actor with a uniform categorical prior.
32
33 :param skills: Number of discoverable skills.
34 :param diversity_weight: Strength of the gated discriminator reward.
35 :param discriminator_hidden_sizes: Hidden widths of the skill discriminator.
36 :param discriminator_learning_rate: Adam rate for the discriminator.
37 """
38
39 skills: int = 8
40 diversity_weight: float = 1.
41 discriminator_hidden_sizes: tuple[int, ...] = (64, 64)
42 discriminator_learning_rate: float = 3e-4
43
44 def __post_init__(self):
45 super().__post_init__()
46 object.__setattr__(self, "skills", _integer(self.skills, "skills", 2))
47 widths = PolicyConfig(self.discriminator_hidden_sizes).hidden_sizes
48 object.__setattr__(self, "discriminator_hidden_sizes", widths)
49 limit = np.finfo(np.float32)
50 if not 0. <= self.diversity_weight <= limit.max:
51 raise ValueError("diversity_weight must be nonnegative and representable in float32.")
52 if not limit.tiny <= self.discriminator_learning_rate <= limit.max:
53 raise ValueError("discriminator_learning_rate must be positive and representable in float32.")
54
55
56
57@dataclass(frozen=True)
59 """Track completed and eligible episodes and discard counts for partial episode rows."""
60
61 completed_episodes: int = 0
62 eligible_episodes: int = 0
63 incomplete_episode_steps: int = 0
64 discriminator_updates: int = 0
65
66
67
69 """Use a fixed-shape Box observation and skill index to select a physical Box action."""
70
71 _kind = "smerl-categorical-skill"
72
73 def __init__(self, observation_space, action_space, skills, *, policy=None, seed=0, device="cpu"):
74 self._initialize(_observation_shape(observation_space), _BoxLayout.from_space(action_space),
75 skills, PolicyConfig() if policy is None else policy, seed, device)
76
77 def _initialize(self, shape, actions, skills, config, seed, device):
78 self._obs_shape, self._actions = shape, actions
79 self._skills = _integer(skills, "skills", 2)
80 self._actor = SACPolicy._from_layout((prod(shape) + self.num_skills,), actions, config,
81 seed, device, stochastic=False)
82
83 @property
84 def num_skills(self):
85 """Return the number of skill IDs."""
86 return self._skills
87
88 @property
89 def device(self):
90 """Return the Torch device of the actor."""
91 return self._actor.device
92
93 def _observation(self, observation):
94 return _flatten_observation(observation, self._obs_shape)
95
96 def _action(self, observation, skill, deterministic, generator):
97 inputs = np.zeros(len(observation) + self.num_skills, dtype=np.float32)
98 inputs[:len(observation)] = observation
99 inputs[len(observation) + skill] = 1.
100 return self._actor._draw(inputs, deterministic, generator)[0]
101
102
106 def act(self, observation, skill, deterministic=True):
107 """Return one physical action for a zero-based skill ID."""
108 skill = _integer(skill, "skill", 0)
109 if skill >= self.num_skills:
110 raise ValueError("Use a skill ID in range(num_skills).")
111 return self._action(self._observation(observation), skill, deterministic, self._actor._rng)
112
113
114 def save(self, path):
115 """Write a numeric policy artifact for inference."""
116 metadata = _actor_metadata(self._actor, self._kind, self._obs_shape)
117 metadata["skills"] = self.num_skills
118 _save_actor(path, metadata, self._actor._parameters())
119
120
121 @classmethod
122 def load(cls, path, *, device="cpu", seed=0):
123 """Restore the actor and a fresh inference random stream."""
124 metadata, parameters, shape, actions, config = _load_actor_layout(path, cls._kind)
125 actor = cls.__new__(cls)
126 actor._initialize(shape, actions, metadata["skills"], config, seed, device)
127 actor._actor._set_parameters(parameters)
128 return actor
129
130
132 """Retain raw task rewards and the episode's gate, skill, and true termination."""
133
134 def __init__(self, capacity, observations, actions):
135 super().__init__(capacity, observations, actions)
136 self.skills = np.empty(capacity, np.int64)
137 self.eligible = np.empty(capacity, bool)
138
139 def commit(self, transitions, skill, eligible):
140 for transition in transitions:
141 index = self.position
142 self.add(*transition)
143 self.skills[index], self.eligible[index] = skill, eligible
144
145 def batch(self, rows, device):
146 return (*super().batch(rows, device), torch.as_tensor(self.skills[rows], device=device),
147 torch.as_tensor(self.eligible[rows], device=device))
148
149
150def _gated_reward(reward, logits, labels, eligible, weight):
151 """Add the current discriminator bonus only on rows with an active gate."""
152 log_probability = logits.log_softmax(-1).gather(-1, labels[:, None]).squeeze(-1)
153 return reward + weight * torch.where(eligible, log_probability + log(logits.shape[-1]), 0.)
154
155
157 def __init__(self, policy, config, seed, counts):
158 actor = policy._actor
159 replay = _GatedReplay(config.replay_capacity, prod(policy._obs_shape), prod(policy._actions.shape))
160 base, discriminator = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
161 super().__init__(actor, config, _seed(base), counts, replay=replay)
162 widths = PolicyConfig(config.discriminator_hidden_sizes)
163 self.discriminator = _mlp(prod(policy._obs_shape), config.skills, widths,
164 _seed(discriminator), self.device, nn.ReLU)
165 self.discriminator_optimizer = torch.optim.Adam(self.discriminator.parameters(),
166 lr=config.discriminator_learning_rate)
167
168 def _batch(self):
169 obs, action, reward, successor, terminal, skills, eligible = super()._batch()
170 logits = self.discriminator(successor)
171 rewards = _gated_reward(reward, logits.detach(), skills, eligible, self.config.diversity_weight)
172 self._update(F.cross_entropy(logits, skills), self.discriminator_optimizer, "discriminator")
173 code = F.one_hot(skills, num_classes=self.config.skills).to(obs.dtype)
174 return torch.cat((obs, code), -1), action, rewards, torch.cat((successor, code), -1), terminal
175
176
177
178class SMERL(SAC):
179 """Train SAC with task reward and a gated discriminator bonus.
180
181 Sample one skill uniformly per episode. Open the gate for all of
182 its transitions if its undiscounted task return meets return_threshold.
183 The discriminator classifies successor observations from every
184 completed episode. Recompute bonuses with its current parameters
185 when sampling replay. The archive and behavioural descriptors are
186 only used in held-out evaluation.
187
188 :param env_factory: Callable creating a single numeric Box/Box environment.
189 :param return_threshold: Minimum complete-episode task return for the bonus.
190 :param policy: Optional PolicyConfig for the actor.
191 :param config: Optional SMERLConfig.
192 :param max_episode_steps: External time limit for complete episodes.
193 :param seed: Private seed for initialization, skill draws and rollouts.
194 :param device: Torch CPU or CUDA device.
195 """
196
197 _config_type = SMERLConfig
198 _stats_type = SMERLStats
199
200 def __init__(self, env_factory, *, return_threshold, policy=None, config=None,
201 max_episode_steps=300, seed=0, device="cpu"):
202 if not isfinite(return_threshold):
203 raise ValueError("Use a finite return_threshold.")
204 self._threshold = float(return_threshold)
205 self._skill_rng = np.random.default_rng(np.random.SeedSequence(_integer(seed, "seed", 0), spawn_key=(5,)))
206 self._pending = []
207 super().__init__(env_factory, policy=policy, config=config, max_episode_steps=max_episode_steps,
208 seed=seed, device=device)
209
210 def _make_policy(self, env, policy, seed, device):
211 return SMERLPolicy(env.observation_space, env.action_space, self.config.skills,
212 policy=policy, seed=seed, device=device)
213
214 def _make_learner(self, seed):
215 return _SMERLLearner(self.policy, self.config, seed, self._counts)
216
217 def _start_episode(self):
218 return int(self._skill_rng.integers(self.policy.num_skills))
219
220 def _action(self, observation, context):
221 return self.policy._action(observation, context, False, self._rollout_rng)
222
223 def _record(self, observation, action, reward, successor, terminated, truncated, feature, context):
224 if abs(reward) > np.finfo(np.float32).max:
225 raise ValueError("Replay requires rewards representable in float32.")
226 encoded = self.policy._actor._encode(action)
227 self._pending.append((observation, encoded, reward, successor, terminated))
228 if terminated or truncated:
229 eligible = fsum(row[2] for row in self._pending) >= self._threshold
230 self._learner.replay.commit(self._pending, context, eligible)
231 self._pending.clear()
232 self._counts["completed_episodes"] += 1
233 self._counts["eligible_episodes"] += int(eligible)
234
235
236 def train(self, max_env_steps):
237 """Count partial episodes toward the budget and exclude them from replay."""
238 try:
239 super().train(max_env_steps)
240 finally:
241 self._counts["incomplete_episode_steps"] += len(self._pending)
242 self._pending.clear()
243 return self.stats
244
245
246
247@dataclass(frozen=True)
249 skill: int
250 return_: float
251 descriptor: tuple[float, ...] | None
252 episode_returns: tuple[float, ...]
253
254
255
256@dataclass(frozen=True)
258 skills: tuple[DiscoveredSkill, ...]
259 env_steps: int
260 mean_return: float
261 occupied_cells: int | None
262 archive_coverage: float | None
263 archive_qd_score: float | None
264
265
267 def __init__(self, policy, index):
268 self._obs_shape = policy._obs_shape
269 self._observation = policy._observation
270 self._policy, self._index = policy, index
271
272 def _greedy(self, observation):
273 return self._policy._action(observation, self._index, True, None)
274
275
276
286def evaluate_discovered_skills(env_factory, policy, *, descriptor=None, archive=None, episodes=1,
287 max_episode_steps=300, seed=0, qd_offset=0.):
288 """Score achieved descriptors independently of training and archive contents."""
289 if not callable(env_factory) or not isinstance(policy, SMERLPolicy):
290 raise TypeError("Supply an environment factory and a SMERLPolicy.")
291 if descriptor is not None and not callable(descriptor):
292 raise TypeError("descriptor must be callable.")
293 if archive is not None and (not isinstance(archive, Grid) or descriptor is None):
294 raise ValueError("An audit archive needs a Grid or CVTGrid and a descriptor callback.")
295 if not isfinite(qd_offset):
296 raise ValueError("qd_offset must be finite.")
297 episodes = _integer(episodes, "episodes")
298 horizon = _integer(max_episode_steps, "max_episode_steps")
299 seed = _integer(seed, "seed", 0)
300 counts = Counter()
301 budget = _StepBudget(episodes * horizon * policy.num_skills, counts)
302 rows, cells = [], {}
303 with _open_environment(env_factory) as env:
304 _check_spaces(env, policy)
305 for skill in range(policy.num_skills):
306 actor = _BoundSkill(policy, skill)
307 cursor = _Cursor(env, actor, horizon, np.random.default_rng(seed))
308 rollouts = [_evaluate_episode(cursor, actor, budget) for _ in range(episodes)]
309 returns = tuple(episode.return_ for episode in rollouts)
310 if not all(map(isfinite, returns)):
311 raise ValueError("Episode returns must be finite.")
312 quality = fsum(value / episodes for value in returns)
313 achieved = None
314 if descriptor is not None:
315 values = np.asarray([descriptor(episode) for episode in rollouts], dtype=float)
316 if values.ndim != 2 or not values.shape[1] or not np.isfinite(values).all():
317 raise ValueError("Return a finite descriptor vector of fixed length.")
318 achieved = tuple(map(float, (values / episodes).sum(0)))
319 rows.append(DiscoveredSkill(skill, quality, achieved, returns))
320 if archive is not None:
321 if len(achieved) != len(archive.features_domain):
322 raise ValueError("Descriptor length must match the audit archive.")
323 try:
324 cell = archive.index_grid(achieved)
325 except IndexError:
326 continue
327 cells[cell] = max(cells.get(cell, -float("inf")), quality)
328 return SkillDiscoveryAudit(tuple(rows), counts["evaluation_steps"], fsum(row.return_ / len(rows) for row in rows),
329 None if archive is None else len(cells),
330 None if archive is None else len(cells) / prod(archive.shape),
331 None if archive is None else fsum(quality + qd_offset for quality in cells.values()))
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
Replay, network, optimizer, and entropy settings for Soft Actor-Critic.
Definition sac.py:23
Cumulative SAC budget, replay, optimizer, and entropy statistics.
Definition sac.py:149
Train a reusable standalone Soft Actor-Critic policy.
Definition sac.py:250
stats(self)
Definition sac.py:292
_update(self, loss, optimizer, name, parameters=None)
Definition sac.py:202
Held-out return and behaviour of a discovered skill ID.
Definition smerl.py:248
Configure SAC and the categorical skill discriminator.
Definition smerl.py:30
tuple discriminator_hidden_sizes
Definition smerl.py:41
float discriminator_learning_rate
Definition smerl.py:42
A portable continuous-action actor with a discrete skill input.
Definition smerl.py:68
save(self, path)
Export the skill-conditioned actor without replay or a discriminator.
Definition smerl.py:114
load(cls, path, *, device="cpu", seed=0)
Load a policy independently of training and environment setup.
Definition smerl.py:122
act(self, observation, skill, deterministic=True)
Infer an action at a given discovered skill.
Definition smerl.py:106
_observation(self, observation)
Definition smerl.py:93
_action(self, observation, skill, deterministic, generator)
Definition smerl.py:96
_initialize(self, shape, actions, skills, config, seed, device)
Definition smerl.py:77
Report real steps, complete episodes, and return-gate outcomes.
Definition smerl.py:58
Learn discrete latent skills with episode-return gating.
Definition smerl.py:178
train(self, max_env_steps)
Collect at most max_env_steps interactions on a fresh environment.
Definition smerl.py:236
Report achieved behaviours and optional archive metrics on independent episodes.
Definition smerl.py:257
add(self, observation, action, reward, next_observation, terminated)
Definition td3.py:107