48 """Predict actions from observation tokens with a causal attention mask."""
50 def __init__(self, observations, actions, descriptors, config):
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),
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)
70 sequence = layer(sequence, src_mask=self.causal[:3 * count, :3 * count])
71 return self.
output(sequence[:, 1::3])
114 """Distill offline QD trajectories following the QDT paper (2023).
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.
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.
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)
134 def _initialize(self, obs_shape, actions, descriptor_size, config, seed, device):
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.)
147 with torch.random.fork_rng(devices=[]):
148 torch.random.default_generator.manual_seed(seed)
152 def _tensor(self, values):
153 return torch.as_tensor(np.asarray(values), dtype=torch.float32, device=self.
device)
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.")
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)
166 def _encode(self, actions):
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)
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)
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)]
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)
208 for _
in range(epochs):
209 order = self.
_rng.permutation(len(data))
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)
220 torch.nn.utils.clip_grad_norm_(self.
_network.parameters(), 1., error_if_nonfinite=
True)
222 weighted_loss += loss.item() * sum(len(obs)
for _, obs, _
in rows)
229 """Return a policy session using the current model weights."""
234 """Write a versioned policy NPZ without storing trajectories or an environment."""
235 metadata = dict(version=1, kind=
"qdt", observation_shape=self.
_obs_shape,
238 parameters = parameters_to_vector(self.
_network.parameters()).detach().cpu().numpy()
239 _save_actor(path, metadata, parameters)
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()