QDpy
Loading...
Searching...
No Matches
_qdac_world.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Replay and a small Dreamer-style latent model for continuous control."""
7
8from dataclasses import dataclass
9
10import numpy as np
11import torch
12from torch import nn
13from torch.nn import functional as F
14
15from .policy import PolicyConfig, _integer, _mlp
16from .rollout import _seed
17from .td3 import _Replay
18
19# A fixed support for symlog reward and value predictions.
20_SYMLOG_LIMIT = 20.
21_SYMLOG_BINS = 101
22
23
24
25@dataclass(frozen=True)
27 """Size the GRU, independent categorical variables, and prediction networks.
28
29 :param recurrent_size: Number of deterministic recurrent units.
30 :param latent_variables: Number of independent categorical variables.
31 :param latent_classes: Number of possible classes in each variable.
32 :param hidden_size: Width of encoder and prediction layers.
33 """
34
35 recurrent_size: int = 64
36 latent_variables: int = 8
37 latent_classes: int = 8
38 hidden_size: int = 96
39
40 def __post_init__(self):
41 for key in ("recurrent_size", "latent_variables", "latent_classes", "hidden_size"):
42 object.__setattr__(self, key, _integer(getattr(self, key), key, 2 if key == "latent_classes" else 1))
43
44 @property
45 def state_size(self):
46 """Return the number of coordinates seen by each latent policy head."""
47 return self.recurrent_size + self.latent_variables * self.latent_classes
48
49
50def _symlog(value):
51 return value.sign() * value.abs().log1p()
52
53
54def _symlog_loss(logits, target):
55 """Regress scalar values with a linearly interpolated categorical target."""
56 intervals = logits.shape[-1] - 1
57 position = (_symlog(target).clamp(-_SYMLOG_LIMIT, _SYMLOG_LIMIT) + _SYMLOG_LIMIT) * (
58 intervals / (2 * _SYMLOG_LIMIT))
59 low = position.long()
60 high = (low + 1).clamp_max(intervals)
61 fraction = position - low
62 loss = -logits.log_softmax(-1)
63 first = loss.gather(-1, low.unsqueeze(-1)).squeeze(-1)
64 second = loss.gather(-1, high.unsqueeze(-1)).squeeze(-1)
65 return (1 - fraction) * first + fraction * second
66
67
68def _symlog_mean(logits):
69 support = torch.linspace(-_SYMLOG_LIMIT, _SYMLOG_LIMIT, logits.shape[-1],
70 dtype=logits.dtype, device=logits.device)
71 mean = (logits.softmax(-1) * support).sum(-1)
72 return mean.sign() * mean.abs().expm1()
73
74
75def _scalar_head(inputs, hidden, rng, device):
76 model = _mlp(inputs, _SYMLOG_BINS, hidden, _seed(rng), device, nn.SiLU)
77 with torch.no_grad():
78 model[-1].weight.zero_()
79 model[-1].bias.zero_()
80 return model
81
82
84 """Draw chronological windows from a ring and retain real reset markers."""
85
86 def __init__(self, capacity, obs_size, action_size, feature_size):
87 super().__init__(capacity, obs_size, action_size)
88 self.features = np.empty((capacity, feature_size), dtype=np.float32)
89 self.starts = np.empty(capacity, dtype=bool)
90
91 def add(self, observation, action, reward, next_observation, terminated, *, feature, start):
92 row = self.position
93 super().add(observation, action, reward, next_observation, terminated)
94 self.features[row], self.starts[row] = feature, start
95
96 def windows(self, batch_size, sequence_length, rng, device):
97 if not 0 < sequence_length <= self.size:
98 raise ValueError("The replay has too few transitions for a sequence.")
99 start = rng.integers(self.size - sequence_length + 1, size=batch_size)
100 first_available = self.position - self.size
101 rows = (first_available + start[:, None] + np.arange(sequence_length)) % self.capacity
102 return (*self.batch(rows, device), torch.as_tensor(self.features[rows], device=device),
103 torch.as_tensor(self.starts[rows], device=device))
104
105
106class _RSSM(nn.Module):
107 """Infer latents from observations and predict them from action history."""
108
109 def __init__(self, obs_size, action_size, config, seed, device):
110 super().__init__()
111 self.config = config
112 self._latent_shape = config.latent_variables, config.latent_classes
113 hidden, recurrent = config.hidden_size, config.recurrent_size
114 latent_size = config.latent_variables * config.latent_classes
115 rng = np.random.default_rng(seed)
116 widths = PolicyConfig((hidden,))
117 self.encoder = _mlp(obs_size, hidden, widths, _seed(rng), device, nn.SiLU)
118 self.posterior = _mlp(recurrent + hidden, latent_size, widths, _seed(rng), device, nn.SiLU)
119 self.prior = _mlp(recurrent, latent_size, widths, _seed(rng), device, nn.SiLU)
120 with torch.random.fork_rng(devices=[]):
121 torch.random.default_generator.manual_seed(_seed(rng))
122 self.recur = nn.GRUCell(latent_size + action_size, recurrent, device="cpu").to(device)
123
124 def zero(self, *shape):
125 weight = self.recur.weight_hh
126 return weight.new_zeros((*shape, self.config.recurrent_size))
127
128 def _probabilities(self, logits):
129 logits = logits.unflatten(-1, self._latent_shape)
130 return .99 * logits.softmax(-1) + .01 / self.config.latent_classes
131
132 def posterior_probs(self, recurrent, obs):
133 return self._probabilities(self.posterior(torch.cat((recurrent, self.encoder(_symlog(obs))), -1)))
134
135 def prior_probs(self, recurrent):
136 return self._probabilities(self.prior(recurrent))
137
138 def draw(self, probabilities, generator=None, *, deterministic=False):
139 if deterministic:
140 indices = probabilities.argmax(-1)
141 else:
142 draws = torch.multinomial(probabilities.flatten(0, -2), 1, generator=generator)
143 indices = draws.reshape(probabilities.shape[:-1])
144 hard = F.one_hot(indices, self.config.latent_classes).to(probabilities.dtype)
145 # Preserve the sampled one-hot value and pass the softmax gradient.
146 return hard + (probabilities - probabilities.detach())
147
148 @staticmethod
149 def flatten(recurrent, latent):
150 return torch.cat((recurrent, latent.flatten(-2)), -1)
151
152 def transition(self, recurrent, latent, action):
153 return self.recur(torch.cat((latent.flatten(-2), action), -1), recurrent)
154
155
156def _balanced_kl(posterior, prior, free_nats):
157 def kl(q, p):
158 return (q * (q.log() - p.log())).sum((-2, -1))
159
160 dynamics = kl(posterior.detach(), prior)
161 representation = kl(posterior, prior.detach())
162 return .5 * dynamics.clamp_min(free_nats) + .1 * representation.clamp_min(free_nats)
163
164
165class _WorldModel(nn.Module):
166 """Model successor observations and transition rewards, features, and continuation."""
167
168 def __init__(self, rssm, obs_size, action_size, feature_size, seed, device):
169 super().__init__()
170 self.rssm = rssm
171 config = rssm.config
172 state = config.state_size
173 hidden = PolicyConfig((config.hidden_size,))
174 rng = np.random.default_rng(seed)
175 self.observation = _mlp(state, obs_size, hidden, _seed(rng), device, nn.SiLU)
176 self.reward = _scalar_head(state + action_size, hidden, rng, device)
177 self.features_continue = _mlp(state + action_size, feature_size + 1, hidden, _seed(rng), device, nn.SiLU)
178
179 def predict(self, state, action):
180 transition = torch.cat((state, action), -1)
181 outcomes = self.features_continue(transition)
182 return self.reward(transition), outcomes[..., :-1], outcomes[..., -1]
183
184 def loss(self, batch, generator, free_nats):
185 obs, action, reward, next_obs, terminated, feature, start = batch
186 rssm = self.rssm
187 initial_h = rssm.zero(*obs.shape[:2])
188 initial_z = rssm.draw(rssm.posterior_probs(initial_h, obs), generator)
189 recurrent, latent = initial_h[:, 0], initial_z[:, 0]
190 anchors, successors, penalties = [], [], []
191 for step in range(obs.shape[1]):
192 reset = start[:, step]
193 recurrent = torch.where(reset[:, None], initial_h[:, step], recurrent)
194 latent = torch.where(reset[:, None, None], initial_z[:, step], latent)
195 anchors.append((recurrent, latent))
196 recurrent = rssm.transition(recurrent, latent, action[:, step])
197 prior = rssm.prior_probs(recurrent)
198 posterior = rssm.posterior_probs(recurrent, next_obs[:, step])
199 latent = rssm.draw(posterior, generator)
200 successors.append(rssm.flatten(recurrent, latent))
201 penalties.append(_balanced_kl(posterior, prior, free_nats))
202 states = torch.stack([rssm.flatten(h, z) for h, z in anchors], dim=1)
203 reward_logits, predicted_features, continuation = self.predict(states, action)
204 reconstruction = self.observation(torch.stack(successors, dim=1))
205 loss = (_symlog_loss(reward_logits, reward).mean()
206 + F.mse_loss(predicted_features, feature)
207 + F.mse_loss(reconstruction, _symlog(next_obs))
208 + F.binary_cross_entropy_with_logits(continuation, (~terminated).float())
209 + torch.stack(penalties).mean())
210 h, z = (torch.stack(parts, dim=1).flatten(0, 1).detach() for parts in zip(*anchors, strict=True))
211 return loss, h, z
Dimensions of the vector-observation recurrent state-space model.
_probabilities(self, logits)
predict(self, state, action)
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
batch(self, rows, device)
Definition td3.py:122