13 ContinuousPolicy, PolicyConfig, _BoxLayout, _integer, _observation_shape, _read_actor, _save_actor,
18 """Transform physical descriptors into common coordinates for networks and distance."""
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.)
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.")
47 """Concatenate a flattened observation and an affine-normalized target.
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.
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),
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)
68 def _initialize(self, shape, actions, domain, config, seed, device):
70 inputs = prod(shape) + len(domain.bounds)
71 self.
_model = ContinuousPolicy._from_layout((inputs,), actions, config, seed, device, stochastic=
False)
75 """Return the descriptor bounds in the same units accepted by act."""
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)))
89 """Return a :class:`ContinuousPolicy` with the archive policy architecture."""
90 target = self.
_domain.normalize(descriptor, goal=
True)
94 def _specialize(self, target, device=None):
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,
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())
109 """Write a versioned numeric NPZ for inference without an environment."""
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,
115 _save_actor(path, metadata, model._parameters())
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"])
129 actor._model._set_parameters(parameters)