QDpy
Loading...
Searching...
No Matches
ssd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Train independent skill-conditioned SAC species using shared intrinsic rewards."""
7
8from collections import Counter
9from dataclasses import dataclass
10from math import log, prod
11
12import numpy as np
13import torch
14from torch import nn
15from torch.nn import functional as F
16
17from .policy import PolicyConfig, _integer, _mlp
18from .rollout import _Cursor, _StepBudget, _check_spaces, _open_environment, _seed
19from .sac import SACConfig, SACStats, _SACLearner
20from .smerl import SMERLPolicy, evaluate_discovered_skills
21
22__all__ = ["SSD", "SSDConfig", "SSDPolicy", "SSDStats"]
23
24
25
26@dataclass(frozen=True, slots=True)
28 """Configure an independent SAC learner for each species.
29
30 :param species: Number of independent species.
31 :param skills: Number of discrete skills per species.
32 :param embedding_size: Width of the shared contrastive representation.
33 :param representation_layers: Hidden widths of the shared state encoder.
34 :param representation_batch: Maximum replay particles sampled per active species per update.
35 :param representation_rate: Adam rate for the encoder and label prototypes.
36 :param temperature: Temperature for normalized contrastive logits.
37 :param neighbors: Number of replay particles used to estimate state dispersion.
38 :param contrastive_weight: Scale of the joint label likelihood bonus.
39 :param entropy_weight: Scale of the particle-based exploration bonus.
40 :param update_period: Species interactions between successive learner updates.
41 """
42
43 species: int = 3
44 skills: int = 4
45 embedding_size: int = 16
46 representation_layers: tuple[int, ...] = (64,)
47 representation_batch: int = 24
48 representation_rate: float = .001
49 temperature: float = .2
50 neighbors: int = 5
51 contrastive_weight: float = 1.
52 entropy_weight: float = 1.
53 update_period: int = 2
54
55 def __post_init__(self):
56 for name in ("species", "embedding_size", "representation_batch", "neighbors", "update_period"):
57 object.__setattr__(self, name, _integer(getattr(self, name), name))
58 object.__setattr__(self, "skills", _integer(self.skills, "skills", 2))
59 object.__setattr__(self, "representation_layers", PolicyConfig(self.representation_layers).hidden_sizes)
60 cap = np.finfo(np.float32).max
61 if not (1e-6 <= self.temperature <= cap and 0 < self.representation_rate <= cap
62 and 0 <= self.contrastive_weight <= cap and 0 <= self.entropy_weight <= cap):
63 raise ValueError("Use representable intrinsic reward weights, a positive rate and temperature >= 1e-6.")
64
65
66
68 """Use an observation and a skill index to produce a physical Box action."""
69
70 _kind = "ssd-categorical-skill"
71
72
73
74@dataclass(frozen=True)
76 """The extrinsic environment reward is reserved for independent audits."""
77
78 contrastive_updates: int = 0
79 species_steps: tuple[int, ...] = ()
80 species_episodes: tuple[int, ...] = ()
81 replay_by_species: tuple[int, ...] = ()
82 species_temperatures: tuple[float, ...] = ()
83
84
85def _particle_bonus(query, particles, neighbors):
86 distances = torch.cdist(query, particles)
87 count = min(neighbors, distances.shape[1])
88 return torch.log1p(distances.topk(count, largest=False, dim=1).values.mean(dim=1))
89
90
92 def __init__(self, config, dimension, device, seed):
93 self.config, self.width, self.device = config, dimension, device
94 self.rng = np.random.default_rng(seed)
95 layers = PolicyConfig(config.representation_layers)
96 self.encoder = _mlp(dimension, config.embedding_size, layers, _seed(self.rng), device, nn.ReLU)
97 generator = torch.Generator(device="cpu").manual_seed(_seed(self.rng))
98 self.labels = nn.Parameter(torch.randn(config.species * config.skills, config.embedding_size,
99 generator=generator, device="cpu").to(device))
100 self.optimizer = torch.optim.Adam((*self.encoder.parameters(), self.labels), lr=config.representation_rate)
101
102 def encode(self, states):
103 return F.normalize(self.encoder(states), dim=-1)
104
105 def logits(self, encoded):
106 return encoded @ F.normalize(self.labels, dim=-1).T / self.config.temperature
107
108 def sample(self, learners):
109 states, labels = [], []
110 for i, learner in enumerate(learners):
111 if learner.replay.size:
112 observations, _, _, successors, _ = learner.replay.sample(
113 self.config.representation_batch, self.rng, self.device)
114 states.append(successors[:, :self.width])
115 labels.append(i * self.config.skills + observations[:, self.width:].argmax(dim=1))
116 return torch.cat(states), torch.cat(labels)
117
118 @torch.no_grad()
119 def reward(self, states, labels, references):
120 points = self.encode(states)
121 log_prob = F.log_softmax(self.logits(points), dim=1)
122 contrast = log_prob.gather(1, labels[:, None]).squeeze(1) + log(log_prob.shape[1])
123 entropy = _particle_bonus(points, self.encode(references), self.config.neighbors)
124 return self.config.contrastive_weight * contrast + self.config.entropy_weight * entropy
125
126
128 def __init__(self, actor, sac, seed, counts, species, representation):
129 super().__init__(actor, sac, seed, counts)
130 self.species = species
131 self.representation = representation
132
133 def update_species(self, learners):
134 rep = self.representation
135 states, labels = rep.sample(learners)
136 loss = F.cross_entropy(rep.logits(rep.encode(states)), labels)
137 self._update(loss, rep.optimizer, "contrastive")
138 self.references = states
139 try:
140 self.update()
141 finally:
142 del self.references
143
144 def _batch(self):
145 observations, actions, _, successors, terminated = super()._batch()
146 rep = self.representation
147 labels = self.species * rep.config.skills + observations[:, rep.width:].argmax(dim=1)
148 reward = rep.reward(successors[:, :rep.width], labels, self.references)
149 return observations, actions, reward, successors, terminated
150
151
152
153class SSD:
154 """Use jointly classified species-skill pairs and a shared particle exploration reward.
155
156 Each species has a separate actor, critics and replay buffer. A shared
157 contrastive encoder scores successor observations against all learned
158 species-skill prototypes. Its joint log likelihood decomposes into
159 skill and conditional species log likelihoods. A nearest-particle
160 bonus encourages visitation of underrepresented states.
161
162 This implementation uses discrete skills, Gymnasium Box observations
163 and Box actions. A new episode holds one skill fixed throughout.
164 Each call visits species in round-robin order and can spend its full
165 interaction budget. A cutoff contributes the measured transitions
166 to replay and the next call starts a fresh episode.
167
168 :param env_factory: Callable returning a fresh Gymnasium environment.
169 :param config: SSDConfig for intrinsic rewards and speciation.
170 :param sac: SACConfig shared by the independent learners.
171 :param policy: PolicyConfig for the actors.
172 :param max_episode_steps: Horizon for collection and independent evaluation.
173 :param seed: Private search and reset seed.
174 :param device: PyTorch device.
175 """
176
177 def __init__(self, env_factory, *, config=None, sac=None, policy=None,
178 max_episode_steps=300, seed=0, device="cpu"):
179 if not callable(env_factory):
180 raise TypeError("Supply a callable environment factory.")
181 self.config = SSDConfig() if config is None else config
182 self._sac = SACConfig() if sac is None else sac
183 if not isinstance(self.config, SSDConfig) or not isinstance(self._sac, SACConfig):
184 raise TypeError("Use SSDConfig and SACConfig.")
185 self._factory = env_factory
186 self._horizon = _integer(max_episode_steps, "max_episode_steps")
187 self._rng, self._reset_rng = map(np.random.default_rng, np.random.SeedSequence(_integer(seed, "seed", 0)).spawn(2))
188 self._counts = Counter()
189 self._species_steps = [0] * self.config.species
190 self._species_episodes = [0] * self.config.species
191 self._episode_starts = 0
192 with _open_environment(env_factory) as env:
193 self._policies = tuple(SSDPolicy(env.observation_space, env.action_space, self.config.skills,
194 policy=policy, seed=_seed(self._rng), device=device)
195 for _ in range(self.config.species))
196 width = prod(self._policies[0]._obs_shape)
197 self._representation = _Representation(self.config, width, self._policies[0].device, _seed(self._rng))
198 self._learners = tuple(_SpeciesLearner(actor._actor, self._sac, _seed(self._rng),
199 self._counts, i, self._representation)
200 for i, actor in enumerate(self._policies))
201
202 @property
203 def stats(self):
204 """Return cumulative costs, including prefixes of unfinished episodes."""
205 replay = tuple(learner.replay.size for learner in self._learners)
206 temperatures = tuple(float(learner.temperature) for learner in self._learners)
207 return SSDStats(**self._counts, replay_size=sum(replay), replay_by_species=replay,
208 temperature=float(np.mean(temperatures)), species_temperatures=temperatures,
209 species_steps=tuple(self._species_steps), species_episodes=tuple(self._species_episodes))
210
211
214 def train(self, max_env_steps):
215 """Train on intrinsic rewards and return cumulative accounting."""
216 limit = _integer(max_env_steps, "max_env_steps", 0)
217 if not limit:
218 return self.stats
219 budget = _StepBudget(limit, self._counts)
220 with _open_environment(self._factory) as env:
221 _check_spaces(env, self._policies[0])
222 cursor = _Cursor(env, self._policies[0], self._horizon, self._reset_rng)
223 while budget.remaining:
224 i = self._episode_starts % self.config.species
225 self._episode_starts += 1
226 policy, learner = self._policies[i], self._learners[i]
227 skill = int(self._rng.integers(self.config.skills))
228 code = np.zeros(self.config.skills, dtype=np.float32)
229 code[skill] = 1.
230 cursor.reset()
231 while budget.remaining and not cursor.ended:
232 state = np.concatenate((cursor.observation, code))
233 if self._species_steps[i] < self._sac.learning_starts:
234 shape = prod(learner.actor._actions.shape)
235 action = learner.actor._decode(self._rng.uniform(-1., 1., size=shape))
236 else:
237 action = learner.actor._draw(state, False, learner.noise_rng)[0]
238 saved = action.copy()
239 _, terminated, _, _ = cursor.step(action, budget, "training_steps")
240 successor = np.concatenate((cursor.observation, code))
241 learner.record(state, saved, 0., successor, terminated)
242 self._species_steps[i] += 1
243 steps = self._species_steps[i]
244 if steps % self.config.update_period == 0 and learner.ready(steps):
245 learner.update_species(self._learners)
246 self._species_episodes[i] += int(cursor.ended)
247 return self.stats
248
249
254 def policy(self, species, *, device=None, seed=0):
255 """Copy one actor. Save it with SSDPolicy.save."""
256 i = _integer(species, "species", 0)
257 if i >= len(self._policies):
258 raise ValueError("Species is outside the trained population.")
259 source = self._policies[i]
260 result = SSDPolicy.__new__(SSDPolicy)
261 result._initialize(source._obs_shape, source._actions, source.num_skills, source._actor.config,
262 seed, source.device if device is None else device)
263 result._actor._set_parameters(source._actor._parameters())
264 return result
265
266
272 def evaluate(self, *, episodes=1, descriptor=None, archive=None, seed=0):
273 """Use the standard skill audit with one result per species."""
274 return tuple(evaluate_discovered_skills(self._factory, actor, descriptor=descriptor, archive=archive,
275 episodes=episodes, max_episode_steps=self._horizon, seed=seed)
276 for actor in self._policies)
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
_update(self, loss, optimizer, name, parameters=None)
Definition sac.py:202
A portable continuous-action actor with a discrete skill input.
Definition smerl.py:68
Population, contrastive representation, and intrinsic reward settings.
Definition ssd.py:27
float temperature
Definition ssd.py:49
float contrastive_weight
Definition ssd.py:51
float entropy_weight
Definition ssd.py:52
float representation_rate
Definition ssd.py:48
tuple representation_layers
Definition ssd.py:46
A single exportable species with discrete skill-conditioned inference.
Definition ssd.py:67
Report interactions, representation updates, and replay sizes of the species.
Definition ssd.py:75
Discover controllable skills with a population of continuous-action SAC species.
Definition ssd.py:153
int _episode_starts
Definition ssd.py:191
list _species_steps
Definition ssd.py:189
list _species_episodes
Definition ssd.py:190
policy(self, species, *, device=None, seed=0)
Copy a portable species actor with fresh inference randomness.
Definition ssd.py:254
stats(self)
Definition ssd.py:203
train(self, max_env_steps)
Collect reward-free replay and update the shared contrastive model.
Definition ssd.py:214
evaluate(self, *, episodes=1, descriptor=None, archive=None, seed=0)
Audit every species on common seeded resets independently of training.
Definition ssd.py:272
].argmax(dim width
Definition ssd.py:93
encode(self, states)
Definition ssd.py:102
logits(self, encoded)
Definition ssd.py:105