QDpy
Loading...
Searching...
No Matches
diveoff.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""PyTorch DiveOff with a bounded continuous actor and no simulator during training."""
7
8from copy import deepcopy
9from dataclasses import dataclass
10from math import log, pi, prod
11
12import numpy as np
13import torch
14from torch import nn
15from torch.nn import functional as F
16
17from .policy import (PolicyConfig, _BoxLayout, _flatten_observation, _integer, _mlp,
18 _observation_shape, _save_actor, _squashed_log_prob)
19from .rollout import _seed
20from .sac import SACPolicy, _actor_metadata, _load_actor_layout
21from .td3 import _Replay, _checked_step, _critic, _polyak, _twin_critics
22
23__all__ = ["DiveOff", "DiveOffConfig", "DiveOffPolicy", "DiveOffStats"]
24
25_FLOAT_MAX = np.finfo(np.float32).max
26
27
28
29@dataclass(frozen=True)
31 """Set latent dimension, optimization schedule, and model widths.
32
33 :param latent_size: Number of coordinates of the standard-normal skill prior.
34 :param batch_size: Number of logged transitions in a sampled minibatch.
35 :param pretrain_updates: Unweighted VAE updates before the main loop.
36 :param advantage_samples: Number of latent draws per transition in the policy update.
37 :param policy_delay: Number of critic updates between policy and representation updates.
38 :param gamma: Bellman discount.
39 :param tau: Polyak fraction of critic weights copied to targets after each critic update.
40 :param policy_temperature: Advantage temperature in the actor likelihood and weighted VAE.
41 :param posterior_temperature: Advantage temperature in the posterior update.
42 :param max_weight: Upper clip for unnormalized exponential advantage weights.
43 :param information_weight: Weight of the latent recovery objective. Zero gives an ablation.
44 :param reconstruction_std: Fixed Gaussian likelihood scale for reconstruction.
45 :param actor_learning_rate: Adam learning rate for the weighted actor update.
46 :param critic_learning_rate: Adam learning rate for joint twin-critic updates.
47 :param representation_learning_rate: Adam rate for the encoder and decoder.
48 :param information_learning_rate: Separate Adam rate for the actor's latent recovery update.
49 :param critic_hidden_sizes: ReLU widths of both independent critics.
50 :param representation_hidden_sizes: ReLU widths of the encoder and decoder.
51 """
52
53 latent_size: int = 2
54 batch_size: int = 128
55 pretrain_updates: int = 128
56 advantage_samples: int = 4
57 policy_delay: int = 2
58 gamma: float = .99
59 tau: float = .005
60 policy_temperature: float = 1.
61 posterior_temperature: float = 1.
62 max_weight: float = 20.
63 information_weight: float = .2
64 reconstruction_std: float = .35
65 actor_learning_rate: float = 3e-4
66 critic_learning_rate: float = 3e-4
67 representation_learning_rate: float = 3e-4
68 information_learning_rate: float = 1e-4
69 critic_hidden_sizes: tuple[int, ...] = (64, 64)
70 representation_hidden_sizes: tuple[int, ...] = (64, 64)
71
72 def __post_init__(self):
73 for name in ("latent_size", "batch_size", "advantage_samples", "policy_delay"):
74 object.__setattr__(self, name, _integer(getattr(self, name), name))
75 object.__setattr__(self, "pretrain_updates", _integer(self.pretrain_updates, "pretrain_updates", 0))
76 for name in ("critic_hidden_sizes", "representation_hidden_sizes"):
77 object.__setattr__(self, name, PolicyConfig(getattr(self, name)).hidden_sizes)
78 for name in ("policy_temperature", "posterior_temperature", "max_weight", "reconstruction_std",
79 "actor_learning_rate", "critic_learning_rate", "representation_learning_rate",
80 "information_learning_rate"):
81 if not np.finfo(np.float32).tiny <= getattr(self, name) <= _FLOAT_MAX:
82 raise ValueError(f"{name} must be positive and representable as a normal float32.")
83 if not (0. <= self.gamma < 1. and 0. < self.tau <= 1. and 0. <= self.information_weight <= _FLOAT_MAX):
84 raise ValueError("Use gamma in [0, 1), tau in (0, 1], and a finite nonnegative information weight.")
85
86
87
89 """Select bounded Box actions from an observation and a standard-normal skill code."""
90
91 def __init__(self, observation_space, action_space, latent_size, *, config=None, seed=0, device="cpu"):
92 self._initialize(_observation_shape(observation_space), _BoxLayout.from_space(action_space),
93 latent_size, PolicyConfig() if config is None else config, seed, device)
94
95 def _initialize(self, shape, actions, latent_size, config, seed, device):
96 self._shape, self._actions = shape, actions
97 self._latent_size = _integer(latent_size, "latent_size")
98 self._model = SACPolicy._from_layout((prod(shape) + self._latent_size,), actions, config,
99 seed, device, stochastic=False)
100
101 @property
102 def latent_size(self):
103 """Return the number of coordinates expected by act()."""
104 return self._latent_size
105
106
107 def act(self, observation, latent, deterministic=True):
108 """Return an action with the environment's original shape, bounds, and dtype."""
109 obs = _flatten_observation(observation, self._shape)
110 code = np.asarray(latent, dtype=float)
111 if code.shape != (self._latent_size,) or not np.all(np.abs(code) <= _FLOAT_MAX):
112 raise ValueError(f"Supply a finite latent vector of length {self._latent_size}.")
113 inputs = np.concatenate((obs, code.astype(np.float32)))
114 return self._model._draw(inputs, deterministic, self._model._rng)[0]
115
116
117 def save(self, path):
118 """Write a versioned numeric NPZ for independent inference."""
119 metadata = _actor_metadata(self._model, "diveoff", self._shape)
120 metadata["latent_size"] = self._latent_size
121 _save_actor(path, metadata, self._model._parameters())
122
123
124 @classmethod
125 def load(cls, path, *, device="cpu", seed=0):
126 """Load a numeric policy with a fresh inference generator."""
127 metadata, parameters, shape, actions, config = _load_actor_layout(path, "diveoff")
128 policy = cls.__new__(cls)
129 policy._initialize(shape, actions, metadata["latent_size"], config, seed, device)
130 policy._model._set_parameters(parameters)
131 return policy
132
133
134
135@dataclass(frozen=True)
137 """Count offline work without charging an environment interaction."""
138
139 transitions: int
140 pretraining_updates: int = 0
141 critic_updates: int = 0
142 actor_updates: int = 0
143 representation_updates: int = 0
144 information_updates: int = 0
145
146
147def _normal_logp(values, mean, log_std):
148 return (-.5 * (((values - mean) * (-log_std).exp()).square() + log(2 * pi)) - log_std).sum(dim=-1)
149
150
151def _advantage_weights(advantages, temperature, maximum):
152 return (advantages / temperature).clamp(min=-80., max=log(maximum)).exp()
153
154
155def _step(loss, *optimizers):
156 if not torch.isfinite(loss):
157 raise ValueError("DiveOff produced a nonfinite training loss.")
158 for optimizer in optimizers:
159 optimizer.zero_grad(set_to_none=True)
160 loss.backward()
161 for optimizer in optimizers:
162 _checked_step(optimizer)
163
164
165def _fixed_log(policy, observations, actions, rewards, next_observations, terminated):
166 observations, actions, rewards, successors = (np.asarray(values, dtype=float) for values in (
167 observations, actions, rewards, next_observations))
168 if not rewards.ndim == 1 or not len(rewards):
169 raise ValueError("Provide one reward for each of a nonempty set of transitions.")
170 count = len(rewards)
171 terminals = np.asarray(terminated)
172 model = policy._model
173 if (observations.shape != (count, *policy._shape) or successors.shape != observations.shape
174 or actions.shape != (count, *policy._actions.shape) or terminals.shape != (count,)
175 or not np.all((terminals == 0) | (terminals == 1))
176 or not all(np.all(np.abs(array) <= _FLOAT_MAX) for array in (observations, successors, rewards))):
177 raise ValueError("Provide aligned finite transition arrays and Boolean termination flags.")
178 flattened = actions.reshape(count, -1)
179 if not np.all((flattened >= model._low) & (flattened <= model._high)):
180 raise ValueError("Logged actions must be finite and inside the physical Box bounds.")
181 replay = _Replay(count, prod(policy._shape), prod(policy._actions.shape))
182 replay.observations[:] = observations.reshape(count, -1)
183 replay.next_observations[:] = successors.reshape(count, -1)
184 replay.actions[:] = model._encode_actions(flattened)
185 replay.rewards[:] = rewards
186 replay.terminated[:] = terminals
187 replay.size = count
188 return replay
189
190
191
193 """Learn several ways to solve a single continuous-control task from a static log.
194
195 Pretrain a Gaussian VAE on state-action pairs. Train twin critics
196 with a shared skill code on both sides of each Bellman update.
197 Alternate advantage-weighted actor likelihood with a posterior
198 update and advantage-weighted VAE training. Mutual information
199 encourages recoverable skills from sampled policy actions.
200
201 :param observation_space: Fixed numeric Gymnasium Box.
202 :param action_space: Bounded floating-point Gymnasium Box.
203 :param observations: State array with one row per transition.
204 :param actions: Logged physical actions in the same row order.
205 :param rewards: One finite task reward per transition.
206 :param next_observations: Actual successor states, before any reset.
207 :param terminated: One Boolean per transition. Time limits can bootstrap.
208 :param config: DiveOffConfig for offline training settings.
209 :param policy: PolicyConfig for the latent-conditioned actor.
210 :param seed: Seed for networks and minibatch or latent draws.
211 :param device: Torch device. CPU is the default.
212 """
213
214 def __init__(self, observation_space, action_space, *, observations, actions, rewards, next_observations,
215 terminated, config=None, policy=None, seed=0, device="cpu"):
216 self.config = DiveOffConfig() if config is None else config
217 if not isinstance(self.config, DiveOffConfig):
218 raise TypeError("config must be a DiveOffConfig.")
219 self._rng = np.random.default_rng(_integer(seed, "seed", 0))
220 settings = self.config
221 self._policy = DiveOffPolicy(observation_space, action_space, settings.latent_size, config=policy,
222 seed=_seed(self._rng), device=device)
223 self._actor = self._policy._model
224 self._replay = _fixed_log(self._policy, observations, actions, rewards, next_observations, terminated)
225 self._torch_rng = torch.Generator(device=self._actor.device).manual_seed(_seed(self._rng))
226 width = prod(self._policy._shape) + prod(self._policy._actions.shape)
227 architecture = PolicyConfig(settings.representation_hidden_sizes)
228 self._encoder = _mlp(width, 2 * settings.latent_size, architecture, _seed(self._rng), self._actor.device,
229 nn.ReLU)
230 self._decoder = _mlp(settings.latent_size, width, architecture, _seed(self._rng), self._actor.device, nn.ReLU)
231 self._critics = _twin_critics(self._actor, settings, self._rng, self._rng)
232 self._targets = deepcopy(self._critics).requires_grad_(False)
233 self._critic_optimizer = torch.optim.Adam(self._critics.parameters(), lr=settings.critic_learning_rate)
234 self._actor_optimizer = torch.optim.Adam(self._actor._trainable_parameters(), lr=settings.actor_learning_rate)
235 self._rep_optimizer = torch.optim.Adam((*self._encoder.parameters(), *self._decoder.parameters()),
236 lr=settings.representation_learning_rate)
237 self._info_optimizer = (torch.optim.Adam(self._actor._trainable_parameters(),
238 lr=settings.information_learning_rate)
239 if settings.information_weight else None)
240 self._updates = dict(pretraining_updates=0, critic_updates=0, actor_updates=0,
241 representation_updates=0, information_updates=0)
242
243 @property
244 def stats(self):
245 """Return offline training and log counts."""
246 return DiveOffStats(self._replay.size, **self._updates)
247
248
249 def policy(self, *, device=None, seed=0):
250 """Return an inference actor that can be exported without the learner."""
251 result = DiveOffPolicy.__new__(DiveOffPolicy)
252 actor = self._actor
253 result._initialize(self._policy._shape, self._policy._actions, self.config.latent_size,
254 actor.config, seed, actor.device if device is None else device)
255 result._model._set_parameters(actor._parameters())
256 return result
257
258 def _sample(self, shape):
259 return torch.randn(shape, generator=self._torch_rng, device=self._actor.device)
260
261 def _posterior(self, rows):
262 mean, log_std = self._encoder(rows).chunk(2, dim=-1)
263 return mean, log_std.clamp(-8., 2.)
264
265 def _vae_loss(self, rows, mean, log_std):
266 latent = mean + log_std.exp() * self._sample(mean.shape)
267 residual = (self._decoder(latent) - rows) / self.config.reconstruction_std
268 kl = .5 * (mean.square() + (2. * log_std).exp() - 1. - 2. * log_std)
269 return .5 * residual.square().sum(dim=-1) + kl.sum(dim=-1)
270
271 def _batch(self):
272 return self._replay.sample(self.config.batch_size, self._rng, self._actor.device)
273
274 @staticmethod
275 def _minimum(critics, inputs, actions):
276 first, second = (_critic(network, inputs, actions) for network in critics)
277 return torch.minimum(first, second)
278
279 def _update_critics(self, obs, actions, rewards, next_obs, terminated, joint):
280 with torch.no_grad():
281 mean, log_std = self._posterior(joint)
282 latent = mean + log_std.exp() * self._sample(mean.shape)
283 inputs, future = torch.cat((obs, latent), -1), torch.cat((next_obs, latent), -1)
284 next_actions, _ = self._actor._sample_actions(future, self._torch_rng)
285 value = self._minimum(self._targets, future, next_actions)
286 target = rewards + self.config.gamma * value.masked_fill(terminated, 0.)
287 loss = sum(F.mse_loss(_critic(network, inputs, actions), target) for network in self._critics)
288 _step(loss, self._critic_optimizer)
289 _polyak(self._critics, self._targets, self.config.tau)
290 self._updates["critic_updates"] += 1
291
292 def _update_behavior(self, obs, actions, joint):
293 settings, k = self.config, self.config.advantage_samples
294 with torch.no_grad():
295 q_mean, q_log_std = self._posterior(joint)
296 latents = q_mean[:, None] + q_log_std[:, None].exp() * self._sample((len(obs), k, settings.latent_size))
297 inputs = torch.cat((obs[:, None].expand(-1, k, -1), latents), -1)
298 repeated = actions[:, None].expand(-1, k, -1)
299 sampled_actions, _ = self._actor._sample_actions(inputs, self._torch_rng)
300 advantage = (self._minimum(self._critics, inputs, repeated)
301 - self._minimum(self._critics, inputs, sampled_actions))
302 if not torch.isfinite(advantage).all():
303 raise ValueError("DiveOff produced nonfinite advantages.")
304 weights = _advantage_weights(advantage, settings.policy_temperature, settings.max_weight)
305 posterior_logits = (advantage - advantage.max(dim=1, keepdim=True).values) / settings.posterior_temperature
306 posterior_weights = posterior_logits.softmax(dim=1)
307 before_tanh = torch.atanh(repeated.clamp(-1. + 1e-6, 1. - 1e-6))
308
309 mean, scale = self._actor._network(inputs).chunk(2, dim=-1)
310 log_probability = _squashed_log_prob(mean, (F.softplus(scale) + .001).log(), before_tanh, 0.)
311 _step(-(weights * log_probability).mean(), self._actor_optimizer)
312 self._updates["actor_updates"] += 1
313
314 q_mean, q_log_std = self._posterior(joint)
315 posterior = _normal_logp(latents, q_mean[:, None], q_log_std[:, None])
316 loss = (self._vae_loss(joint, q_mean, q_log_std) * weights.mean(dim=1)
317 - (posterior_weights * posterior).sum(dim=1)).mean()
318 if self._info_optimizer is None:
319 _step(loss, self._rep_optimizer)
320 else:
321 prior = self._sample(q_mean.shape)
322 generated, _ = self._actor._sample_actions(torch.cat((obs, prior), -1), self._torch_rng)
323 inferred_mean, inferred_log_std = self._posterior(torch.cat((obs, generated), -1))
324 information_loss = -_normal_logp(prior, inferred_mean, inferred_log_std).mean()
325 _step(loss + settings.information_weight * information_loss, self._rep_optimizer, self._info_optimizer)
326 self._updates["information_updates"] += 1
327 self._updates["representation_updates"] += 1
328
329
330 def train(self, updates):
331 """Train on the fixed log only. Successive calls retain all optimizer and RNG state."""
332 updates = _integer(updates, "updates", 0)
333 while self._updates["pretraining_updates"] < self.config.pretrain_updates:
334 obs, action, *_ = self._batch()
335 joint = torch.cat((obs, action), -1)
336 mean, log_std = self._posterior(joint)
337 _step(self._vae_loss(joint, mean, log_std).mean(), self._rep_optimizer)
338 self._updates["pretraining_updates"] += 1
339 for _ in range(updates):
340 obs, actions, rewards, successors, terminated = self._batch()
341 joint = torch.cat((obs, actions), -1)
342 self._update_critics(obs, actions, rewards, successors, terminated, joint)
343 if self._updates["critic_updates"] % self.config.policy_delay == 0:
344 self._update_behavior(obs, actions, joint)
345 return self.stats
Configure offline VAE pretraining, critic learning, and the two advantage temperatures.
Definition diveoff.py:30
Portable conditioned Gaussian policy using a latent vector directly as input.
Definition diveoff.py:88
save(self, path)
Save only policy weights, shapes, bounds, and the latent size.
Definition diveoff.py:117
load(cls, path, *, device="cpu", seed=0)
Restore an exported actor without offline data or training networks.
Definition diveoff.py:125
act(self, observation, latent, deterministic=True)
Sample an action or use the squashed mean at one chosen latent code.
Definition diveoff.py:107
_initialize(self, shape, actions, latent_size, config, seed, device)
Definition diveoff.py:95
Report fixed-log size and actual optimizer steps by phase.
Definition diveoff.py:136
Discover useful latent skills by alternating offline critic, actor, and representation updates.
Definition diveoff.py:192
_posterior(self, rows)
Definition diveoff.py:261
policy(self, *, device=None, seed=0)
Copy an independently usable conditioned actor.
Definition diveoff.py:249
_vae_loss(self, rows, mean, log_std)
Definition diveoff.py:265
_minimum(critics, inputs, actions)
Definition diveoff.py:275
_sample(self, shape)
Definition diveoff.py:258
_update_critics(self, obs, actions, rewards, next_obs, terminated, joint)
Definition diveoff.py:279
train(self, updates)
Complete the configured VAE warm-up and run additional critic iterations.
Definition diveoff.py:330
_update_behavior(self, obs, actions, joint)
Definition diveoff.py:292
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36