58 """Combine a Box observation and a desired skill to select an action.
60 The actor concatenates the flattened observation with the skill mapped
61 into [-1, 1]. The saved actor requires only an observation and a skill
62 in physical units. It can be loaded without the environment or trainer.
64 :param observation_space: Fixed-shape numeric Gymnasium Box.
65 :param action_space: Finite floating-point Gymnasium Box.
66 :param skill_bounds: Ordered physical (low, high) pairs for skill coordinates.
67 :param config: Optional actor architecture as a PolicyConfig.
68 :param seed: Nonnegative initialization and inference seed.
69 :param device: Torch CPU or CUDA device.
72 def __init__(self, observation_space, action_space, skill_bounds, *, config=None, seed=0, device="cpu"):
73 self.
_initialize(_observation_shape(observation_space), _BoxLayout.from_space(action_space),
77 def _initialize(self, shape, actions, domain, config, seed, device):
79 self.
_model = SACPolicy._from_layout((prod(shape) + len(domain.bounds),), actions, config,
80 seed, device, stochastic=
False)
84 """Return the original physical bounds as an immutable tuple."""
89 """Return the policy architecture."""
94 """Return the actor's Torch device."""
97 def _observation(self, observation):
98 return _flatten_observation(observation, self.
_obs_shape)
100 def _action(self, observation, normalized_skill, deterministic, generator):
101 inputs = np.concatenate((observation, normalized_skill))
102 return self.
_model._draw(inputs, deterministic, generator)[0]
105 def act(self, observation, skill, deterministic=True):
106 """Return a physical Box action given an observation and a physical goal."""
107 goal = self.
_domain.normalize(skill, goal=
True)
112 """Export the conditioned actor for independent inference."""
113 metadata = _actor_metadata(self.
_model,
"skill-conditioned-sac", self.
_obs_shape)
115 _save_actor(path, metadata, self.
_model._parameters())
119 def load(cls, path, *, device="cpu", seed=0):
120 """Load an exported actor and start a fresh stochastic generator."""
121 metadata, parameters, shape, actions, config = _load_actor_layout(path,
"skill-conditioned-sac")
122 actor = cls.__new__(cls)
123 actor._initialize(shape, actions,
_DescriptorDomain(metadata[
"skill_bounds"]), config, seed, device)
124 actor._model._set_parameters(parameters)
144 """Store pre-action features, original skills, and time-limit masks."""
146 def __init__(self, capacity, observation_size, action_size, skill_size):
147 super().__init__(capacity, observation_size, action_size)
148 self.
features = np.empty((capacity, skill_size), dtype=np.float32)
150 self.
truncated = np.empty(capacity, dtype=bool)
152 def add(self, observation, action, reward, next_observation, terminated, *, truncated, feature, skill):
154 super().add(observation, action, reward, next_observation, terminated)
156 self.
truncated[index] = truncated
and not terminated
158 def batch(self, rows, device):
159 return (*super().batch(rows, device), *(torch.as_tensor(field[rows], device=device)
for field
in
184 """Learn reward, successor-feature and multiplier networks for a single actor."""
186 def __init__(self, policy, config, seed, counts, sample_skill):
187 actor = policy._model
188 dimension = len(policy.skill_bounds)
189 replay =
_SkillReplay(config.replay_capacity, prod(policy._obs_shape), prod(actor._actions.shape), dimension)
190 base_seed, sf_one, sf_two, multiplier, relabel_seed = map(np.random.default_rng,
191 np.random.SeedSequence(seed).spawn(5))
192 super().__init__(actor, config, _seed(base_seed), counts, replay=replay, entropy_per_action=-0.5)
193 inputs = prod(actor._obs_shape) + prod(actor._actions.shape)
196 _mlp(inputs, dimension, widths, _seed(rng), self.
device, nn.ReLU)
for rng
in (sf_one, sf_two)
201 _seed(multiplier), self.
device, nn.ReLU)
205 def record(self, observation, action, reward, successor, terminated, truncated, feature, skill):
206 self.
replay.add(observation, self.
actor._encode(action), reward, successor, terminated,
207 truncated=truncated, feature=feature, skill=skill)
210 """Duplicate transitions with fresh skills while preserving observations, rewards and features."""
212 copies = self.
config.skill_relabels
215 skills = torch.cat((skills, self.
actor._tensor(relabeled)))
216 transition = [field.repeat((copies + 1,) + (1,) * (field.ndim - 1))
for field
in transition]
217 return (*transition, skills)
220 def _feature_values(networks, observations, actions):
221 inputs = torch.cat((observations, actions), dim=-1)
222 return torch.stack([network(inputs)
for network
in networks])
224 def _multiplier_step(self, observations, skills):
225 with torch.no_grad():
226 actions, _ = self.
actor._sample_actions(observations, self.
noise_rng)
228 error = _skill_error(sf, skills, self.
config.gamma)
229 loss = _multiplier_loss(self.
multiplier(observations).squeeze(-1), error, self.
config.delta)
232 def _successor_step(self, observations, actions, successors, terminated, truncated, features):
233 with torch.no_grad():
234 next_actions, _ = self.
actor._sample_actions(successors, self.
noise_rng)
236 targets = _successor_target(features, terminated, estimates, self.
config.gamma)
238 self.
_update(_twin_loss(estimates, targets, truncated[:,
None]),
243 observations, actions, rewards, successors, terminated, truncated, features, skills = self.
_training_batch()
244 observations = torch.cat((observations, skills), dim=-1)
245 successors = torch.cat((successors, skills), dim=-1)
248 self.
_reward_step(observations, actions, rewards, successors, terminated, truncated)
249 self.
_successor_step(observations, actions, successors, terminated, truncated, features)
250 with torch.no_grad():
251 weight = self.
multiplier(observations).squeeze(-1).sigmoid()
252 actions, log_prob = self.
actor._sample_actions(observations, self.
noise_rng)
253 rewards = self.
_values(self.
critics, observations, actions).mean(dim=0)
255 penalty = _pseudo_huber(_skill_error(features, skills, self.
config.gamma), self.
config.huber_scale)
256 loss = self.
temperature * log_prob - (1 - weight) * rewards + self.
config.lambda_scale * weight * penalty
262 """Optimize rewards and skill matching without an archive.
264 One desired skill is sampled per episode and held until reset. The
265 callback feature(observation, action, info) returns the physical feature
266 vector for the current transition, before the environment step. The
267 observation and info come from reset or the previous step. The action is
268 the physical action about to be applied. Features outside skill bounds
269 are allowed and are normalized without clipping.
271 :param env_factory: Callable producing fresh single Box Gymnasium environments.
272 :param feature: Pre-action feature callback returning one value per skill coordinate.
273 :param skill_bounds: Finite physical (low, high) pairs defining the normalization.
274 :param skill_sampler: Optional callable taking a numpy.random.Generator
275 and returning a physical goal inside the bounds. By default, goals
276 are uniform in the Box. The same prior is used for replay relabeling.
277 :param policy: Optional PolicyConfig specifying actor widths.
278 :param config: QDACConfig with the optimization and constraint settings.
279 :param max_episode_steps: External horizon. Time-limit rows are masked
280 in both Bellman losses, as in the reference implementation.
281 :param seed: Nonnegative seed for initialization, environments, skills, and replay.
282 :param device: Torch CPU or CUDA device.
285 _config_type = QDACConfig
286 _stats_type = QDACStats
288 def __init__(self, env_factory, *, feature, skill_bounds, skill_sampler=None, policy=None, config=None,
289 max_episode_steps=300, seed=0, device="cpu"):
290 if not callable(feature)
or (skill_sampler
is not None and not callable(skill_sampler)):
291 raise TypeError(
"feature and any supplied skill_sampler must be callable.")
294 self.
_skill_rng = np.random.default_rng(np.random.SeedSequence(_integer(seed,
"seed", 0), spawn_key=(5,)))
295 super().__init__(env_factory, policy=policy, config=config, max_episode_steps=max_episode_steps,
296 seed=seed, device=device)
298 def _make_policy(self, env, policy, seed, device):
300 config=policy, seed=seed, device=device)
302 def _make_learner(self, seed):
305 def _sample_skill(self, rng):
307 return rng.uniform(-1, 1, len(self.
_domain.bounds)).astype(np.float32)
310 def _start_episode(self):
313 def _action(self, observation, context):
316 def _feature(self, observation, action, info):
320 def _record(self, observation, action, reward, successor, terminated, truncated, feature, context):
321 self.
_learner.record(observation, action, reward, successor, terminated, truncated, feature, context)