21def _decoder_pullback(torch, decoder, code, noise):
29 """Train a deterministic autoencoder on bounded normalized policy vectors."""
31 def __init__(self, dimension, hidden, latent, rate, seed, device):
34 except ImportError
as error:
35 raise ImportError(
"PolicyManifoldSearch requires PyTorch. Install qdpy[rl] or torch.")
from error
37 self.
torch, self.
device = torch, torch.device(device)
39 generator = torch.Generator(device=
"cpu").manual_seed(seed)
41 with torch.random.fork_rng(devices=[]):
42 torch.random.set_rng_state(generator.get_state())
43 self.
encoder = nn.Sequential(nn.Linear(dimension, hidden, device=
"cpu", dtype=torch.float32),
44 nn.Tanh(), nn.Linear(hidden, latent, device=
"cpu", dtype=torch.float32))
45 self.
decoder = nn.Sequential(nn.Linear(latent, hidden, device=
"cpu", dtype=torch.float32),
46 nn.Tanh(), nn.Linear(hidden, dimension, device=
"cpu", dtype=torch.float32),
52 def _tensor(self, values):
53 return self.
torch.as_tensor(values, device=self.
device, dtype=self.
torch.float32)
55 def fit(self, rows, *, epochs, batch_size, rng):
57 for _
in range(epochs):
58 order = self.
torch.as_tensor(rng.permutation(len(data)), device=self.
device)
59 for batch
in data[order].split(batch_size):
61 if not self.
torch.isfinite(loss):
62 raise ValueError(
"The policy autoencoder produced a nonfinite loss.")
63 self.
optimizer.zero_grad(set_to_none=
True)
66 _, errors = self.
encode(rows)
67 return float(errors.mean())
69 def encode(self, rows):
70 with self.
torch.no_grad():
73 errors = (self.
decoder(codes) - data).square().mean(dim=-1)
74 if not self.
torch.isfinite(errors).all():
75 raise ValueError(
"The policy autoencoder produced a nonfinite reconstruction.")
76 return codes, errors.cpu().numpy()
78 def mutate(self, codes, rows, parameter_noise):
79 codes = codes[self.
torch.as_tensor(rows, device=self.
device)]
80 noise = self.
_tensor(parameter_noise)
81 delta = _decoder_pullback(self.
torch, self.
decoder, codes, noise)
82 if not self.
torch.isfinite(delta).all():
83 raise ValueError(
"The decoder Jacobian produced a nonfinite mutation.")
84 with self.
torch.no_grad():
85 result = self.
decoder(codes + delta).cpu().numpy()
86 if not np.isfinite(result).all():
87 raise ValueError(
"The policy autoencoder produced a nonfinite offspring.")
94 """Bounded Policy Manifold Search (PoMS) using a native best-only grid.
96 Fit a deterministic autoencoder periodically on the occupied elite
97 vectors. For a parent at or below the mean reconstruction error at the
98 last fit, draw a Gaussian in normalized parameter coordinates and
99 multiply it by the transpose of the decoder Jacobian. Add this
100 perturbation to the parent's latent code and decode the result.
101 Less well-reconstructed parents receive direct parameter mutation.
103 :param container: Best-only scalar Grid or CVTGrid.
104 :param budget: Total attempted candidate evaluations.
105 :param dimension: Number of bounded real coordinates in each policy vector.
106 :param ind_domain: Shared finite lower and upper bounds.
107 :param batch_size: Maximum candidates in one generation.
108 :param latent_size: Size of the autoencoder bottleneck.
109 :param hidden_size: Width of the encoder and decoder hidden layers.
110 :param min_elites: Minimum measured archive size before fitting.
111 :param fit_interval: Minimum number of generations between refits.
112 :param fit_epochs: Number of archive passes per fit.
113 :param fit_batch_size: Maximum number of training rows per update.
114 :param learning_rate: Positive Adam learning rate.
115 :param sigma: Gaussian standard deviation in normalized [0, 1] coordinates.
116 :param seed: Seed for initialization, parent selection and fitting.
117 :param device: PyTorch CPU or CUDA device.
118 :param kwargs: Native algorithm options such as optimisation_task.
120 Archive admission uses scalar fitness. For an exploration-only
121 objective, return the same fitness in every niche.
124 _requires_proposed_genome =
True
126 def __init__(self, container, budget, dimension, ind_domain=(0., 1.), *, batch_size=32,
127 latent_size=4, hidden_size=64, min_elites=4, fit_interval=1, fit_epochs=5,
128 fit_batch_size=64, learning_rate=1e-3, sigma=.05, seed=0, device=
"cpu", **kwargs):
129 _validate_grid(container, empty=
False)
131 dimension = _positive_int(dimension,
"dimension")
132 latent_size = _positive_int(latent_size,
"latent_size")
133 if not (0. < learning_rate < np.inf
and 0. < sigma <= np.finfo(np.float32).max):
134 raise ValueError(
"Use positive finite learning_rate and representable sigma.")
135 self.
_sigma = float(sigma)
136 self.
_min_elites = _positive_int(min_elites,
"min_elites")
137 self.
_fit_interval = _positive_int(fit_interval,
"fit_interval")
138 self.
_epochs = _positive_int(fit_epochs,
"fit_epochs")
140 self.
_model_args = (_positive_int(hidden_size,
"hidden_size"), latent_size, learning_rate, device)
142 kwargs.setdefault(
"optimisation_task", container.fitness_weights
or "maximisation")
143 super().__init__(container, _positive_int(budget,
"budget"), dimension=dimension,
144 batch_size=_positive_int(batch_size,
"batch_size"), **kwargs)
147 """Reset model state and diagnostics while retaining the reporting archive."""
149 proposals, training, initialization = np.random.SeedSequence(self.
_seed).spawn(3)
150 self.
_rng = np.random.default_rng(proposals)
151 self.
_fit_rng = np.random.default_rng(training)
154 int(initialization.generate_state(1)[0]), device)
164 """Return the number of completed archive autoencoder fits."""
169 """Return wall-clock time spent fitting the autoencoder and measuring training error."""
174 """Return attempted proposals by random, parameter, or latent variation."""
182 self.
_tags = (
"random",) * size
185 parents = np.asarray([tuple(elite)
for elite
in self.
container], dtype=float)
186 if (parents.shape != (len(self.
container), self.
dimension)
or not np.isfinite(parents).all()
187 or np.any((parents < lower) | (parents > upper))):
188 raise ValueError(
"PolicyManifoldSearch needs finite archive vectors inside ind_domain.")
189 normalized = (parents - lower) / (upper - lower)
192 start = perf_counter()
195 self.
_seconds += perf_counter() - start
198 selected = normalized[self.
_rng.integers(len(parents), size=size)]
199 noise = self.
_rng.normal(0., self.
_sigma, selected.shape)
200 vectors = selected + noise
201 tags = np.full(size,
"parameter")
203 codes, errors = self.
_model.encode(selected)
204 eligible = np.flatnonzero(errors <= self.
_threshold)
206 vectors[eligible] = self.
_model.mutate(codes, eligible, noise[eligible])
207 tags[eligible] =
"latent"
208 self.
_vectors = np.clip(lower + (upper - lower) * np.clip(vectors, 0., 1.), lower, upper)
209 self.
_tags = tuple(tags.tolist())
215 def _generation_feedback(self, position):
216 return {
"variation_operator": self.
_tags[position]}
222 def _clear_generation(self):
223 super()._clear_generation()