31 """Set latent dimension, optimization schedule, and model widths.
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.
55 pretrain_updates: int = 128
56 advantage_samples: int = 4
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)
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.")
84 raise ValueError(
"Use gamma in [0, 1), tau in (0, 1], and a finite nonnegative information weight.")
193 """Learn several ways to solve a single continuous-control task from a static log.
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.
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.
214 def __init__(self, observation_space, action_space, *, observations, actions, rewards, next_observations,
215 terminated, config=None, policy=None, seed=0, device="cpu"):
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))
221 self.
_policy =
DiveOffPolicy(observation_space, action_space, settings.latent_size, config=policy,
222 seed=_seed(self.
_rng), device=device)
224 self.
_replay = _fixed_log(self.
_policy, observations, actions, rewards, next_observations, terminated)
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,
230 self.
_decoder = _mlp(settings.latent_size, width, architecture, _seed(self.
_rng), self.
_actor.device, nn.ReLU)
234 self.
_actor_optimizer = torch.optim.Adam(self.
_actor._trainable_parameters(), lr=settings.actor_learning_rate)
236 lr=settings.representation_learning_rate)
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)
245 """Return offline training and log counts."""
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)
254 actor.config, seed, actor.device
if device
is None else device)
255 result._model._set_parameters(actor._parameters())
258 def _sample(self, shape):
259 return torch.randn(shape, generator=self.
_torch_rng, device=self.
_actor.device)
261 def _posterior(self, rows):
262 mean, log_std = self.
_encoder(rows).chunk(2, dim=-1)
263 return mean, log_std.clamp(-8., 2.)
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)
275 def _minimum(critics, inputs, actions):
276 first, second = (_critic(network, inputs, actions)
for network
in critics)
277 return torch.minimum(first, second)
279 def _update_critics(self, obs, actions, rewards, next_obs, terminated, joint):
280 with torch.no_grad():
282 latent = mean + log_std.exp() * self.
_sample(mean.shape)
283 inputs, future = torch.cat((obs, latent), -1), torch.cat((next_obs, latent), -1)
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)
290 self.
_updates[
"critic_updates"] += 1
292 def _update_behavior(self, obs, actions, joint):
293 settings, k = self.
config, self.
config.advantage_samples
294 with torch.no_grad():
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)
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))
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.)
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()
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()
326 self.
_updates[
"information_updates"] += 1
327 self.
_updates[
"representation_updates"] += 1
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)
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: