QDpy
Loading...
Searching...
No Matches
qdac_mb.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""PyTorch, vector-observation Quality-Diversity Actor-Critic with a world model."""
7
8from copy import deepcopy
9from dataclasses import asdict, dataclass
10from math import prod
11
12import numpy as np
13import torch
14from torch import nn
15from torch.nn import functional as F
16
17from ._qdac_world import (
18 QDACMBWorldConfig, _RSSM, _SequenceReplay, _WorldModel, _scalar_head, _symlog_loss, _symlog_mean,
19)
20from .descriptor_policy import _DescriptorDomain
21from .policy import PolicyConfig, _BoxLayout, _flatten_observation, _integer, _mlp, _observation_shape, _save_actor
22from .qdac import QDAC, _pseudo_huber
23from .rollout import _seed
24from .sac import SACPolicy, _actor_metadata, _load_actor_layout
25from .td3 import OffPolicyStats, _polyak
26
27__all__ = ["QDACMB", "QDACMBConfig", "QDACMBPolicy", "QDACMBSession", "QDACMBStats", "QDACMBWorldConfig"]
28
29
30
31@dataclass(frozen=True)
33 """Control the smaller Dreamer-style implementation for vector observations.
34
35 :param world: Recurrent state-space model layout.
36 :param replay_capacity: Real transition capacity of the ring buffer.
37 :param batch_size: Number of measured sequence windows per model update.
38 :param sequence_length: Number of real transitions per window.
39 :param learning_starts: Minimum cumulative interaction count before learning.
40 :param train_every: Run one joint update per this many environment steps.
41 :param imagination_batch_size: Number of independent states and skills per imagined batch.
42 :param imagination_horizon: Number of model transitions per imagined trajectory.
43 :param critic_hidden_sizes: Widths of the reward and successor-feature value networks.
44 :param world_learning_rate: Adam rate of the recurrent model and its heads.
45 :param actor_learning_rate: Adam rate of the squashed Gaussian policy.
46 :param critic_learning_rate: Adam rate of the reward and successor-feature critics.
47 :param multiplier_learning_rate: Adam rate of the skill constraint multiplier.
48 :param gamma: Discount for imagined rewards and features.
49 :param return_lambda: Mixing parameter for imagined lambda returns.
50 :param tau: Polyak averaging rate of the value targets.
51 :param delta: Skill constraint radius in normalized coordinates.
52 :param huber_scale: Smoothing scale of the actor's skill penalty.
53 :param lambda_scale: Multiplier of the smoothed skill distance.
54 :param entropy_scale: Fixed weight of the normalized action entropy.
55 :param free_nats: Floor below which the latent KL receives no gradient.
56 :param gradient_clip: Maximum optimizer gradient norm.
57 """
58
59 world: QDACMBWorldConfig = QDACMBWorldConfig()
60 replay_capacity: int = 100_000
61 batch_size: int = 16
62 sequence_length: int = 16
63 learning_starts: int = 256
64 train_every: int = 4
65 imagination_batch_size: int = 32
66 imagination_horizon: int = 12
67 critic_hidden_sizes: tuple[int, ...] = (128, 128)
68 world_learning_rate: float = 3e-4
69 actor_learning_rate: float = 3e-4
70 critic_learning_rate: float = 3e-4
71 multiplier_learning_rate: float = 3e-4
72 gamma: float = .99
73 return_lambda: float = .95
74 tau: float = .02
75 delta: float = .1
76 huber_scale: float = .001
77 lambda_scale: float = 1.
78 entropy_scale: float = .003
79 free_nats: float = 1.
80 gradient_clip: float = 100.
81
82 def __post_init__(self):
83 if not isinstance(self.world, QDACMBWorldConfig):
84 raise TypeError("world must be a QDACMBWorldConfig.")
85 for name in ("replay_capacity", "batch_size", "sequence_length", "train_every",
86 "imagination_batch_size", "imagination_horizon"):
87 object.__setattr__(self, name, _integer(getattr(self, name), name))
88 object.__setattr__(self, "learning_starts", _integer(self.learning_starts, "learning_starts", 0))
89 object.__setattr__(self, "critic_hidden_sizes", PolicyConfig(self.critic_hidden_sizes).hidden_sizes)
90 if self.sequence_length > self.replay_capacity:
91 raise ValueError("sequence_length cannot exceed replay_capacity.")
92 if not (0 <= self.gamma < 1 and 0 <= self.return_lambda <= 1 and 0 < self.tau <= 1):
93 raise ValueError("Use gamma in [0, 1), return_lambda in [0, 1], and tau in (0, 1].")
94 limits = np.finfo(np.float32)
95 for name in ("world_learning_rate", "actor_learning_rate", "critic_learning_rate", "multiplier_learning_rate",
96 "delta", "huber_scale", "lambda_scale", "gradient_clip"):
97 if not limits.tiny <= getattr(self, name) <= limits.max:
98 raise ValueError(f"{name} must be positive and representable as a normal float32.")
99 for name in ("free_nats", "entropy_scale"):
100 if not 0 <= getattr(self, name) <= limits.max:
101 raise ValueError(f"{name} must be nonnegative and representable in float32.")
102
103
104
105@dataclass(frozen=True)
107 """Replay transitions count sampled rows, including repeats across windows."""
108
109 replay_transitions: int = 0
110 world_model_updates: int = 0
111 imagined_steps: int = 0
112 successor_feature_updates: int = 0
113 multiplier_updates: int = 0
114
115
116
118 """Create a fresh session with :meth:`QDACMBPolicy.new_episode` at each reset.
119
120 Call act once per observation and apply the returned action. The
121 session propagates the latent state with that action as it waits for
122 the next observation. Separate sessions can run independently.
123 """
124
125 def __init__(self, policy, generator):
126 self._policy, self._generator = policy, generator
127 self._recurrent = policy._rssm.zero()
128 self.steps = 0
129
130 @torch.no_grad()
131 def _act(self, observation, normalized_goal, deterministic):
132 policy = self._policy
133 obs = policy._actor._tensor(observation)
134 goal = policy._actor._tensor(normalized_goal)
135 posterior = policy._rssm.posterior_probs(self._recurrent, obs)
136 latent = policy._rssm.draw(posterior, self._generator, deterministic=deterministic)
137 inputs = torch.cat((policy._rssm.flatten(self._recurrent, latent), goal), -1)
138 action = policy._actor._draw(inputs, deterministic, self._generator)[0]
139 applied = policy._actor._tensor(policy._actor._encode(action))
140 self._recurrent = policy._rssm.transition(self._recurrent, latent, applied)
141 self.steps += 1
142 return action
143
144
145 def act(self, observation, skill, deterministic=True):
146 """Advance the session using the selected continuous action."""
147 policy = self._policy
148 return self._act(policy._observation(observation), policy._domain.normalize(skill, goal=True), deterministic)
149
150
151
153 """Hold the policy weights, physical skill bounds, and observation and action layouts.
154
155 The actor uses a recurrent session because the current latent state
156 depends on previous actions. Its saved representation contains the
157 latent model and squashed Gaussian actor weights.
158
159 :param observation_space: Gymnasium Box containing the raw numeric observation.
160 :param action_space: Finite floating-point Gymnasium Box.
161 :param skill_bounds: Physical bounds for the desired behaviour coordinates.
162 :param policy: Optional PolicyConfig for the latent-space actor.
163 :param world: Optional QDACMBWorldConfig for recurrent inference.
164 :param seed: Initialization seed and default seed for new sessions.
165 :param device: Torch CPU or CUDA device.
166 """
167
168 _kind = "qdac-mb-recurrent"
169
170 def __init__(self, observation_space, action_space, skill_bounds, *, policy=None, world=None,
171 seed=0, device="cpu"):
172 world = QDACMBWorldConfig() if world is None else world
173 if not isinstance(world, QDACMBWorldConfig):
174 raise TypeError("world must be a QDACMBWorldConfig.")
175 self._initialize(_observation_shape(observation_space), _BoxLayout.from_space(action_space),
176 _DescriptorDomain(skill_bounds), PolicyConfig() if policy is None else policy,
177 world, _integer(seed, "seed", 0), device)
178
179 def _initialize(self, shape, actions, domain, policy, world, seed, device):
180 self._obs_shape, self._actions, self._domain = shape, actions, domain
181 self._episode_seed = seed
182 rssm_rng, actor_rng = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(2))
183 self._actor = SACPolicy._from_layout((world.state_size + len(domain.bounds),), actions, policy,
184 _seed(actor_rng), device, stochastic=False)
185 self._rssm = _RSSM(prod(shape), prod(actions.shape), world, _seed(rssm_rng), self.device)
186
187 @property
188 def skill_bounds(self):
189 """Return immutable physical skill intervals."""
190 return self._domain.bounds
191
192 @property
193 def device(self):
194 """Return the policy's Torch device."""
195 return self._actor.device
196
197 def _observation(self, observation):
198 return _flatten_observation(observation, self._obs_shape)
199
200 def _parameters(self):
201 return (*self._rssm.parameters(), *self._actor._trainable_parameters())
202
203
206 def new_episode(self, *, seed=None):
207 """Return an inference session for a freshly reset environment."""
208 seed = self._episode_seed if seed is None else _integer(seed, "seed", 0)
209 generator = torch.Generator(device=self.device).manual_seed(seed)
210 return QDACMBSession(self, generator)
211
212
213 def save(self, path):
214 """Export the policy independently of the trainer and simulator."""
215 metadata = _actor_metadata(self._actor, self._kind, self._obs_shape)
216 metadata.update(skill_bounds=self.skill_bounds, world=asdict(self._rssm.config))
217 weights = nn.utils.parameters_to_vector(self._parameters()).detach().cpu().numpy()
218 _save_actor(path, metadata, weights)
219
220
221 @classmethod
222 def load(cls, path, *, device="cpu", seed=0):
223 """Restore the actor and latent dynamics with a default seed for new sessions."""
224 metadata, weights, shape, actions, config = _load_actor_layout(path, cls._kind)
225 policy = cls.__new__(cls)
226 policy._initialize(shape, actions, _DescriptorDomain(metadata["skill_bounds"]), config,
227 QDACMBWorldConfig(**metadata["world"]), _integer(seed, "seed", 0), device)
228 parameters = policy._parameters()
229 values = np.array(weights, dtype=np.float32, copy=True)
230 if values.shape != (sum(parameter.numel() for parameter in parameters),) or not np.isfinite(values).all():
231 raise ValueError("The recurrent policy contains invalid parameters.")
232 with torch.no_grad():
233 nn.utils.vector_to_parameters(policy._actor._tensor(values), parameters)
234 return policy
235
236
237def _lambda_returns(outcomes, discounts, bootstrap, mix):
238 """Use time-first arrays. Bootstrap[i] is the value at the successor of i."""
239 shape = discounts.shape + (1,) * (outcomes.ndim - discounts.ndim)
240 discounts = discounts.reshape(shape)
241 carry = bootstrap[-1]
242 returns = []
243 for outcome, discount, successor in zip(outcomes.flip(0), discounts.flip(0), bootstrap.flip(0), strict=True):
244 carry = outcome + discount * ((1 - mix) * successor + mix * carry)
245 returns.append(carry)
246 return torch.stack(returns[::-1])
247
248
250 """Fit real dynamics, then optimize skills on trajectories through the frozen model."""
251
252 def __init__(self, policy, config, seed, counts, sample_skill):
253 self.policy, self.config, self.counts, self.sample_skill = policy, config, counts, sample_skill
254 self._world_rng, self._prior_rng, init = map(np.random.default_rng, np.random.SeedSequence(seed).spawn(3))
255 self._torch_rng = torch.Generator(device=policy.device).manual_seed(_seed(init))
256 obs_size, action_size = prod(policy._obs_shape), prod(policy._actions.shape)
257 goal_size = len(policy.skill_bounds)
258 self.replay = _SequenceReplay(config.replay_capacity, obs_size, action_size, goal_size)
259 self.world = _WorldModel(policy._rssm, obs_size, action_size, goal_size, _seed(init), policy.device)
260 inputs = config.world.state_size + goal_size
261 widths = PolicyConfig(config.critic_hidden_sizes)
262 self.reward = _scalar_head(inputs, widths, init, policy.device)
263 self.successor = _mlp(inputs, goal_size, widths, _seed(init), policy.device, nn.SiLU)
264 self.multiplier = _mlp(inputs, 1, widths, _seed(init), policy.device, nn.SiLU)
265 self.reward_target = deepcopy(self.reward).requires_grad_(False)
266 self.successor_target = deepcopy(self.successor).requires_grad_(False)
267 self._world_opt = torch.optim.Adam(self.world.parameters(), lr=config.world_learning_rate)
268 self._actor_opt = torch.optim.Adam(policy._actor._trainable_parameters(), lr=config.actor_learning_rate)
269 self._value_opt = torch.optim.Adam(self.reward.parameters(), lr=config.critic_learning_rate)
270 self._successor_opt = torch.optim.Adam(self.successor.parameters(), lr=config.critic_learning_rate)
271 self._multiplier_opt = torch.optim.Adam(self.multiplier.parameters(), lr=config.multiplier_learning_rate)
272
273 def ready(self, steps):
274 config = self.config
275 return steps >= config.learning_starts and steps % config.train_every == 0 and (
276 self.replay.size >= config.sequence_length)
277
278 def record(self, observation, action, reward, successor, terminated, feature, first):
279 self.replay.add(observation, self.policy._actor._encode(action), reward, successor, terminated,
280 feature=feature, start=first)
281
282 def _step(self, name, optimizer, loss):
283 if not torch.isfinite(loss):
284 raise ValueError(f"QDAC-MB produced nonfinite {name} loss.")
285 optimizer.zero_grad(set_to_none=True)
286 loss.backward()
287 parameters = [parameter for group in optimizer.param_groups for parameter in group["params"]]
288 nn.utils.clip_grad_norm_(parameters, self.config.gradient_clip, error_if_nonfinite=True)
289 optimizer.step()
290 self.counts[name + "_updates"] += 1
291 self.counts["optimizer_steps"] += 1
292
293 def _imagine(self, recurrent, latent, skill):
294 config, rssm, actor = self.config, self.policy._rssm, self.policy._actor
295 states, actions, densities = [], [], []
296 for _ in range(config.imagination_horizon):
297 state = rssm.flatten(recurrent, latent)
298 action, log_prob = actor._sample_actions(torch.cat((state, skill), -1), self._torch_rng)
299 states.append(state)
300 actions.append(action)
301 densities.append(log_prob)
302 recurrent = rssm.transition(recurrent, latent, action)
303 latent = rssm.draw(rssm.prior_probs(recurrent), self._torch_rng)
304 trajectory = torch.stack(states)
305 successor = torch.cat((trajectory[1:], rssm.flatten(recurrent, latent).unsqueeze(0)))
306 goals = skill.expand(len(trajectory), -1, -1)
307 current = torch.cat((trajectory, goals), -1)
308 following = torch.cat((successor, goals), -1)
309 self.counts["imagined_steps"] += len(trajectory) * len(skill)
310 reward_logits, features, cont_logits = self.world.predict(trajectory, torch.stack(actions))
311 discounts = config.gamma * cont_logits.sigmoid()
312 rewards = _lambda_returns(_symlog_mean(reward_logits), discounts, _symlog_mean(self.reward_target(following)),
313 config.return_lambda)
314 successors = _lambda_returns(features, discounts, self.successor_target(following), config.return_lambda)
315 weights = torch.cat((torch.ones_like(discounts[:1]), discounts[:-1].detach().cumprod(0)))
316 return current, rewards, successors, goals, weights, torch.stack(densities)
317
318 def _actor_step(self, recurrent, latent, skill):
319 config = self.config
320 self.world.requires_grad_(False)
321 try:
322 current, rewards, successors, goals, weights, log_prob = self._imagine(recurrent, latent, skill)
323 with torch.no_grad():
324 multiplier = self.multiplier(current).squeeze(-1).sigmoid()
325 error = (1 - config.gamma) * successors - goals
326 loss = (config.entropy_scale * log_prob - (1 - multiplier) * rewards
327 + config.lambda_scale * multiplier * _pseudo_huber(error, config.huber_scale))
328 self._step("actor", self._actor_opt, (loss * weights).sum() / weights.sum())
329 finally:
330 self.world.requires_grad_(True)
331 return current.detach(), rewards.detach(), successors.detach(), error.detach(), weights
332
333 def update(self):
334 config = self.config
335 batch = self.replay.windows(config.batch_size, config.sequence_length, self._world_rng, self.policy.device)
336 self.counts["replay_transitions"] += config.batch_size * config.sequence_length
337 model_loss, h, z = self.world.loss(batch, self._torch_rng, config.free_nats)
338 self._step("world_model", self._world_opt, model_loss)
339 rows = torch.as_tensor(self._prior_rng.integers(len(h), size=config.imagination_batch_size), device=h.device)
340 skills = np.stack([self.sample_skill(self._prior_rng) for _ in range(config.imagination_batch_size)])
341 skill = self.policy._actor._tensor(skills)
342 current, rewards, successors, error, weights = self._actor_step(h[rows], z[rows], skill)
343
344 logit = self.multiplier(current).squeeze(-1)
345 violated = (torch.linalg.vector_norm(error, dim=-1) >= config.delta).to(logit.dtype)
346 multiplier_loss = F.binary_cross_entropy_with_logits(logit, violated, reduction="none")
347 value_loss = _symlog_loss(self.reward(current), rewards)
348 sf_loss = (self.successor(current) - successors).square().mean(-1)
349 for name, optimizer, loss in (("critic", self._value_opt, value_loss),
350 ("successor_feature", self._successor_opt, sf_loss),
351 ("multiplier", self._multiplier_opt, multiplier_loss)):
352 self._step(name, optimizer, (loss * weights).sum() / weights.sum())
353 _polyak(self.reward, self.reward_target, config.tau)
354 _polyak(self.successor, self.successor_target, config.tau)
355
356
357
359 """Implement QDAC-MB for numeric Box observations and continuous Box actions.
360
361 Use the same physical skill bounds and pre-action feature callback
362 as model-free QDAC. This vector-state adaptation uses a categorical
363 GRU world model, prediction of reward, features and continuation,
364 and pathwise actor updates through imagined lambda returns. It uses
365 the standard QDpy continuous-action layout and an episode session.
366
367 :param env_factory: Callable returning a fresh Gymnasium environment.
368 :param feature: Callable returning a feature vector from observation, action and info.
369 :param skill_bounds: Ordered physical bounds for each feature coordinate.
370 :param skill_sampler: Optional function of a NumPy Generator returning a desired skill.
371 :param policy: Optional PolicyConfig with the latent actor's widths.
372 :param config: Optional QDACMBConfig controlling real and imagined work.
373 :param max_episode_steps: External time limit for environment interactions.
374 :param seed: Nonnegative seed for initialization, replay, goals and actions.
375 :param device: Torch CPU or CUDA device.
376 """
377
378 _config_type = QDACMBConfig
379 _stats_type = QDACMBStats
380
381 def _make_policy(self, env, policy, seed, device):
382 return QDACMBPolicy(env.observation_space, env.action_space, self._domain.bounds,
383 policy=policy, world=self.config.world, seed=seed, device=device)
384
385 def _make_learner(self, seed):
386 return _ModelLearner(self.policy, self.config, seed, self._counts, self._sample_skill)
387
388 @property
389 def stats(self):
390 """Return real training steps, sampled replay rows, imagined steps, and updates."""
391 return self._stats_type(**self._counts, replay_size=self._learner.replay.size)
392
393 def _start_episode(self):
394 return self._sample_skill(self._skill_rng), QDACMBSession(self.policy, self._rollout_rng)
395
396 def _action(self, observation, context):
397 goal, session = context
398 return session._act(observation, goal, False)
399
400 def _record(self, observation, action, reward, successor, terminated, truncated, feature, context):
401 _, session = context
402 self._learner.record(observation, action, reward, successor, terminated, feature, session.steps == 1)
Dimensions of the vector-observation recurrent state-space model.
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
Train a single goal-conditioned policy with model-free QDAC.
Definition qdac.py:261
Specify work budgets and optimization settings for QDAC-MB.
Definition qdac_mb.py:32
QDACMBWorldConfig world
Definition qdac_mb.py:59
Numeric policy artifact with a recurrent observation model and a latent actor.
Definition qdac_mb.py:152
new_episode(self, *, seed=None)
Start an independent recurrent state and stochastic action stream.
Definition qdac_mb.py:206
_initialize(self, shape, actions, domain, policy, world, seed, device)
Definition qdac_mb.py:179
load(cls, path, *, device="cpu", seed=0)
Load a recurrent policy without a simulator, replay, or optimizer.
Definition qdac_mb.py:222
save(self, path)
Save model layout, bounds and inference weights in a numeric NPZ.
Definition qdac_mb.py:213
Maintain one policy belief state for an inference episode.
Definition qdac_mb.py:117
_act(self, observation, normalized_goal, deterministic)
Definition qdac_mb.py:131
act(self, observation, skill, deterministic=True)
Produce a Box action from the latest observation and physical skill.
Definition qdac_mb.py:145
Cumulative real and imagined work in a model-based QDAC run.
Definition qdac_mb.py:106
Train a recurrent skill-conditioned policy with real replay and imagined trajectories.
Definition qdac_mb.py:358
_actor_step(self, recurrent, latent, skill)
Definition qdac_mb.py:318
_imagine(self, recurrent, latent, skill)
Definition qdac_mb.py:293
_step(self, name, optimizer, loss)
Definition qdac_mb.py:282
Cumulative optimizer, offspring, and replay counts for off-policy learners.
Definition td3.py:76