6"""Advantage-weighted trajectory skills and offline-to-online latent control."""
8from collections
import Counter
9from copy
import deepcopy
10from dataclasses
import dataclass
17from .policy
import (PolicyConfig, _BoxLayout, _flatten_observation, _integer, _mlp,
18 _observation_shape, _save_actor, _squashed_log_prob)
19from .rollout
import Episode, _Cursor, _StepBudget, _open_environment, _seed
20from .sac
import SACConfig, SACPolicy, SACStats, _SACLearner, _actor_metadata, _load_actor_layout, _twin_loss
21from .td3
import _Replay, _checked_step, _critic, _polyak, _twin_critics
23__all__ = [
"QDOS",
"QDOSConfig",
"QDOSPolicy",
"QDOSStats"]
25_FLOAT_MAX = np.finfo(np.float32).max
29@dataclass(frozen=True)
31 """Set the skill representation and its use in offline and online learning.
33 :param skill_horizon: Maximum environment steps per latent action.
34 :param latent_size: Number of coordinates of a bounded continuous skill.
35 :param batch_size: Offline representation minibatch size.
36 :param expectile: Upper expectile for implicit Q-learning.
37 :param advantage_temperature: Temperature of normalized advantage weights.
38 :param advantage_weighted: Use IQL advantages to weight representation learning.
39 :param kl_weight: Weight on Gaussian posterior-to-prior divergence.
40 :param information_weight: Weight of latent recovery on decoded logged states.
41 :param optimism: Random network distillation bonus for offline replay rewards.
42 :param offline_fraction: Fraction of offline samples in high-level SAC updates.
43 :param updates_per_skill: SAC minibatches per completed online latent action.
44 :param learning_rate: Offline IQL, representation, and pseudo-reward estimator rate.
47 skill_horizon: int = 8
51 advantage_temperature: float = .5
52 advantage_weighted: bool =
True
54 information_weight: float = .1
56 offline_fraction: float = .5
57 updates_per_skill: int = 1
58 learning_rate: float = 3e-4
60 def __post_init__(self):
61 for name
in (
"skill_horizon",
"latent_size",
"batch_size",
"updates_per_skill"):
62 object.__setattr__(self, name, _integer(getattr(self, name), name))
65 raise ValueError(
"Use an upper expectile, a Boolean weighting flag, and offline_fraction in [0, 1].")
66 for name
in (
"kl_weight",
"information_weight",
"optimism"):
67 if not 0. <= getattr(self, name) <= _FLOAT_MAX:
68 raise ValueError(f
"{name} must be finite, nonnegative and representable in float32.")
69 for name
in (
"advantage_temperature",
"learning_rate"):
70 if not np.finfo(np.float32).tiny <= getattr(self, name) <= _FLOAT_MAX:
71 raise ValueError(f
"{name} must be positive and representable as a normal float32.")
76 """Compose primitive actions from a state-to-skill policy and a frozen decoder.
78 Call reset() when the simulator resets. Between resets, act() chooses
79 a code every skill_horizon calls and holds it fixed for the decoder.
80 Each inference session needs its own policy instance and episode state.
83 def __init__(self, high, low, skill_horizon):
90 """Start the next action with a freshly selected skill."""
96 """Inspect the high-level policy's choice for an observation."""
97 flat = _flatten_observation(observation, self.
_high._obs_shape)
98 return self.
_high._draw(flat, deterministic, self.
_high._rng)[0]
101 def act_skill(self, observation, skill, deterministic=True):
102 """Decode one physical action for a skill vector with entries in [-1, 1]."""
103 flat = _flatten_observation(observation, self.
_high._obs_shape)
104 skill = np.asarray(skill, dtype=float)
105 if skill.shape != self.
_high._actions.shape
or not np.all(np.abs(skill) <= 1.):
106 raise ValueError(f
"Use a bounded skill vector of shape {self._high._actions.shape}.")
107 return self.
_decode(flat, skill.astype(np.float32), deterministic)
109 def _decode(self, flat, code, deterministic):
110 return self.
_low._draw(np.concatenate((flat, code)), deterministic, self.
_low._rng)[0]
113 def act(self, observation, deterministic=True):
114 """Accept the original observation shape and return a bounded Box action."""
115 observation = _flatten_observation(observation, self.
_high._obs_shape)
117 self.
_latent, _, _ = self.
_high._draw(observation, deterministic, self.
_high._rng)
125 """Write learned weights and spaces. The saved policy starts a new episode."""
126 low = _actor_metadata(self.
_low,
"qdos", self.
_high._obs_shape)
127 high_parameters = self.
_high._parameters()
128 low.update(latent_size=prod(self.
_high._actions.shape), skill_horizon=self.
skill_horizon,
129 high_hidden_sizes=self.
_high.config.hidden_sizes, high_parameters=len(high_parameters))
130 _save_actor(path, low, np.concatenate((high_parameters, self.
_low._parameters())))
134 def load(cls, path, *, device="cpu", seed=0):
135 """Load the actor pair and initialize new seeded inference generators."""
136 metadata, parameters, shape, action, policy = _load_actor_layout(path,
"qdos")
137 latent = _integer(metadata[
"latent_size"],
"latent_size")
138 cut = _integer(metadata[
"high_parameters"],
"high_parameters")
139 high, low = _build_actors(shape, action, latent,
PolicyConfig(metadata[
"high_hidden_sizes"]),
140 policy, np.random.default_rng(_integer(seed,
"seed", 0)), device)
141 high._set_parameters(parameters[:cut])
142 low._set_parameters(parameters[cut:])
143 return cls(high, low, metadata[
"skill_horizon"])
147@dataclass(frozen=True)
149 """Report logged segments, replay reuse, and actual primitive interactions."""
151 logged_segments: int = 0
152 unused_logged_steps: int = 0
153 offline_updates: int = 0
154 pseudo_labeled_segments: int = 0
155 online_skills: int = 0
156 discarded_prefix_steps: int = 0
157 offline_samples: int = 0
158 online_samples: int = 0
161def _build_actors(shape, action, latent, high_policy, low_policy, rng, device):
162 code =
_BoxLayout((latent,), (-1.,) * latent, (1.,) * latent, np.dtype(np.float32).str)
163 high = SACPolicy._from_layout(shape, code, high_policy, _seed(rng), device, stochastic=
False)
164 low = SACPolicy._from_layout((prod(shape) + latent,), action, low_policy, _seed(rng), device, stochastic=
False)
168def _segments(episodes, shape, actor, horizon, gamma):
169 """Build fixed-length within-episode chunks with discounted rewards and true successors."""
170 observations, actions, rewards, successors, terminal = [], [], [], [], []
172 discount = gamma ** np.arange(horizon)
173 for episode
in episodes:
174 if not isinstance(episode, Episode)
or not (episode.terminated
or episode.truncated):
175 raise ValueError(
"Supply completed Episode records with explicit termination or truncation.")
176 steps = episode.steps
177 obs, act, reward = (np.asarray(row, dtype=float)
for row
in
178 (episode.observations, episode.actions, episode.rewards))
179 if (
not steps
or obs.shape != (steps + 1, *shape)
or act.shape != (steps, *actor._actions.shape)
180 or reward.shape != (steps,)
181 or not all(np.all(np.abs(array) <= _FLOAT_MAX)
for array
in (obs, reward))):
182 raise ValueError(
"Logged episodes need aligned finite observations, actions, and rewards.")
183 rows, rest = divmod(steps, horizon)
185 obs, act = obs.reshape(steps + 1, -1), act.reshape(steps, -1)
186 if not np.all((act >= actor._low) & (act <= actor._high)):
187 raise ValueError(
"Logged actions must be within the physical Box bounds.")
188 length = rows * horizon
189 observations.extend(obs[:length].reshape(rows, horizon, obs.shape[1]))
190 actions.extend(actor._encode_actions(act[:length]).reshape(rows, horizon, act.shape[1]))
191 rewards.extend(reward[:length].reshape(rows, horizon) @ discount)
192 successors.extend(obs[horizon:length + 1:horizon])
193 terminal.extend((np.arange(1, rows + 1) * horizon == steps) & episode.terminated)
194 if not observations
or not np.all(np.abs(rewards) <= _FLOAT_MAX):
195 raise ValueError(
"Supply at least one complete logged skill segment with representable rewards.")
196 return tuple(np.asarray(array, dtype=dtype)
for array, dtype
in zip(
197 (observations, actions, rewards, successors, terminal), (np.float32,) * 4 + (bool,))), unused
201 """Keep an actual per-skill bootstrap discount alongside each macro transition."""
203 def __init__(self, capacity, state_size, code_size):
204 super().__init__(capacity, state_size, code_size)
205 self.
discounts = np.empty(capacity, dtype=np.float32)
207 def add_skill(self, observation, action, reward, successor, terminal, discount):
209 self.
add(observation, action, reward, successor, terminal)
212 def batch(self, rows, device):
213 return (*super().batch(rows, device), torch.as_tensor(self.
discounts[rows], device=device))
217 """Use ordinary SAC updates with mixed replay and variable-duration bootstrap."""
219 def __init__(self, actor, config, seed, counts, offline, fraction):
220 replay =
_SkillReplay(config.replay_capacity, prod(actor._obs_shape), prod(actor._actions.shape))
221 super().__init__(actor, config, seed, counts, replay=replay)
225 size = self.
config.batch_size
227 count = int(expected)
229 count += int(self.
sample_rng.random() < expected - count)
231 for replay, samples, field
in ((self.
offline, count,
"offline_samples"),
232 (self.
replay, size - count,
"online_samples")):
235 self.
counts[field] += samples
236 return tuple(torch.cat(parts)
for parts
in zip(*batches))
238 def _reward_step(self, states, actions, rewards, successors, terminal, discounts):
239 with torch.no_grad():
240 next_actions, log_prob = self.
actor._sample_actions(successors, self.
noise_rng)
242 targets = rewards + discounts * (values - self.
temperature * log_prob).masked_fill(terminal, 0.)
247def _normal_parameters(network, inputs):
248 mean, log_std = network(inputs).chunk(2, dim=-1)
249 return mean, log_std.clamp(-8., 2.)
252def _offline_step(loss, optimizer):
253 if not torch.isfinite(loss):
254 raise ValueError(
"QDOS produced a nonfinite offline loss.")
255 optimizer.zero_grad(set_to_none=
True)
257 _checked_step(optimizer)
262 """Discover skills with a trajectory VAE and compose them using semi-Markov SAC.
264 :param env_factory: Single Gymnasium environment with fixed Box observations and actions.
265 :param episodes: Completed rollout.Episode records from the same observation and action spaces.
266 :param config: Skill learning, reward relabeling and mixed replay settings.
267 :param sac: SACConfig for primitive discount, critics and high-level SAC.
268 learning_starts is measured in live primitive steps.
269 :param policy: Network architecture for both actors and the trajectory encoder.
270 :param max_episode_steps: External episode safety horizon.
271 :param seed: Nonnegative seed for data sampling, optimizers and reset.
272 :param device: Torch device. CPU by default.
275 def __init__(self, env_factory, *, episodes, config=None, sac=None, policy=None,
276 max_episode_steps=300, seed=0, device="cpu"):
277 if not callable(env_factory):
278 raise TypeError(
"Provide a callable environment factory.")
281 if not isinstance(self.
config, QDOSConfig)
or not isinstance(self.
sac, SACConfig):
282 raise TypeError(
"Supply QDOSConfig and SACConfig settings.")
285 rng = np.random.default_rng(_integer(seed,
"seed", 0))
287 self.
_horizon = _integer(max_episode_steps,
"max_episode_steps")
289 with _open_environment(env_factory)
as env:
290 self.
_shape = _observation_shape(env.observation_space)
291 self.
_action = _BoxLayout.from_space(env.action_space)
292 self.
_high, self.
_low = _build_actors(self.
_shape, self.
_action, config.latent_size, policy, policy, rng, device)
295 self.
_torch_rng = torch.Generator(device=self.
_low.device).manual_seed(_seed(rng))
296 self.
_reset_rng = np.random.default_rng(_seed(rng))
297 self.
_rollout_rng = torch.Generator(device=self.
_low.device).manual_seed(_seed(rng))
299 trajectory_width = config.skill_horizon * (width + prod(self.
_action.shape))
300 self.
_encoder = _mlp(trajectory_width, 2 * config.latent_size, policy, _seed(rng), self.
_low.device)
301 self.
_prior = _mlp(width, 2 * config.latent_size, policy, _seed(rng), self.
_low.device)
302 self.
_value = _mlp(width, 1, policy, _seed(rng), self.
_low.device)
305 aux_width = width + config.latent_size
306 self.
_reward = _mlp(aux_width, 1, policy, _seed(rng), self.
_low.device)
307 self.
_rnd_target = _mlp(aux_width, 8, policy, _seed(rng), self.
_low.device).requires_grad_(
False)
308 self.
_rnd = _mlp(aux_width, 8, policy, _seed(rng), self.
_low.device)
309 rate = config.learning_rate
312 *self.
_low._trainable_parameters()), lr=rate)
318 """Return the updated split of logged, live, and optimizer work."""
320 temperature = self.
sac.initial_temperature
if self.
_learner is None else float(self.
_learner.temperature)
322 replay_size=size, temperature=temperature)
324 def _batch(self, rows):
325 return tuple(torch.as_tensor(array[rows], device=self.
_low.device)
for array
in self.
_log)
327 def _sample_normal(self, mean, log_std):
328 noise = torch.randn(mean.shape, generator=self.
_torch_rng, device=mean.device, dtype=mean.dtype)
329 return mean + noise * log_std.exp()
331 def _posterior(self, states, actions):
332 return _normal_parameters(self.
_encoder, torch.cat((states, actions), dim=-1).flatten(1))
336 """Continue offline updates up to the first call to train()."""
337 updates = _integer(updates,
"updates", 0)
339 raise RuntimeError(
"QDOS freezes the decoder and offline labels at the start of online training.")
341 for _
in range(updates):
342 states, actions, rewards, successor, terminal = self.
_batch(self.
_rng.integers(self.
_count,
343 size=cfg.batch_size))
345 mean, scale = self.
_posterior(states, actions)
347 value = self.
_value(start).flatten()
348 with torch.no_grad():
349 target = rewards + gamma * self.
_value(successor).flatten().masked_fill(terminal, 0.)
350 target_q = torch.stack([_critic(net, start, code)
for net
in self.
_targets]).min(dim=0).values
351 advantage = target_q - value
352 expectile = torch.where(advantage > 0., cfg.expectile, 1. - cfg.expectile)
353 critic_loss = sum(F.mse_loss(_critic(net, start, code.detach()), target)
for net
in self.
_critics)
354 _offline_step(critic_loss + (expectile * advantage.square()).mean(), self.
_iql_optimizer)
357 weights = ((advantage.detach() - advantage.detach().max()) / cfg.advantage_temperature
358 ).softmax(dim=0)
if cfg.advantage_weighted
else torch.full_like(advantage, 1. / len(start))
359 prior, prior_scale = _normal_parameters(self.
_prior, start)
360 kl = prior_scale - scale + .5 * ((2 * (scale - prior_scale)).exp()
361 + ((mean - prior) * (-prior_scale).exp()).square() - 1.)
362 inputs = torch.cat((states, code[:,
None].expand(-1, cfg.skill_horizon, -1)), dim=-1)
363 predicted, std = self.
_low._network(inputs).chunk(2, dim=-1)
364 latent_actions = actions.clamp(-1. + 1e-6, 1. - 1e-6).atanh()
365 logp = _squashed_log_prob(predicted, (F.softplus(std) + .001).log(), latent_actions, 0.)
366 loss = cfg.kl_weight * kl.sum(dim=-1).mean() - weights @ logp.mean(dim=-1)
367 if cfg.information_weight:
369 random_code = 2 * torch.rand(code.shape, generator=self.
_torch_rng, device=code.device) - 1
370 generated = self.
_low._normalized(
371 torch.cat((states, random_code[:,
None].expand(-1, cfg.skill_horizon, -1)), dim=-1))
372 recovered, _ = self.
_posterior(states, generated)
373 loss = loss + cfg.information_weight * (weights @ (recovered.tanh() - random_code).square().mean(-1))
376 inputs = torch.cat((start, code.detach()), dim=-1)
377 _offline_step(F.mse_loss(self.
_reward(inputs).flatten(), rewards)
379 self.
_counts[
"offline_updates"] += 1
380 self.
_counts[
"optimizer_steps"] += 3
384 def _start_online(self):
385 if not self.
_counts[
"offline_updates"]:
386 raise RuntimeError(
"Call pretrain() with a positive update count before online training.")
389 if cfg.offline_fraction:
390 for start
in range(0, self.
_count, cfg.batch_size):
391 rows = slice(start, start + cfg.batch_size)
392 states, actions, reward, _, _ = self.
_batch(rows)
395 inputs = torch.cat((states[:, 0], code), dim=-1)
396 bonus = (self.
_rnd(inputs) - self.
_rnd_target(inputs)).square().mean(dim=-1).sqrt()
397 reward = self.
_reward(inputs).flatten() + cfg.optimism * bonus
398 if not bool(torch.isfinite(reward).all()):
399 raise ValueError(
"QDOS pseudo-rewards must be finite.")
400 replay.actions[rows], replay.rewards[rows] = code.cpu().numpy(), reward.cpu().numpy()
401 replay.observations[:] = self.
_log[0][:, 0]
402 replay.next_observations[:] = self.
_log[3]
403 replay.terminated[:] = self.
_log[4]
404 replay.discounts.fill(gamma)
411 """Continue high-level SAC in a fresh environment with the same spaces.
413 A cut prefix without an environment boundary is counted and
414 omitted from replay. A completed short terminal or truncated
415 skill is kept with its actual duration and last observation.
418 horizon, gamma = self.
config.skill_horizon, self.
sac.gamma
419 with _open_environment(self.
_factory)
as env:
420 if (_observation_shape(env.observation_space) != self.
_shape
421 or _BoxLayout.from_space(env.action_space) != self.
_action):
422 raise ValueError(
"The environment factory changed its observation or action space.")
426 while budget.remaining:
429 start = cursor.observation
430 if self.
_counts[
"training_steps"] < self.
sac.learning_starts:
431 with torch.no_grad():
432 mean, scale = _normal_parameters(self.
_prior, self.
_high._tensor(start))
436 reward, discount, count = 0., 1., 0
437 for count
in range(1, min(horizon, budget.remaining) + 1):
438 inputs = np.concatenate((cursor.observation, code))
440 step_reward, terminal, _, _ = cursor.step(action, budget,
"training_steps")
441 reward += discount * step_reward
445 if count < horizon
and not cursor.ended:
446 self.
_counts[
"discarded_prefix_steps"] += count
448 self.
_learner.replay.add_skill(start, code, reward, cursor.observation, terminal, discount)
449 self.
_counts[
"online_skills"] += 1
450 if self.
_counts[
"training_steps"] >= self.
sac.learning_starts:
451 for _
in range(self.
config.updates_per_skill):
456 def policy(self, *, seed=0, device=None):
457 """Return a new episode-state QDOSPolicy for evaluation or export."""
458 rng = np.random.default_rng(_integer(seed,
"seed", 0))
459 high, low = [actor._new(_seed(rng), device)
for actor
in (self.
_high, self.
_low)]
460 high._set_parameters(self.
_high._parameters())
461 low._set_parameters(self.
_low._parameters())
Architecture of the actor and, for PPO, the separate value network.
Configure trajectory pretraining, data reuse, and the latent action horizon.
Two portable inference networks and a fixed skill duration.
_decode(self, flat, code, deterministic)
load(cls, path, *, device="cpu", seed=0)
Restore the two actors without an environment or training data.
act(self, observation, deterministic=True)
Choose or continue a skill and decode one physical action.
act_skill(self, observation, skill, deterministic=True)
Execute a caller-selected code independently of the high-level actor.
save(self, path)
Export both actors and the skill horizon in one numeric file.
reset(self)
Drop the pending skill at an episode boundary.
select_skill(self, observation, deterministic=True)
Select one bounded code without changing the held skill.
Offline and online training counts with separate sample origins.
Train trajectory skills from a fixed log and adapt a high-level controller online.
train(self, max_env_steps)
Spend exactly the additional primitive-step budget on the deployed hierarchy.
policy(self, *, seed=0, device=None)
Copy both inference actors without replay or optimizer state.
pretrain(self, updates)
Fit the skill and advantage networks from logged segments only.
_posterior(self, states, actions)
_sample_normal(self, mean, log_std)
Replay, network, optimizer, and entropy settings for Soft Actor-Critic.
Cumulative SAC budget, replay, optimizer, and entropy statistics.
_values(networks, observations, actions)
_update(self, loss, optimizer, name, parameters=None)
add(self, observation, action, reward, next_observation, terminated)