6"""Structured maximum-entropy RL with a discrete skill prior."""
8from collections
import Counter
9from dataclasses
import dataclass
10from math
import fsum, isfinite, log, prod
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
24__all__ = [
"SMERL",
"SMERLConfig",
"SMERLStats",
"SMERLPolicy",
"DiscoveredSkill",
25 "SkillDiscoveryAudit",
"evaluate_discovered_skills"]
29@dataclass(frozen=True)
31 """Train a skill-conditioned SAC actor with a uniform categorical prior.
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.
40 diversity_weight: float = 1.
41 discriminator_hidden_sizes: tuple[int, ...] = (64, 64)
42 discriminator_learning_rate: float = 3e-4
44 def __post_init__(self):
45 super().__post_init__()
46 object.__setattr__(self,
"skills", _integer(self.
skills,
"skills", 2))
48 object.__setattr__(self,
"discriminator_hidden_sizes", widths)
49 limit = np.finfo(np.float32)
51 raise ValueError(
"diversity_weight must be nonnegative and representable in float32.")
53 raise ValueError(
"discriminator_learning_rate must be positive and representable in float32.")
57@dataclass(frozen=True)
59 """Track completed and eligible episodes and discard counts for partial episode rows."""
61 completed_episodes: int = 0
62 eligible_episodes: int = 0
63 incomplete_episode_steps: int = 0
64 discriminator_updates: int = 0
69 """Use a fixed-shape Box observation and skill index to select a physical Box action."""
71 _kind =
"smerl-categorical-skill"
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)
77 def _initialize(self, shape, actions, skills, config, seed, device):
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)
85 """Return the number of skill IDs."""
90 """Return the Torch device of the actor."""
93 def _observation(self, observation):
94 return _flatten_observation(observation, self.
_obs_shape)
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]
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)
110 raise ValueError(
"Use a skill ID in range(num_skills).")
115 """Write a numeric policy artifact for inference."""
118 _save_actor(path, metadata, self.
_actor._parameters())
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)
132 """Retain raw task rewards and the episode's gate, skill, and true termination."""
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)
139 def commit(self, transitions, skill, eligible):
140 for transition
in transitions:
142 self.
add(*transition)
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))
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.)
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)
166 lr=config.discriminator_learning_rate)
169 obs, action, reward, successor, terminal, skills, eligible = super()._batch()
171 rewards = _gated_reward(reward, logits.detach(), skills, eligible, self.
config.diversity_weight)
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
179 """Train SAC with task reward and a gated discriminator bonus.
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.
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.
197 _config_type = SMERLConfig
198 _stats_type = SMERLStats
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.")
205 self.
_skill_rng = np.random.default_rng(np.random.SeedSequence(_integer(seed,
"seed", 0), spawn_key=(5,)))
207 super().__init__(env_factory, policy=policy, config=config, max_episode_steps=max_episode_steps,
208 seed=seed, device=device)
210 def _make_policy(self, env, policy, seed, device):
212 policy=policy, seed=seed, device=device)
214 def _make_learner(self, seed):
217 def _start_episode(self):
220 def _action(self, observation, context):
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:
232 self.
_counts[
"completed_episodes"] += 1
233 self.
_counts[
"eligible_episodes"] += int(eligible)
237 """Count partial episodes toward the budget and exclude them from replay."""
239 super().
train(max_env_steps)
247@dataclass(frozen=True)
251 descriptor: tuple[float, ...] |
None
252 episode_returns: tuple[float, ...]
256@dataclass(frozen=True)
258 skills: tuple[DiscoveredSkill, ...]
261 occupied_cells: int |
None
262 archive_coverage: float |
None
263 archive_qd_score: float |
None
267 def __init__(self, policy, index):
272 def _greedy(self, observation):
273 return self.
_policy._action(observation, self.
_index,
True,
None)
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)
301 budget =
_StepBudget(episodes * horizon * policy.num_skills, counts)
303 with _open_environment(env_factory)
as env:
304 _check_spaces(env, policy)
305 for skill
in range(policy.num_skills):
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)
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)))
320 if archive
is not None:
321 if len(achieved) != len(archive.features_domain):
322 raise ValueError(
"Descriptor length must match the audit archive.")
324 cell = archive.index_grid(achieved)
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.
Replay, network, optimizer, and entropy settings for Soft Actor-Critic.
Cumulative SAC budget, replay, optimizer, and entropy statistics.
Train a reusable standalone Soft Actor-Critic policy.
_update(self, loss, optimizer, name, parameters=None)
Held-out return and behaviour of a discovered skill ID.
Configure SAC and the categorical skill discriminator.
tuple discriminator_hidden_sizes
float discriminator_learning_rate
A portable continuous-action actor with a discrete skill input.
save(self, path)
Export the skill-conditioned actor without replay or a discriminator.
load(cls, path, *, device="cpu", seed=0)
Load a policy independently of training and environment setup.
act(self, observation, skill, deterministic=True)
Infer an action at a given discovered skill.
_observation(self, observation)
_action(self, observation, skill, deterministic, generator)
_initialize(self, shape, actions, skills, config, seed, device)
Report real steps, complete episodes, and return-gate outcomes.
Learn discrete latent skills with episode-return gating.
train(self, max_env_steps)
Collect at most max_env_steps interactions on a fresh environment.
Report achieved behaviours and optional archive metrics on independent episodes.
add(self, observation, action, reward, next_observation, terminated)