QDpy
Loading...
Searching...
No Matches
policy.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Flat-vector actors for categorical and bounded continuous actions."""
6
7from dataclasses import dataclass
8import json
9from math import log, pi, prod, sqrt
10from operator import index
11import os
12from pathlib import Path
13from tempfile import NamedTemporaryFile
14
15from gymnasium import spaces
16import numpy as np
17import torch
18from torch import nn
19from torch.nn import functional as F
20
21
22def _integer(value, name, minimum=1):
23 try:
24 if isinstance(value, (bool, np.bool_)):
25 raise TypeError
26 result = index(value)
27 except TypeError as error:
28 raise ValueError(f"{name} must be an integer.") from error
29 if result < minimum:
30 raise ValueError(f"{name} must be at least {minimum}.")
31 return result
32
33
34
35@dataclass(frozen=True)
37 """Configure hidden-layer widths. An empty tuple selects a linear model."""
38
39 hidden_sizes: tuple[int, ...] = (64, 64)
40
41 def __post_init__(self):
42 widths = tuple(_integer(size, "Hidden width") for size in self.hidden_sizes)
43 object.__setattr__(self, "hidden_sizes", widths)
44
45
46@dataclass(frozen=True)
48 shape: tuple
49 counts: tuple
50 starts: tuple
51 dtype: str
52 discrete: bool
53
54 def __post_init__(self):
55 dtype = np.dtype(self.dtype)
56 if not np.issubdtype(dtype, np.integer):
57 raise ValueError("Categorical actions require an integer dtype.")
58 limits = np.iinfo(dtype)
59 if (type(self.discrete) is not bool or (self.discrete and self.shape)
60 or len(self.counts) != prod(self.shape) or len(self.counts) != len(self.starts)
61 or not self.counts or any(size < 1 for size in self.shape)
62 or any(count < 1 or start < limits.min or start + count - 1 > limits.max
63 for count, start in zip(self.counts, self.starts))):
64 raise ValueError("Invalid categorical action layout.")
65
66 @classmethod
67 def from_space(cls, space):
68 if isinstance(space, spaces.Discrete):
69 return cls((), (int(space.n),), (int(space.start),), space.dtype.str, True)
70 if isinstance(space, spaces.MultiDiscrete):
71 return cls(space.shape, tuple(map(int, space.nvec.flat)), tuple(map(int, space.start.flat)),
72 space.dtype.str, False)
73 raise ValueError("Use a Gymnasium Discrete or unmasked MultiDiscrete action space.")
74
75 def decode(self, indices):
76 values = [start + int(i) for start, i in zip(self.starts, indices.tolist())]
77 dtype = np.dtype(self.dtype)
78 if self.discrete:
79 return dtype.type(values[0])
80 return np.asarray(values, dtype=dtype).reshape(self.shape)
81
82
83def _observation_shape(space):
84 if not isinstance(space, spaces.Box) or not np.issubdtype(space.dtype, np.number):
85 raise ValueError("Use a numeric Gymnasium Box observation space or flatten it with a wrapper.")
86 if not prod(space.shape):
87 raise ValueError("Observations must have at least one coordinate.")
88 return space.shape
89
90
91def _flatten_observation(observation, shape):
92 value = np.array(observation, dtype=np.float32, copy=True)
93 if value.shape != shape or not np.isfinite(value).all():
94 raise ValueError(f"Expected a finite observation with shape {shape}.")
95 return value.reshape(-1)
96
97
98class _SeededLinear(nn.Linear):
99 """Draw the usual Linear initializer from a caller-owned generator."""
100
101 def __init__(self, inputs, outputs, rng):
102 self._initialization_rng = rng
103 super().__init__(inputs, outputs, device="cpu", dtype=torch.float32)
104 self._initialization_rng = None
105
106 def reset_parameters(self):
107 if self._initialization_rng is None:
108 return super().reset_parameters()
109 nn.init.kaiming_uniform_(self.weight, a=sqrt(5), generator=self._initialization_rng)
110 bound = 1 / sqrt(self.in_features)
111 nn.init.uniform_(self.bias, -bound, bound, generator=self._initialization_rng)
112
113
114def _mlp(inputs, outputs, config, seed, device, activation=nn.Tanh):
115 # Construct on CPU so the initializer is the same for both target devices.
116 rng = torch.Generator(device="cpu").manual_seed(seed)
117 widths = (inputs, *config.hidden_sizes, outputs)
118 layers = []
119 for index, (first, second) in enumerate(zip(widths, widths[1:])):
120 layers.append(_SeededLinear(first, second, rng))
121 if index < len(config.hidden_sizes):
122 layers.append(activation())
123 return nn.Sequential(*layers).to(device=device)
124
125
126def _distributions(logits, counts):
127 return tuple(torch.distributions.Categorical(logits=factor) for factor in logits.split(counts, dim=-1))
128
129
130def _joint_statistics(logits, indices, counts):
131 """Return the log-probability and entropy of a product of categoricals."""
132 factors = _distributions(logits, counts)
133 log_probability = sum(factor.log_prob(indices[..., i]) for i, factor in enumerate(factors))
134 entropy = sum(factor.entropy() for factor in factors)
135 return log_probability, entropy
136
137
138def _save_actor(path, metadata, parameters):
139 """Write a numeric policy artifact atomically."""
140 path = Path(path)
141 with NamedTemporaryFile(dir=path.parent, delete=False) as temporary:
142 try:
143 np.savez_compressed(temporary, metadata=json.dumps(metadata), parameters=parameters)
144 temporary.close()
145 os.replace(temporary.name, path)
146 finally:
147 Path(temporary.name).unlink(missing_ok=True)
148
149
150def _read_actor(path):
151 with np.load(path, allow_pickle=False) as data:
152 return json.loads(data["metadata"].item()), data["parameters"]
153
154
156 """Shared flat parameter codec for exportable Torch actors."""
157
158 _activation = nn.Tanh
159
160 @classmethod
161 def _from_layout(cls, obs_shape, actions, config, seed, device, **kwargs):
162 actor = cls.__new__(cls)
163 actor._initialize(obs_shape, actions, config, seed, device, **kwargs)
164 return actor
165
166 def _initialize(self, obs_shape, actions, config, seed, device):
167 outputs = self._output_size(actions)
168 self._obs_shape = obs_shape
169 self._actions = actions
170 if not isinstance(config, PolicyConfig):
171 raise TypeError("config must be a PolicyConfig.")
172 self.config = config
173 self.device = torch.device(device)
174 if self.device.type not in ("cpu", "cuda"):
175 raise ValueError("Use a CPU or CUDA device.")
176 seed = _integer(seed, "seed", 0)
177 self._network = self._build_network(outputs, seed)
178 self._network.eval()
179 self._rng = torch.Generator(device=self.device).manual_seed(seed)
180
181 def _build_network(self, outputs, seed):
182 return _mlp(prod(self._obs_shape), outputs, self.config, seed, self.device, self._activation)
183
184 def _observation(self, observation):
185 return _flatten_observation(observation, self._obs_shape)
186
187 def _tensor(self, observation):
188 return torch.as_tensor(observation, dtype=torch.float32, device=self.device)
189
190 def _new(self, seed, device=None, **kwargs):
191 return type(self)._from_layout(self._obs_shape, self._actions, self.config, seed,
192 self.device if device is None else device, **kwargs)
193
194 def _trainable_parameters(self):
195 return tuple(self._network.parameters())
196
197
198 def act(self, observation, deterministic=True):
199 """Return an action in the original space's shape, dtype, and bounds."""
200 observation = self._observation(observation)
201 if deterministic:
202 return self._greedy(observation)
203 action, _, _ = self._draw(observation, False, self._rng)
204 return action
205
206 def _greedy(self, observation):
207 return self._draw(observation, True, None)[0]
208
209 def _parameters(self):
210 return nn.utils.parameters_to_vector(self._trainable_parameters()).detach().cpu().numpy().copy()
211
212 def _set_parameters(self, parameters):
213 values = np.array(parameters, dtype=np.float32, copy=True)
214 count = sum(parameter.numel() for parameter in self._trainable_parameters())
215 if values.shape != (count,) or not np.isfinite(values).all():
216 raise ValueError(f"Expected {count} finite actor parameters in a flat vector.")
217 with torch.no_grad():
218 nn.utils.vector_to_parameters(self._tensor(values), self._trainable_parameters())
219
220
221
223 """Map finite Box observations to valid discrete controller actions.
224
225 Each component of a MultiDiscrete action has its own categorical
226 distribution. Observations are flattened in C order and converted to
227 float32. The actor stores no value function or optimiser state.
228
229 :param observation_space: Numeric Gymnasium Box, with a fixed shape.
230 :param action_space: Discrete or unmasked MultiDiscrete space.
231 :param config: Optional :class:`PolicyConfig` with hidden-layer widths.
232 :param seed: Nonnegative seed for initialization and stochastic actions.
233 :param device: Torch CPU or CUDA device.
234 """
235
236 def __init__(self, observation_space, action_space, *, config=None, seed=0, device="cpu"):
237 self._initialize(_observation_shape(observation_space), _ActionLayout.from_space(action_space),
238 PolicyConfig() if config is None else config, seed, device)
239
240 @staticmethod
241 def _output_size(actions):
242 return sum(actions.counts)
243
244 def _ppo_statistics(self, observations, actions, generator):
245 return _joint_statistics(self._network(observations), actions, self._actions.counts)
246
247 @torch.no_grad()
248 def _draw(self, observation, deterministic, generator):
249 logits = self._network(self._tensor(observation))
250 factors = _distributions(logits, self._actions.counts)
251 if deterministic:
252 indices = torch.stack([factor.logits.argmax(dim=-1) for factor in factors])
253 else:
254 indices = torch.stack([torch.multinomial(factor.probs, 1, generator=generator)[0]
255 for factor in factors])
256 log_probability = sum(factor.log_prob(i) for factor, i in zip(factors, indices))
257 return self._actions.decode(indices), indices, log_probability
258
259 @torch.no_grad()
260 def _greedy(self, observation):
261 return self._actions.decode(self._greedy_indices(self._network(self._tensor(observation))))
262
263 def _greedy_indices(self, logits):
264 parts = logits.split(self._actions.counts, dim=-1)
265 # Normalize first to preserve ties caused by float rounding in Categorical.
266 normalized = [part - part.logsumexp(dim=-1, keepdim=True) for part in parts]
267 if torch.cat(normalized, dim=-1).isnan().any():
268 raise ValueError("The categorical policy produced invalid logits.")
269 return torch.stack([part.argmax(dim=-1) for part in normalized], dim=-1)
270
271
272 def save(self, path):
273 """Write a versioned NumPy archive to the supplied filename."""
274 metadata = dict(version=1, observation_shape=self._obs_shape, action_shape=self._actions.shape,
275 counts=self._actions.counts, starts=self._actions.starts, dtype=self._actions.dtype,
276 discrete=self._actions.discrete, hidden_sizes=self.config.hidden_sizes)
277 _save_actor(path, metadata, self._parameters())
278
279
280 @classmethod
281 def load(cls, path, *, device="cpu", seed=0):
282 """Load a saved actor without instantiating its training environment."""
283 metadata, parameters = _read_actor(path)
284 if metadata.get("version") != 1 or "kind" in metadata:
285 raise ValueError("Unsupported categorical policy artifact.")
286 shape = tuple(_integer(size, "Observation extent") for size in metadata["observation_shape"])
287 layout = _ActionLayout(tuple(_integer(size, "Action extent") for size in metadata["action_shape"]),
288 tuple(_integer(count, "Action count") for count in metadata["counts"]),
289 tuple(index(start) for start in metadata["starts"]),
290 metadata["dtype"], metadata["discrete"])
291 actor = cls._from_layout(shape, layout, PolicyConfig(tuple(metadata["hidden_sizes"])), seed, device)
292 actor._set_parameters(parameters)
293 return actor
294
295
296@dataclass(frozen=True)
298 shape: tuple
299 low: tuple
300 high: tuple
301 dtype: str
302
303 def __post_init__(self):
304 dtype = np.dtype(self.dtype)
305 low, high = np.asarray(self.low, dtype=np.float64), np.asarray(self.high, dtype=np.float64)
306 if (dtype.kind != "f" or dtype.itemsize > 8 or not prod(self.shape)
307 or low.shape != (prod(self.shape),) or high.shape != low.shape
308 or not np.isfinite(low).all() or not np.isfinite(high).all()
309 or np.any(low < np.finfo(dtype).min) or np.any(high > np.finfo(dtype).max)
310 or np.any(high <= low)):
311 raise ValueError("Use a floating-point Box with finite, strictly increasing action bounds.")
312
313 @classmethod
314 def from_space(cls, space):
315 if not isinstance(space, spaces.Box):
316 raise ValueError("Use a bounded floating-point Gymnasium Box action space.")
317 return cls(space.shape, tuple(map(float, space.low.flat)), tuple(map(float, space.high.flat)),
318 space.dtype.str)
319
320
321def _action_layout(space):
322 if isinstance(space, spaces.Box):
323 return _BoxLayout.from_space(space)
324 if isinstance(space, (spaces.Discrete, spaces.MultiDiscrete)):
325 return _ActionLayout.from_space(space)
326 raise ValueError("Use a Gymnasium Discrete, unmasked MultiDiscrete, or bounded floating-point Box action space.")
327
328
329def _squashed_log_prob(mean, log_std, latent, log_scale):
330 """Compute the joint density after tanh and the affine action transform."""
331 normal = -0.5 * ((latent - mean) * (-log_std).exp()).square() - log_std - 0.5 * log(2 * pi)
332 log_jacobian = 2 * (log(2.) - latent - F.softplus(-2 * latent))
333 return (normal - log_jacobian - log_scale).sum(dim=-1)
334
335
336
338 """Apply tanh and scale each output into its environment action interval.
339
340 Hidden layers use ReLU. A stochastic actor learns a state-independent
341 diagonal Gaussian scale in the coordinates before tanh. Its log
342 standard deviation is clamped to [-12, 2] for float32 sampling. A deterministic
343 actor always uses the squashed mean, including when ``deterministic=False``.
344
345 :param observation_space: Numeric Gymnasium Box with a fixed shape.
346 :param action_space: Floating-point Gymnasium Box with finite bounds.
347 :param config: Optional :class:`PolicyConfig` with hidden-layer widths.
348 :param stochastic: Include a trainable log standard deviation per coordinate.
349 :param seed: Nonnegative seed for initialization and stochastic actions.
350 :param device: Torch CPU or CUDA device.
351 """
352
353 _activation = nn.ReLU
354
355 def __init__(self, observation_space, action_space, *, config=None, stochastic=False, seed=0, device="cpu"):
356 self._initialize(_observation_shape(observation_space), _BoxLayout.from_space(action_space),
357 PolicyConfig() if config is None else config, seed, device, stochastic=stochastic)
358
359 def _initialize(self, obs_shape, actions, config, seed, device, *, stochastic):
360 if type(stochastic) is not bool:
361 raise TypeError("stochastic must be a bool.")
362 super()._initialize(obs_shape, actions, config, seed, device)
363 self._low, self._high = (np.asarray(bound, dtype=np.float64) for bound in (actions.low, actions.high))
364 # Halve intervals that could overflow when computing their width.
365 wide = np.maximum(np.abs(self._low), np.abs(self._high)) > np.finfo(np.float64).max / 2
366 self._encode_factor = np.where(wide, 0.5, 1.)
367 self._encode_low = self._low * self._encode_factor
368 self._encode_width = self._high * self._encode_factor - self._encode_low
369 self._log_scale = self._tensor(np.log(self._encode_width) - np.where(wide, 0., log(2.)))
370 self._log_std = (nn.Parameter(torch.zeros(prod(actions.shape), device=self.device, dtype=torch.float32))
371 if stochastic else None)
372
373 @staticmethod
374 def _output_size(actions):
375 return prod(actions.shape)
376
377 def _new(self, seed, device=None):
378 return super()._new(seed, device, stochastic=self._log_std is not None)
379
380 def _trainable_parameters(self):
381 parameters = super()._trainable_parameters()
382 return parameters if self._log_std is None else (*parameters, self._log_std)
383
384 def _normalized(self, observations):
385 return self._network(observations).tanh()
386
387 def _decode(self, normalized):
388 fraction = (np.asarray(normalized, dtype=np.float64) + 1) / 2
389 physical = np.clip((1 - fraction) * self._low + fraction * self._high, self._low, self._high)
390 return physical.astype(self._actions.dtype).reshape(self._actions.shape)
391
392 def _encode(self, action):
393 flat = np.asarray(action, dtype=np.float64).reshape(-1)
394 return self._encode_actions(flat)
395
396 def _encode_actions(self, flat):
397 fraction = (flat * self._encode_factor - self._encode_low) / self._encode_width
398 return (2 * np.clip(fraction, 0, 1) - 1).astype(np.float32)
399
400 def _sample(self, mean, log_std, generator):
401 noise = torch.randn(mean.shape, dtype=mean.dtype, device=mean.device, generator=generator)
402 return mean + log_std.exp() * noise
403
404 def _ppo_statistics(self, observations, actions, generator):
405 mean = self._network(observations)
406 log_std = self._log_std.clamp(-12, 2)
407 log_probability = _squashed_log_prob(mean, log_std, actions, self._log_scale)
408 sample = self._sample(mean, log_std, generator)
409 entropy = -_squashed_log_prob(mean, log_std, sample, self._log_scale)
410 return log_probability, entropy
411
412 @torch.no_grad()
413 def _draw(self, observation, deterministic, generator):
414 mean = self._network(self._tensor(observation))
415 if self._log_std is None or deterministic:
416 return self._decode(mean.tanh().cpu().numpy()), mean, None
417 log_std = self._log_std.clamp(-12, 2)
418 latent = self._sample(mean, log_std, generator)
419 log_probability = _squashed_log_prob(mean, log_std, latent, self._log_scale)
420 return self._decode(latent.tanh().cpu().numpy()), latent, log_probability
421
422
423 def save(self, path):
424 """Write a portable numeric NPZ file at the supplied path."""
425 metadata = dict(version=1, kind="continuous", observation_shape=self._obs_shape,
426 action_shape=self._actions.shape, low=self._actions.low, high=self._actions.high,
427 dtype=self._actions.dtype, hidden_sizes=self.config.hidden_sizes,
428 stochastic=self._log_std is not None)
429 _save_actor(path, metadata, self._parameters())
430
431
432 @classmethod
433 def load(cls, path, *, device="cpu", seed=0):
434 """Restore the actor, action bounds, shape, and floating-point dtype."""
435 metadata, parameters = _read_actor(path)
436 if metadata.get("version") != 1 or metadata.get("kind") != "continuous":
437 raise ValueError("Unsupported continuous policy artifact.")
438 shape = tuple(_integer(size, "Observation extent") for size in metadata["observation_shape"])
439 layout = _BoxLayout(tuple(_integer(size, "Action extent") for size in metadata["action_shape"]),
440 tuple(metadata["low"]), tuple(metadata["high"]), metadata["dtype"])
441 actor = cls._from_layout(shape, layout, PolicyConfig(tuple(metadata["hidden_sizes"])), seed, device,
442 stochastic=metadata["stochastic"])
443 actor._set_parameters(parameters)
444 return actor
445
446
447def _make_policy(env, config, seed, device, *, stochastic):
448 shape = _observation_shape(env.observation_space)
449 actions = _action_layout(env.action_space)
450 config = PolicyConfig() if config is None else config
451 if isinstance(actions, _BoxLayout):
452 return ContinuousPolicy._from_layout(shape, actions, config, seed, device, stochastic=stochastic)
453 return CategoricalPolicy._from_layout(shape, actions, config, seed, device)
A categorical actor that can run independently of its training environment.
Definition policy.py:222
load(cls, path, *, device="cpu", seed=0)
Rebuild an inference actor from a versioned, numeric policy artifact.
Definition policy.py:281
save(self, path)
Export actor parameters and the information needed to decode actions.
Definition policy.py:272
A bounded Box actor for evolutionary, on-policy, and deterministic control.
Definition policy.py:337
save(self, path)
Store a versioned continuous actor without optimizer state.
Definition policy.py:423
_decode(self, normalized)
Definition policy.py:387
load(cls, path, *, device="cpu", seed=0)
Load a continuous actor without constructing its environment.
Definition policy.py:433
_sample(self, mean, log_std, generator)
Definition policy.py:400
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
_observation(self, observation)
Definition policy.py:184
_from_layout(cls, obs_shape, actions, config, seed, device, **kwargs)
Definition policy.py:161
_greedy(self, observation)
Definition policy.py:206
_build_network(self, outputs, seed)
Definition policy.py:181
_tensor(self, observation)
Definition policy.py:187
act(self, observation, deterministic=True)
Choose a deterministic action or sample from the actor.
Definition policy.py:198
_initialize(self, obs_shape, actions, config, seed, device)
Definition policy.py:166