QDpy
Loading...
Searching...
No Matches
qdt.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Quality-Diversity Transformer for offline continuous-action trajectories."""
6
7from dataclasses import asdict, dataclass
8from math import isfinite, prod
9
10import numpy as np
11import torch
12from torch import nn
13from torch.nn.utils import parameters_to_vector, vector_to_parameters
14
15from .policy import _BoxLayout, _flatten_observation, _integer, _observation_shape, _read_actor, _save_actor
16from .rollout import Episode
17
18
19
20@dataclass(frozen=True)
22 """Set a fixed context length, encoder width, attention heads, and layer count."""
23
24 context_length: int = 128
25 width: int = 64
26 heads: int = 4
27 layers: int = 2
28
29 def __post_init__(self):
30 for name in ("context_length", "width", "heads", "layers"):
31 object.__setattr__(self, name, _integer(getattr(self, name), name))
32 if self.width % self.heads:
33 raise ValueError("QDT width must be divisible by heads.")
34
35
36
37@dataclass(frozen=True)
39 """Report trajectory and transition counts, optimizer steps, and final-epoch MSE."""
40
41 episodes: int
42 transitions: int
43 updates: int
44 loss: float
45
46
47class _SequenceModel(nn.Module):
48 """Predict actions from observation tokens with a causal attention mask."""
49
50 def __init__(self, observations, actions, descriptors, config):
51 super().__init__()
52 self.embeddings = nn.ModuleList(nn.Sequential(nn.Linear(size, config.width), nn.LayerNorm(config.width))
53 for size in (descriptors, observations, actions))
54 self.times = nn.Embedding(config.context_length, config.width)
55 self.layers = nn.ModuleList(nn.TransformerEncoderLayer(config.width, config.heads,
56 dim_feedforward=4 * config.width, dropout=0., batch_first=True,
57 norm_first=True) for _ in range(config.layers))
58 self.output = nn.Sequential(nn.LayerNorm(config.width), nn.Linear(config.width, actions), nn.Tanh())
59 self.register_buffer("causal", torch.ones((3 * config.context_length,) * 2, dtype=torch.bool).triu(1),
60 persistent=False)
61
62 def forward(self, descriptors, observations, actions):
63 count = observations.shape[1]
64 goals = descriptors[:, None, :].expand(-1, count, -1)
65 tokens = torch.stack([embed(values) for embed, values in
66 zip(self.embeddings, (goals, observations, actions))], dim=2)
67 tokens = tokens + self.times.weight[:count][None, :, None, :]
68 sequence = tokens.flatten(1, 2)
69 for layer in self.layers:
70 sequence = layer(sequence, src_mask=self.causal[:3 * count, :3 * count])
71 return self.output(sequence[:, 1::3])
72
73
74
76 """Act on observations from one episode. Call reset between episodes."""
77
78 def __init__(self, model, descriptor):
79 self._model = model
80 self._descriptor = model._descriptor(descriptor)
81 self.reset()
82
83
84 def reset(self, descriptor=None):
85 """Clear observations and actions. Optionally replace the requested descriptor."""
86 if descriptor is not None:
87 self._descriptor = self._model._descriptor(descriptor)
88 self._observations, self._actions = [], []
89
90
91 @torch.no_grad()
92 def act(self, observation):
93 """Use the returned physical action verbatim before supplying the next observation."""
94 if len(self._observations) >= self._model.config.context_length:
95 raise RuntimeError("The QDT context is full. Reset or use a larger trained context.")
96 obs = _flatten_observation(observation, self._model._obs_shape)
97 observations = [*self._observations, obs]
98 actions = [*self._actions, np.zeros(self._model._scale.shape, dtype=np.float32)]
99 network = self._model._network
100 network.eval()
101 result = network(self._model._tensor([self._descriptor]),
102 self._model._tensor([observations]),
103 self._model._tensor([actions]))[0, -1].cpu().numpy()
104 if not np.isfinite(result).all():
105 raise ValueError("The QDT produced a nonfinite action.")
106 action = self._model._decode(result)
107 self._observations.append(obs)
108 self._actions.append(self._model._encode(action.astype(float).reshape(-1)))
109 return action
110
111
112
114 """Distill offline QD trajectories following the QDT paper (2023).
115
116 Each step contributes descriptor, observation, and action tokens. A
117 causal mask prevents a prediction from reading its target action.
118 The descriptor can be a measured behavior of the training trajectory
119 or a teacher label. Use a context length at least as long as the
120 episodes you will train on and deploy.
121
122 :param observation_space: Fixed numeric Gymnasium Box.
123 :param action_space: Bounded floating-point Gymnasium Box.
124 :param descriptor_size: Number of coordinates in each goal descriptor.
125 :param config: Optional QDTConfig architecture.
126 :param seed: Nonnegative initialization and minibatch seed.
127 :param device: CPU or CUDA Torch device.
128 """
129
130 def __init__(self, observation_space, action_space, descriptor_size, *, config=None, seed=0, device="cpu"):
131 self._initialize(_observation_shape(observation_space), _BoxLayout.from_space(action_space),
132 descriptor_size, config, seed, device)
133
134 def _initialize(self, obs_shape, actions, descriptor_size, config, seed, device):
135 self._obs_shape, self._layout = obs_shape, actions
136 self.descriptor_size = _integer(descriptor_size, "descriptor_size")
137 self.config = QDTConfig() if config is None else config
138 if not isinstance(self.config, QDTConfig):
139 raise TypeError("config must be a QDTConfig.")
140 self.device = torch.device(device)
141 seed = _integer(seed, "seed", 0)
142 self._rng = np.random.default_rng(seed)
143 self._low, self._high = (np.asarray(bound, dtype=float) for bound in (actions.low, actions.high))
144 wide = np.maximum(np.abs(self._low), np.abs(self._high)) > np.finfo(float).max / 2
145 self._factor = np.where(wide, .5, 1.)
146 self._scale = self._high * self._factor - self._low * self._factor
147 with torch.random.fork_rng(devices=[]):
148 torch.random.default_generator.manual_seed(seed)
149 self._network = _SequenceModel(prod(obs_shape), prod(actions.shape), self.descriptor_size,
150 self.config).to(self.device)
151
152 def _tensor(self, values):
153 return torch.as_tensor(np.asarray(values), dtype=torch.float32, device=self.device)
154
155 def _descriptor(self, descriptor):
156 vector = np.array(descriptor, dtype=np.float32, copy=True)
157 if vector.shape != (self.descriptor_size,) or not np.isfinite(vector).all():
158 raise ValueError("Supply a finite descriptor vector of the configured size.")
159 return vector
160
161 def _decode(self, normalized):
162 fraction = (normalized.astype(float) + 1) / 2
163 physical = np.clip((1 - fraction) * self._low + fraction * self._high, self._low, self._high)
164 return physical.astype(self._layout.dtype).reshape(self._layout.shape)
165
166 def _encode(self, actions):
167 return (2 * ((actions * self._factor - self._low * self._factor) / self._scale) - 1).astype(np.float32)
168
169 def _inputs(self, episode, descriptor):
170 if not isinstance(episode, Episode) or not 1 <= episode.steps <= self.config.context_length:
171 raise ValueError("Training requires nonempty Episode records within the QDT context.")
172 observations = np.asarray(episode.observations, dtype=np.float32)
173 actions = np.asarray(episode.actions, dtype=float)
174 if (observations.shape != (episode.steps + 1, *self._obs_shape) or not np.isfinite(observations).all()
175 or actions.shape != (episode.steps, *self._layout.shape) or not np.isfinite(actions).all()):
176 raise ValueError("An episode has inconsistent or nonfinite observations or actions.")
177 actions = actions.reshape(episode.steps, -1)
178 if np.any((actions < self._low) | (actions > self._high)):
179 raise ValueError("Episode actions must respect Box bounds.")
180 return self._descriptor(descriptor), observations[:-1].reshape(episode.steps, -1), self._encode(actions)
181
182 def _batch(self, rows):
183 goals, states, actions = zip(*rows)
184 lengths = np.array([len(row) for row in states])
185 size = int(lengths.max())
186 observations = np.zeros((len(rows), size, prod(self._obs_shape)), dtype=np.float32)
187 controls = np.zeros((len(rows), size, prod(self._layout.shape)), dtype=np.float32)
188 for i, (state, action) in enumerate(zip(states, actions)):
189 observations[i, :len(state)] = state
190 controls[i, :len(action)] = action
191 mask = torch.as_tensor(np.arange(size) < lengths[:, None], device=self.device)
192 return self._tensor(goals), self._tensor(observations), self._tensor(controls), mask
193
194
195 def fit(self, episodes, descriptors, *, epochs=10, batch_size=16, learning_rate=3e-4):
196 """Train offline with action MSE. Return costs for this fit call."""
197 epochs = _integer(epochs, "epochs")
198 batch_size = _integer(batch_size, "batch_size")
199 if not isfinite(learning_rate) or learning_rate <= 0:
200 raise ValueError("learning_rate must be finite and positive.")
201 data = [self._inputs(episode, goal) for episode, goal in zip(episodes, descriptors, strict=True)]
202 if not data:
203 raise ValueError("Supply at least one descriptor-labelled episode.")
204 steps = sum(len(observations) for _, observations, _ in data)
205 optimizer = torch.optim.Adam(self._network.parameters(), lr=learning_rate)
206 updates = 0
207 self._network.train()
208 for _ in range(epochs):
209 order = self._rng.permutation(len(data))
210 weighted_loss = 0.
211 for start in range(0, len(data), batch_size):
212 rows = [data[row] for row in order[start:start + batch_size]]
213 goals, obs, actions, mask = self._batch(rows)
214 predictions = self._network(goals, obs, actions)
215 loss = (predictions[mask] - actions[mask]).square().mean()
216 if not torch.isfinite(loss):
217 raise ValueError("The QDT produced a nonfinite loss.")
218 optimizer.zero_grad(set_to_none=True)
219 loss.backward()
220 torch.nn.utils.clip_grad_norm_(self._network.parameters(), 1., error_if_nonfinite=True)
221 optimizer.step()
222 weighted_loss += loss.item() * sum(len(obs) for _, obs, _ in rows)
223 updates += 1
224 self._network.eval()
225 return QDTTrainingStats(len(data), steps, updates, weighted_loss / steps)
226
227
228 def policy_for(self, descriptor):
229 """Return a policy session using the current model weights."""
230 return QDTPolicy(self, descriptor)
231
232
233 def save(self, path):
234 """Write a versioned policy NPZ without storing trajectories or an environment."""
235 metadata = dict(version=1, kind="qdt", observation_shape=self._obs_shape,
236 action_shape=self._layout.shape, low=self._layout.low, high=self._layout.high,
237 dtype=self._layout.dtype, descriptor_size=self.descriptor_size, config=asdict(self.config))
238 parameters = parameters_to_vector(self._network.parameters()).detach().cpu().numpy()
239 _save_actor(path, metadata, parameters)
240
241
242 @classmethod
243 def load(cls, path, *, device="cpu"):
244 """Load a versioned QDT artifact saved by this class."""
245 metadata, parameters = _read_actor(path)
246 if metadata.get("kind") != "qdt" or metadata.get("version") != 1:
247 raise ValueError("Unsupported QDT artifact.")
248 obs_shape = tuple(_integer(size, "observation extent") for size in metadata["observation_shape"])
249 actions = _BoxLayout(tuple(_integer(size, "action extent") for size in metadata["action_shape"]),
250 tuple(metadata["low"]), tuple(metadata["high"]), metadata["dtype"])
251 model = cls.__new__(cls)
252 model._initialize(obs_shape, actions, metadata["descriptor_size"], QDTConfig(**metadata["config"]), 0, device)
253 parameters = np.asarray(parameters, dtype=np.float32)
254 length = sum(param.numel() for param in model._network.parameters())
255 if parameters.shape != (length,) or not np.isfinite(parameters).all():
256 raise ValueError(f"Expected {length} finite QDT weights.")
257 with torch.no_grad():
258 vector_to_parameters(model._tensor(parameters), model._network.parameters())
259 model._network.eval()
260 return model
Set the episode context and the dimensions of the causal Transformer.
Definition qdt.py:21
An independent autoregressive history for one requested behavior.
Definition qdt.py:75
reset(self, descriptor=None)
Start a fresh episode with the current or a new descriptor.
Definition qdt.py:84
act(self, observation)
Append one observation, emit the next action, and retain the action in context.
Definition qdt.py:92
Report the inputs and work of one offline supervised training call.
Definition qdt.py:38
Train and export a continuous descriptor-conditioned Quality-Diversity Transformer.
Definition qdt.py:113
save(self, path)
Save model parameters and numeric environment layout for inference.
Definition qdt.py:233
_inputs(self, episode, descriptor)
Definition qdt.py:169
load(cls, path, *, device="cpu")
Restore a Transformer independently of the training data and environment.
Definition qdt.py:243
_initialize(self, obs_shape, actions, descriptor_size, config, seed, device)
Definition qdt.py:134
policy_for(self, descriptor)
Bind a target descriptor to independent episode state.
Definition qdt.py:228
fit(self, episodes, descriptors, *, epochs=10, batch_size=16, learning_rate=3e-4)
Fit the causal model using complete, descriptor-labelled episodes.
Definition qdt.py:195