QDpy
Loading...
Searching...
No Matches
dmome.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""PyTorch DQN control of user-supplied combinatorial operators."""
7
8from collections import deque
9from copy import deepcopy
10from dataclasses import dataclass
11
12import numpy as np
13import torch
14from torch import nn
15from torch.nn import functional as F
16
17from qdpy.algorithms.operator_mome import OperatorMOME
18from .policy import PolicyConfig, _integer, _mlp
19from .rollout import _seed
20from .td3 import _checked_step
21
22__all__ = ["DMOME", "DMOMEConfig"]
23
24
25
26@dataclass(frozen=True)
28 """Train one optimizer step per operator feedback once replay is ready.
29
30 :param hidden_sizes: Widths of the operator-value network.
31 :param replay_capacity: Maximum retained archive feedback transitions.
32 :param batch_size: Number of sampled feedback transitions per update.
33 :param learning_rate: Adam learning rate.
34 :param discount: Future archive reward discount, in [0, 1).
35 :param epsilon: Probability of uniform operator exploration.
36 :param target_period: Optimizer steps between target-network copies.
37 """
38
39 hidden_sizes: tuple[int, ...] = (32, 32)
40 replay_capacity: int = 2048
41 batch_size: int = 32
42 learning_rate: float = 5e-4
43 discount: float = .9
44 epsilon: float = .15
45 target_period: int = 24
46
47 def __post_init__(self):
48 object.__setattr__(self, "hidden_sizes", PolicyConfig(self.hidden_sizes).hidden_sizes)
49 for name in ("replay_capacity", "batch_size", "target_period"):
50 object.__setattr__(self, name, _integer(getattr(self, name), name))
51 if (self.batch_size > self.replay_capacity or not 0. < self.learning_rate < np.inf
52 or not 0. <= self.discount < 1. or not 0. <= self.epsilon <= 1.):
53 raise ValueError("Use valid replay, learning-rate, discount, and exploration settings.")
54
55
56
58 """Use a DQN over a bounded summary of the current parent and archive.
59
60 State includes global and local occupancy, recent admission reward,
61 oriented parent fitness, and the parent's descriptor coordinates.
62 The next state describes the next sampled parent. Replay and a lagged
63 target network allow learning across multiple search calls.
64
65 :param archive: An empty two-objective hypervolume ParetoGrid.
66 :param initializer: Callback taking a private generator and returning a genome.
67 :param operators: Mapping of names to callbacks taking (parent, donor, rng).
68 :param config: Optional DMOMEConfig.
69 :param initial_samples: Number of initial random candidates.
70 :param seed: Seed for proposal and controller streams.
71 :param device: Torch CPU or CUDA device.
72 """
73
74 def __init__(self, archive, *, initializer, operators, config=None, initial_samples=16, seed=0, device="cpu"):
75 super().__init__(archive, initializer=initializer, operators=operators,
76 initial_samples=initial_samples, seed=seed)
77 self.config = DMOMEConfig() if config is None else config
78 if not isinstance(self.config, DMOMEConfig):
79 raise TypeError("config must be a DMOMEConfig.")
80 self._device = torch.device(device)
81 streams = np.random.SeedSequence(seed, spawn_key=(4,)).spawn(2)
82 initialization, self._sampling = map(np.random.default_rng, streams)
83 self._online = _mlp(5 + len(archive.features_domain), len(operators),
84 PolicyConfig(self.config.hidden_sizes), _seed(initialization), self._device, nn.ReLU)
85 self._target = deepcopy(self._online).requires_grad_(False)
86 self._optimizer = torch.optim.Adam(self._online.parameters(), lr=self.config.learning_rate)
87 self._replay = deque(maxlen=self.config.replay_capacity)
88
89 def _choose_operator(self, state):
90 if len(self._replay) < self.config.batch_size or self._choice.random() < self.config.epsilon:
91 return super()._choose_operator(state)
92 with torch.no_grad():
93 return int(self._online(torch.as_tensor(state, device=self._device)).argmax().item())
94
95 def _observe(self, state, action, reward, successor):
96 self._replay.append((state, action, reward, successor))
97 if len(self._replay) < self.config.batch_size:
98 return
99 indices = self._sampling.integers(len(self._replay), size=self.config.batch_size)
100 states, actions, rewards, next_states = zip(*(self._replay[i] for i in indices))
101 inputs = torch.as_tensor(np.stack(states), device=self._device)
102 selections = torch.as_tensor(actions, dtype=torch.int64, device=self._device)
103 predicted = self._online(inputs).gather(1, selections[:, None]).squeeze(1)
104 with torch.no_grad():
105 future = self._target(torch.as_tensor(np.stack(next_states), device=self._device)).amax(dim=1)
106 target = torch.as_tensor(rewards, dtype=torch.float32, device=self._device) + self.config.discount * future
107 loss = F.smooth_l1_loss(predicted, target)
108 if not torch.isfinite(loss):
109 raise ValueError("The operator DQN produced a nonfinite loss.")
110 self._optimizer.zero_grad(set_to_none=True)
111 loss.backward()
112 _checked_step(self._optimizer)
113 self._counts["optimizer_steps"] += 1
114 if self._counts["optimizer_steps"] % self.config.target_period == 0:
115 self._target.load_state_dict(self._online.state_dict())
116 self._counts["target_syncs"] += 1
Illuminate a ParetoGrid using user-defined operators and archive feedback.
Settings for the bounded replay and DQN operator controller.
Definition dmome.py:27
Adapt DMOME's operator selection and archive feedback to generic two-objective problems.
Definition dmome.py:57
_observe(self, state, action, reward, successor)
Definition dmome.py:95
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36