5"""Flat-vector actors for categorical and bounded continuous actions."""
7from dataclasses
import dataclass
9from math
import log, pi, prod, sqrt
10from operator
import index
12from pathlib
import Path
13from tempfile
import NamedTemporaryFile
15from gymnasium
import spaces
22def _integer(value, name, minimum=1):
24 if isinstance(value, (bool, np.bool_)):
27 except TypeError
as error:
28 raise ValueError(f
"{name} must be an integer.")
from error
30 raise ValueError(f
"{name} must be at least {minimum}.")
35@dataclass(frozen=True)
37 """Configure hidden-layer widths. An empty tuple selects a linear model."""
39 hidden_sizes: tuple[int, ...] = (64, 64)
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)
46@dataclass(frozen=True)
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)
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
64 raise ValueError(
"Invalid categorical action layout.")
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.")
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)
79 return dtype.type(values[0])
80 return np.asarray(values, dtype=dtype).reshape(self.
shape)
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.")
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)
99 """Draw the usual Linear initializer from a caller-owned generator."""
101 def __init__(self, inputs, outputs, rng):
103 super().__init__(inputs, outputs, device=
"cpu", dtype=torch.float32)
106 def reset_parameters(self):
108 return super().reset_parameters()
110 bound = 1 / sqrt(self.in_features)
114def _mlp(inputs, outputs, config, seed, device, activation=nn.Tanh):
116 rng = torch.Generator(device=
"cpu").manual_seed(seed)
117 widths = (inputs, *config.hidden_sizes, outputs)
119 for index, (first, second)
in enumerate(zip(widths, widths[1:])):
121 if index < len(config.hidden_sizes):
122 layers.append(activation())
123 return nn.Sequential(*layers).to(device=device)
126def _distributions(logits, counts):
127 return tuple(torch.distributions.Categorical(logits=factor)
for factor
in logits.split(counts, dim=-1))
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
138def _save_actor(path, metadata, parameters):
139 """Write a numeric policy artifact atomically."""
141 with NamedTemporaryFile(dir=path.parent, delete=
False)
as temporary:
143 np.savez_compressed(temporary, metadata=json.dumps(metadata), parameters=parameters)
145 os.replace(temporary.name, path)
147 Path(temporary.name).unlink(missing_ok=
True)
150def _read_actor(path):
151 with np.load(path, allow_pickle=
False)
as data:
152 return json.loads(data[
"metadata"].item()), data[
"parameters"]
156 """Shared flat parameter codec for exportable Torch actors."""
158 _activation = nn.Tanh
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)
166 def _initialize(self, obs_shape, actions, config, seed, device):
167 outputs = self._output_size(actions)
170 if not isinstance(config, PolicyConfig):
171 raise TypeError(
"config must be a PolicyConfig.")
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)
179 self.
_rng = torch.Generator(device=self.
device).manual_seed(seed)
181 def _build_network(self, outputs, seed):
184 def _observation(self, observation):
185 return _flatten_observation(observation, self.
_obs_shape)
187 def _tensor(self, observation):
188 return torch.as_tensor(observation, dtype=torch.float32, device=self.
device)
190 def _new(self, seed, device=None, **kwargs):
192 self.
device if device
is None else device, **kwargs)
194 def _trainable_parameters(self):
195 return tuple(self.
_network.parameters())
198 def act(self, observation, deterministic=True):
199 """Return an action in the original space's shape, dtype, and bounds."""
202 return self.
_greedy(observation)
203 action, _, _ = self._draw(observation,
False, self.
_rng)
206 def _greedy(self, observation):
207 return self._draw(observation,
True,
None)[0]
209 def _parameters(self):
212 def _set_parameters(self, parameters):
213 values = np.array(parameters, dtype=np.float32, copy=
True)
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():
223 """Map finite Box observations to valid discrete controller actions.
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.
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.
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)
241 def _output_size(actions):
242 return sum(actions.counts)
244 def _ppo_statistics(self, observations, actions, generator):
245 return _joint_statistics(self.
_network(observations), actions, self.
_actions.counts)
248 def _draw(self, observation, deterministic, generator):
250 factors = _distributions(logits, self.
_actions.counts)
252 indices = torch.stack([factor.logits.argmax(dim=-1)
for factor
in factors])
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
260 def _greedy(self, observation):
263 def _greedy_indices(self, logits):
264 parts = logits.split(self.
_actions.counts, dim=-1)
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)
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,
276 discrete=self.
_actions.discrete, hidden_sizes=self.
config.hidden_sizes)
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"])
292 actor._set_parameters(parameters)
296@dataclass(frozen=True)
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.")
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)),
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.")
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)
338 """Apply tanh and scale each output into its environment action interval.
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``.
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.
353 _activation = nn.ReLU
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)
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))
365 wide = np.maximum(np.abs(self.
_low), np.abs(self.
_high)) > np.finfo(np.float64).max / 2
370 self.
_log_std = (nn.Parameter(torch.zeros(prod(actions.shape), device=self.
device, dtype=torch.float32))
371 if stochastic
else None)
374 def _output_size(actions):
375 return prod(actions.shape)
377 def _new(self, seed, device=None):
378 return super()._new(seed, device, stochastic=self.
_log_std is not None)
380 def _trainable_parameters(self):
381 parameters = super()._trainable_parameters()
382 return parameters
if self.
_log_std is None else (*parameters, self.
_log_std)
384 def _normalized(self, observations):
385 return self.
_network(observations).tanh()
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)
392 def _encode(self, action):
393 flat = np.asarray(action, dtype=np.float64).reshape(-1)
396 def _encode_actions(self, flat):
398 return (2 * np.clip(fraction, 0, 1) - 1).astype(np.float32)
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
404 def _ppo_statistics(self, observations, actions, generator):
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
413 def _draw(self, observation, deterministic, generator):
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
424 """Write a portable numeric NPZ file at the supplied path."""
425 metadata = dict(version=1, kind=
"continuous", observation_shape=self.
_obs_shape,
428 stochastic=self.
_log_std is not None)
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"])
442 stochastic=metadata[
"stochastic"])
443 actor._set_parameters(parameters)
447def _make_policy(env, config, seed, device, *, stochastic):
448 shape = _observation_shape(env.observation_space)
449 actions = _action_layout(env.action_space)
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.
_greedy_indices(self, logits)
load(cls, path, *, device="cpu", seed=0)
Rebuild an inference actor from a versioned, numeric policy artifact.
save(self, path)
Export actor parameters and the information needed to decode actions.
A bounded Box actor for evolutionary, on-policy, and deterministic control.
_encode_actions(self, flat)
save(self, path)
Store a versioned continuous actor without optimizer state.
_decode(self, normalized)
load(cls, path, *, device="cpu", seed=0)
Load a continuous actor without constructing its environment.
_sample(self, mean, log_std, generator)
Architecture of the actor and, for PPO, the separate value network.
_observation(self, observation)
_from_layout(cls, obs_shape, actions, config, seed, device, **kwargs)
_greedy(self, observation)
_build_network(self, outputs, seed)
_tensor(self, observation)
act(self, observation, deterministic=True)
Choose a deterministic action or sample from the actor.
_initialize(self, obs_shape, actions, config, seed, device)
_trainable_parameters(self)