6"""Train independent skill-conditioned SAC species using shared intrinsic rewards."""
8from collections
import Counter
9from dataclasses
import dataclass
10from math
import log, prod
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
22__all__ = [
"SSD",
"SSDConfig",
"SSDPolicy",
"SSDStats"]
26@dataclass(frozen=True, slots=True)
28 """Configure an independent SAC learner for each species.
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.
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
51 contrastive_weight: float = 1.
52 entropy_weight: float = 1.
53 update_period: int = 2
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))
60 cap = np.finfo(np.float32).max
63 raise ValueError(
"Use representable intrinsic reward weights, a positive rate and temperature >= 1e-6.")
68 """Use an observation and a skill index to produce a physical Box action."""
70 _kind =
"ssd-categorical-skill"
74@dataclass(frozen=True)
76 """The extrinsic environment reward is reserved for independent audits."""
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, ...] = ()
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))
92 def __init__(self, config, dimension, device, seed):
94 self.
rng = np.random.default_rng(seed)
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)
102 def encode(self, states):
103 return F.normalize(self.
encoder(states), dim=-1)
105 def logits(self, encoded):
106 return encoded @ F.normalize(self.
labels, dim=-1).T / self.
config.temperature
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(
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)
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
128 def __init__(self, actor, sac, seed, counts, species, representation):
129 super().__init__(actor, sac, seed, counts)
133 def update_species(self, learners):
135 states, labels = rep.sample(learners)
136 loss = F.cross_entropy(rep.logits(rep.encode(states)), labels)
137 self.
_update(loss, rep.optimizer,
"contrastive")
145 observations, actions, _, successors, terminated = super()._batch()
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
154 """Use jointly classified species-skill pairs and a shared particle exploration reward.
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.
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.
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.
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.")
183 if not isinstance(self.
config, SSDConfig)
or not isinstance(self.
_sac, SACConfig):
184 raise TypeError(
"Use SSDConfig and SACConfig.")
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))
192 with _open_environment(env_factory)
as env:
194 policy=policy, seed=_seed(self.
_rng), device=device)
195 for _
in range(self.
config.species))
196 width = prod(self.
_policies[0]._obs_shape)
200 for i, actor
in enumerate(self.
_policies))
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,
215 """Train on intrinsic rewards and return cumulative accounting."""
216 limit = _integer(max_env_steps,
"max_env_steps", 0)
220 with _open_environment(self.
_factory)
as env:
223 while budget.remaining:
227 skill = int(self.
_rng.integers(self.
config.skills))
228 code = np.zeros(self.
config.skills, dtype=np.float32)
231 while budget.remaining
and not cursor.ended:
232 state = np.concatenate((cursor.observation, code))
234 shape = prod(learner.actor._actions.shape)
235 action = learner.actor._decode(self.
_rng.uniform(-1., 1., size=shape))
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)
244 if steps % self.
config.update_period == 0
and learner.ready(steps):
254 def policy(self, species, *, device=None, seed=0):
255 """Copy one actor. Save it with SSDPolicy.save."""
256 i = _integer(species,
"species", 0)
258 raise ValueError(
"Species is outside the trained population.")
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())
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)
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.
_update(self, loss, optimizer, name, parameters=None)
A portable continuous-action actor with a discrete skill input.
Population, contrastive representation, and intrinsic reward settings.
float representation_rate
tuple representation_layers
A single exportable species with discrete skill-conditioned inference.
Report interactions, representation updates, and replay sizes of the species.
Discover controllable skills with a population of continuous-action SAC species.
policy(self, species, *, device=None, seed=0)
Copy a portable species actor with fresh inference randomness.
train(self, max_env_steps)
Collect reward-free replay and update the shared contrastive model.
evaluate(self, *, episodes=1, descriptor=None, archive=None, seed=0)
Audit every species on common seeded resets independently of training.