QDpy
Loading...
Searching...
No Matches
descriptor_policy.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Portable inference for descriptor-conditioned policies."""
6
7from math import prod
8
9import numpy as np
10import torch
11
12from .policy import (
13 ContinuousPolicy, PolicyConfig, _BoxLayout, _integer, _observation_shape, _read_actor, _save_actor,
14)
15
16
18 """Transform physical descriptors into common coordinates for networks and distance."""
19
20 def __init__(self, domain):
21 bounds = np.asarray(domain, dtype=np.float64)
22 if (bounds.ndim != 2 or not len(bounds) or bounds.shape[1] != 2
23 or not np.isfinite(bounds).all() or np.any(bounds[:, 0] >= bounds[:, 1])):
24 raise ValueError("Use finite, strictly increasing descriptor bounds for every coordinate.")
25 self.bounds = tuple(map(tuple, bounds.tolist()))
26 self.low, self.high = bounds[:, 0].copy(), bounds[:, 1].copy()
27 wide = np.maximum(np.abs(self.low), np.abs(self.high)) > np.finfo(np.float64).max / 2
28 self.factor = np.where(wide, 0.5, 1.)
29 self.origin = self.low * self.factor
30 self.width = self.high * self.factor - self.origin
31
32 def normalize(self, descriptor, *, goal=False):
33 values = np.asarray(descriptor, dtype=np.float64)
34 if values.shape != self.low.shape or not np.isfinite(values).all():
35 raise ValueError(f"Expected a finite descriptor of length {len(self.bounds)}.")
36 if goal and (np.any(values < self.low) or np.any(values > self.high)):
37 raise ValueError("The target descriptor is outside the declared domain.")
38 with np.errstate(over="ignore"):
39 normalized = (2 * ((values * self.factor - self.origin) / self.width) - 1).astype(np.float32)
40 if not np.isfinite(normalized).all():
41 raise ValueError("The normalized descriptor must be representable in float32.")
42 return normalized
43
44
45
47 """Concatenate a flattened observation and an affine-normalized target.
48
49 :param observation_space: Fixed numeric Gymnasium Box.
50 :param action_space: Finite floating-point Gymnasium Box.
51 :param descriptor_domain: Finite (low, high) pairs in physical coordinates.
52 :param config: Architecture of the ReLU MLP as a :class:`PolicyConfig`.
53 :param seed: Nonnegative initialization seed.
54 :param device: Torch CPU or CUDA device.
55 """
56
57 def __init__(self, observation_space, action_space, descriptor_domain, *, config=None, seed=0, device="cpu"):
58 self._initialize(_observation_shape(observation_space), _BoxLayout.from_space(action_space),
59 _DescriptorDomain(descriptor_domain), PolicyConfig() if config is None else config,
60 seed, device)
61
62 @classmethod
63 def _from_layout(cls, shape, actions, domain, config, seed, device):
64 policy = cls.__new__(cls)
65 policy._initialize(shape, actions, domain, config, seed, device)
66 return policy
67
68 def _initialize(self, shape, actions, domain, config, seed, device):
69 self._obs_shape, self._domain = shape, domain
70 inputs = prod(shape) + len(domain.bounds)
71 self._model = ContinuousPolicy._from_layout((inputs,), actions, config, seed, device, stochastic=False)
72
73 @property
75 """Return the descriptor bounds in the same units accepted by act."""
76 return self._domain.bounds
77
78
79 def act(self, observation, descriptor):
80 """Return an action in the original environment's shape and dtype."""
81 observation = np.asarray(observation, dtype=np.float32)
82 if observation.shape != self._obs_shape or not np.isfinite(observation).all():
83 raise ValueError(f"Expected a finite observation with shape {self._obs_shape}.")
84 target = self._domain.normalize(descriptor, goal=True)
85 return self._model.act(np.concatenate((observation.reshape(-1), target)))
86
87
88 def specialize(self, descriptor, *, device=None):
89 """Return a :class:`ContinuousPolicy` with the archive policy architecture."""
90 target = self._domain.normalize(descriptor, goal=True)
91 return self._specialize(target, device)
92
93 @torch.no_grad()
94 def _specialize(self, target, device=None):
95 model = self._model
96 actor = ContinuousPolicy._from_layout(
97 self._obs_shape, model._actions, model.config, 0,
98 model.device if device is None else device, stochastic=False,
99 )
100 width = prod(self._obs_shape)
101 source, dest = model._network[0], actor._network[0]
102 dest.weight.copy_(source.weight[:, :width])
103 dest.bias.copy_(source.bias + source.weight[:, width:] @ model._tensor(target))
104 actor._network[1:].load_state_dict(model._network[1:].state_dict())
105 return actor
106
107
108 def save(self, path):
109 """Write a versioned numeric NPZ for inference without an environment."""
110 model = self._model
111 metadata = dict(version=1, kind="descriptor-conditioned", observation_shape=self._obs_shape,
112 action_shape=model._actions.shape, low=model._actions.low, high=model._actions.high,
113 dtype=model._actions.dtype, hidden_sizes=model.config.hidden_sizes,
114 descriptor_domain=self.descriptor_domain)
115 _save_actor(path, metadata, model._parameters())
116
117
118 @classmethod
119 def load(cls, path, *, device="cpu"):
120 """Load weights, input shapes, and normalization from a numeric artifact."""
121 metadata, parameters = _read_actor(path)
122 if metadata.get("version") != 1 or metadata.get("kind") != "descriptor-conditioned":
123 raise ValueError("Unsupported descriptor-conditioned policy artifact.")
124 shape = tuple(_integer(size, "Observation extent") for size in metadata["observation_shape"])
125 layout = _BoxLayout(tuple(_integer(size, "Action extent") for size in metadata["action_shape"]),
126 tuple(metadata["low"]), tuple(metadata["high"]), metadata["dtype"])
127 domain = _DescriptorDomain(metadata["descriptor_domain"])
128 actor = cls._from_layout(shape, layout, domain, PolicyConfig(tuple(metadata["hidden_sizes"])), 0, device)
129 actor._model._set_parameters(parameters)
130 return actor
A bounded continuous actor that takes a target behavior descriptor.
save(self, path)
Export the conditioned actor and descriptor normalization bounds.
_initialize(self, shape, actions, domain, config, seed, device)
act(self, observation, descriptor)
Take a deterministic action toward a target descriptor.
specialize(self, descriptor, *, device=None)
Fold a fixed target into the first affine layer of an independent actor.
load(cls, path, *, device="cpu")
Rebuild a conditioned inference policy from its saved NPZ.
_from_layout(cls, shape, actions, domain, config, seed, device)
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36