QDpy
Loading...
Searching...
No Matches
qdac.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Model-free QDAC (Grillotti et al., ICML 2024) for continuous actions."""
6
7from copy import deepcopy
8from dataclasses import dataclass
9from math import prod
10
11import numpy as np
12import torch
13from torch import nn
14from torch.nn import functional as F
15
16from .descriptor_policy import _DescriptorDomain
17from .policy import PolicyConfig, _BoxLayout, _flatten_observation, _integer, _mlp, _observation_shape, _save_actor
18from .rollout import _seed
19from .sac import SAC, SACConfig, SACPolicy, SACStats, _SACLearner, _actor_metadata, _load_actor_layout, _twin_loss
20from .td3 import _Replay, _polyak
21
22
23
24@dataclass(frozen=True)
26 """Extend SAC settings with the skill constraint and replay relabeling.
27
28 The default target entropy is minus half the flattened action dimension.
29 The warmup uses the untrained stochastic actor with a sampled skill.
30
31 :param delta: Constraint radius in normalized skill coordinates.
32 :param huber_scale: Smoothing scale of the actor's pseudo-Huber penalty.
33 :param lambda_scale: Weight of that penalty when the multiplier is one.
34 :param multiplier_hidden_sizes: ReLU widths of the state-skill multiplier.
35 :param multiplier_learning_rate: Adam learning rate for the multiplier.
36 :param skill_relabels: Number of randomly relabeled copies per replay batch.
37 """
38
39 delta: float = 0.01
40 huber_scale: float = 0.001
41 lambda_scale: float = 1.0
42 multiplier_hidden_sizes: tuple[int, ...] = (128, 128)
43 multiplier_learning_rate: float = 3e-4
44 skill_relabels: int = 1
45
46 def __post_init__(self):
47 super().__post_init__()
48 object.__setattr__(self, "skill_relabels", _integer(self.skill_relabels, "skill_relabels", 0))
49 widths = PolicyConfig(self.multiplier_hidden_sizes).hidden_sizes
50 object.__setattr__(self, "multiplier_hidden_sizes", widths)
51 for name in ("delta", "huber_scale", "lambda_scale", "multiplier_learning_rate"):
52 if not np.finfo(np.float32).tiny <= getattr(self, name) <= np.finfo(np.float32).max:
53 raise ValueError(f"{name} must be positive and representable as a normal float32.")
54
55
56
58 """Combine a Box observation and a desired skill to select an action.
59
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.
63
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.
70 """
71
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),
74 _DescriptorDomain(skill_bounds), PolicyConfig() if config is None else config,
75 seed, device)
76
77 def _initialize(self, shape, actions, domain, config, seed, device):
78 self._obs_shape, self._actions, self._domain = shape, actions, domain
79 self._model = SACPolicy._from_layout((prod(shape) + len(domain.bounds),), actions, config,
80 seed, device, stochastic=False)
81
82 @property
83 def skill_bounds(self):
84 """Return the original physical bounds as an immutable tuple."""
85 return self._domain.bounds
86
87 @property
88 def config(self):
89 """Return the policy architecture."""
90 return self._model.config
91
92 @property
93 def device(self):
94 """Return the actor's Torch device."""
95 return self._model.device
96
97 def _observation(self, observation):
98 return _flatten_observation(observation, self._obs_shape)
99
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]
103
104
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)
108 return self._action(self._observation(observation), goal, deterministic, self._model._rng)
109
110
111 def save(self, path):
112 """Export the conditioned actor for independent inference."""
113 metadata = _actor_metadata(self._model, "skill-conditioned-sac", self._obs_shape)
114 metadata["skill_bounds"] = self.skill_bounds
115 _save_actor(path, metadata, self._model._parameters())
116
117
118 @classmethod
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)
125 return actor
126
127
128
129@dataclass(frozen=True)
131 """Extend SAC counts with one successor-feature and one multiplier update per batch."""
132
133 successor_feature_updates: int = 0
134 multiplier_updates: int = 0
135
136
137def _measure_feature(feature, observation, action, info, domain):
138 """Evaluate the feature before step and protect the transition from mutation."""
139 values = np.asarray(feature(observation.copy(), deepcopy(action), deepcopy(dict(info))), dtype=np.float64)
140 return values, domain.normalize(values)
141
142
144 """Store pre-action features, original skills, and time-limit masks."""
145
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)
149 self.skills = np.empty_like(self.features)
150 self.truncated = np.empty(capacity, dtype=bool)
151
152 def add(self, observation, action, reward, next_observation, terminated, *, truncated, feature, skill):
153 index = self.position
154 super().add(observation, action, reward, next_observation, terminated)
155 self.features[index], self.skills[index] = feature, skill
156 self.truncated[index] = truncated and not terminated
157
158 def batch(self, rows, device):
159 return (*super().batch(rows, device), *(torch.as_tensor(field[rows], device=device) for field in
160 (self.truncated, self.features, self.skills)))
161
162
163def _successor_target(features, terminated, successors, gamma):
164 return features + gamma * successors.mean(dim=0).masked_fill(terminated[:, None], 0.)
165
166
167def _skill_error(predictions, skills, gamma):
168 return (1 - gamma) * predictions.mean(dim=0) - skills
169
170
171def _pseudo_huber(error, scale):
172 distance = torch.linalg.vector_norm(error, dim=-1)
173 # Rationalize hypot(scale, distance) - scale to preserve small penalties.
174 radius = torch.hypot(distance, torch.full_like(distance, scale))
175 return distance * (distance / radius) / (1 + scale / radius)
176
177
178def _multiplier_loss(logits, error, delta):
179 labels = (torch.linalg.vector_norm(error.detach(), dim=-1) >= delta).to(logits.dtype)
180 return F.binary_cross_entropy_with_logits(logits, labels)
181
182
184 """Learn reward, successor-feature and multiplier networks for a single actor."""
185
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)
194 widths = PolicyConfig(config.critic_hidden_sizes)
195 self.successor_features = nn.ModuleList([
196 _mlp(inputs, dimension, widths, _seed(rng), self.device, nn.ReLU) for rng in (sf_one, sf_two)
197 ])
198 self.successor_targets = deepcopy(self.successor_features).requires_grad_(False)
199 self.successor_optimizer = torch.optim.Adam(self.successor_features.parameters(), lr=config.critic_learning_rate)
200 self.multiplier = _mlp(prod(actor._obs_shape), 1, PolicyConfig(config.multiplier_hidden_sizes),
201 _seed(multiplier), self.device, nn.ReLU)
202 self.multiplier_optimizer = torch.optim.Adam(self.multiplier.parameters(), lr=config.multiplier_learning_rate)
203 self.relabel_rng, self.sample_skill = relabel_seed, sample_skill
204
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)
208
210 """Duplicate transitions with fresh skills while preserving observations, rewards and features."""
211 *transition, skills = self.replay.sample(self.config.batch_size, self.sample_rng, self.device)
212 copies = self.config.skill_relabels
213 if copies:
214 relabeled = np.stack([self.sample_skill(self.relabel_rng) for _ in range(len(skills) * copies)])
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)
218
219 @staticmethod
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])
223
224 def _multiplier_step(self, observations, skills):
225 with torch.no_grad():
226 actions, _ = self.actor._sample_actions(observations, self.noise_rng)
227 sf = self._feature_values(self.successor_features, observations, actions)
228 error = _skill_error(sf, skills, self.config.gamma)
229 loss = _multiplier_loss(self.multiplier(observations).squeeze(-1), error, self.config.delta)
230 self._update(loss, self.multiplier_optimizer, "multiplier")
231
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)
235 estimates = self._feature_values(self.successor_targets, successors, next_actions)
236 targets = _successor_target(features, terminated, estimates, self.config.gamma)
237 estimates = self._feature_values(self.successor_features, observations, actions)
238 self._update(_twin_loss(estimates, targets, truncated[:, None]),
239 self.successor_optimizer, "successor_feature")
240 _polyak(self.successor_features, self.successor_targets, self.config.tau)
241
242 def update(self):
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)
246 self._multiplier_step(observations, skills)
247 self._temperature_step(observations)
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)
254 features = self._feature_values(self.successor_features, observations, actions)
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
257 self._update(loss.mean(), self.actor_optimizer, "actor", self.actor._trainable_parameters())
258
259
260
261class QDAC(SAC):
262 """Optimize rewards and skill matching without an archive.
263
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.
270
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.
283 """
284
285 _config_type = QDACConfig
286 _stats_type = QDACStats
287
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.")
292 self._domain = _DescriptorDomain(skill_bounds)
293 self._extract_feature, self._skill_sampler = feature, skill_sampler
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)
297
298 def _make_policy(self, env, policy, seed, device):
299 return SkillConditionedPolicy(env.observation_space, env.action_space, self._domain.bounds,
300 config=policy, seed=seed, device=device)
301
302 def _make_learner(self, seed):
303 return _QDACLearner(self.policy, self.config, seed, self._counts, self._sample_skill)
304
305 def _sample_skill(self, rng):
306 if self._skill_sampler is None:
307 return rng.uniform(-1, 1, len(self._domain.bounds)).astype(np.float32)
308 return self._domain.normalize(self._skill_sampler(rng), goal=True)
309
310 def _start_episode(self):
311 return self._sample_skill(self._skill_rng)
312
313 def _action(self, observation, context):
314 return self.policy._action(observation, context, False, self._rollout_rng)
315
316 def _feature(self, observation, action, info):
317 return _measure_feature(self._extract_feature, observation.reshape(self.policy._obs_shape),
318 action, info, self._domain)[1]
319
320 def _record(self, observation, action, reward, successor, terminated, truncated, feature, context):
321 self._learner.record(observation, action, reward, successor, terminated, truncated, feature, context)
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
Replay, entropy, and constraint settings for model-free QDAC.
Definition qdac.py:25
tuple multiplier_hidden_sizes
Definition qdac.py:42
Cumulative Model-free QDAC interaction and optimizer counts.
Definition qdac.py:130
Train a single goal-conditioned policy with model-free QDAC.
Definition qdac.py:261
Bounded stochastic continuous actor conditioned on a desired behavior.
Definition qdac.py:57
_initialize(self, shape, actions, domain, config, seed, device)
Definition qdac.py:77
load(cls, path, *, device="cpu", seed=0)
Restore a conditioned actor without an environment or feature function.
Definition qdac.py:119
save(self, path)
Save the actor, physical bounds, and architecture to an NPZ file.
Definition qdac.py:111
_action(self, observation, normalized_skill, deterministic, generator)
Definition qdac.py:100
act(self, observation, skill, deterministic=True)
Select a deterministic or sampled action at a desired skill.
Definition qdac.py:105
_observation(self, observation)
Definition qdac.py:97
_feature_values(networks, observations, actions)
Definition qdac.py:220
_successor_step(self, observations, actions, successors, terminated, truncated, features)
Definition qdac.py:232
_multiplier_step(self, observations, skills)
Definition qdac.py:224
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
Train a reusable standalone Soft Actor-Critic policy.
Definition sac.py:250
_reward_step(self, observations, actions, rewards, successors, terminated, ignore=None)
Definition sac.py:222
_values(networks, observations, actions)
Definition sac.py:232
_update(self, loss, optimizer, name, parameters=None)
Definition sac.py:202
_temperature_step(self, observations)
Definition sac.py:216