QDpy
Loading...
Searching...
No Matches
mome_pgx.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""MOME-PGX for bounded continuous-action Gymnasium environments."""
7
8from collections import Counter, deque
9from dataclasses import dataclass
10
11import numpy as np
12
13from qdpy.containers.pareto import _sampling_crowding
14from .mome_p2c import _ParetoPolicySearch, _VectorReplay
15from .policy import _integer
16from .rollout import _seed
17from .td3 import OffPolicyStats, TD3Config, _TD3Learner
18
19__all__ = ["MOMEPGX", "MOMEPGXStats"]
20
21
23 """Read one signed objective from the shared vector transition buffer."""
24
25 def __init__(self, shared, objective, direction):
26 self.shared, self.objective, self.direction = shared, objective, direction
27
28 def sample(self, count, rng, device):
29 observation, action, rewards, successor, terminated = self.shared.sample(count, rng, device)
30 return observation, action, self.direction * rewards[:, self.objective], successor, terminated
31
32 def sample_observations(self, count, rng, device):
33 return self.shared.sample_observations(count, rng, device)
34
35
36
37@dataclass(frozen=True)
39 """Report total optimizer counts and started gradient candidates per objective."""
40
41 genetic_offspring: int = 0
42 objective_offspring: tuple[int, ...] = ()
43
44
45
47 """MOME-PGX from Janmohamed, Pierrot and Cully (GECCO 2023).
48
49 Use one transition buffer for all objectives and independent twin
50 critics and target actors for each objective. Sample cells uniformly
51 and then sample their members by finite crowding distance. ParetoGrid
52 truncation preserves boundary points when admitting measured policies.
53
54 :param env_factory: Factory for a single Gymnasium environment with Box spaces.
55 :param archive: Empty parentless ParetoGrid with crowding truncation.
56 :param reward_vector: Callable of (observation, action, successor, info)
57 returning one raw reward per archive objective.
58 :param descriptor: Callable of a completed Episode returning descriptor coordinates.
59 :param td3: Optional TD3Config for replay, optimizer, and target settings.
60 :param population_size: Even generation size, split equally between genetic
61 and gradient mutations. Gradient slots rotate among the objectives.
62 :param critic_steps: TD3 minibatch updates per objective and generation.
63 :param pg_steps: Adam steps per gradient-mutated policy.
64 :param pg_learning_rate: Adam step size for gradient mutation.
65 :param kwargs: Native neural MAP-Elites policy, evaluation, and seed arguments.
66 """
67
68 def __init__(self, env_factory, archive, *, reward_vector, descriptor, td3=None,
69 population_size=32, critic_steps=4, pg_steps=2, pg_learning_rate=.005, **kwargs):
70 if not callable(reward_vector):
71 raise TypeError("reward_vector must be callable.")
72 if "fitness" in kwargs:
73 raise TypeError("MOME-PGX uses measured vector returns.")
74 if not 0 < pg_learning_rate < np.inf:
75 raise ValueError("pg_learning_rate must be finite and positive.")
76 self.td3 = TD3Config() if td3 is None else td3
77 if not isinstance(self.td3, TD3Config):
78 raise TypeError("td3 must be a TD3Config.")
79 self._population = _integer(population_size, "population_size", 2)
80 if self._population % 2:
81 raise ValueError("population_size must be even.")
82 self._critic_steps = _integer(critic_steps, "critic_steps")
83 self._pg_steps = _integer(pg_steps, "pg_steps")
84 self._pg_rate = pg_learning_rate
85 self.reward_vector = reward_vector
86 super().__init__(env_factory, archive, descriptor=descriptor, **kwargs)
87 self._objectives = len(archive.fitness_domain)
88 self._replay = _VectorReplay(self.td3.replay_capacity, self._actor, self._objectives)
89 self._learners = [
90 _TD3Learner(self._new_actor(_seed(self._training_rng)), self.td3, _seed(self._training_rng),
91 Counter(), replay=_ObjectiveReplay(self._replay, i, np.sign(weight)))
92 for i, weight in enumerate(archive.fitness_weights)
93 ]
94 self._proposals = deque()
95 self._measured = []
96 self._objective_offspring = [0] * self._objectives
97 self._next_objective = 0
98
99
100 @property
101 def stats(self):
102 """Report policy counts in archive objective order."""
103 counts = dict(self._counts)
104 for name in ("actor_updates", "critic_updates", "optimizer_steps", "policy_gradient_steps"):
105 counts[name] = sum(learner.counts[name] for learner in self._learners)
106 return MOMEPGXStats(**counts, replay_size=self._replay.size,
107 objective_offspring=tuple(self._objective_offspring))
108
109 def _parent(self):
110 fronts = [front for front in self.archive.solutions.values() if front]
111 front = fronts[self._selection_rng.integers(len(fronts))]
112 distances = _sampling_crowding([individual.fitness.values for individual in front])
113 total = distances.sum()
114 return front[self._selection_rng.choice(len(front), p=distances / total if total else None)]
115
116 def _propose_generation(self):
117 for learner in self._learners:
118 for _ in range(self._critic_steps):
119 learner.update()
120 for _ in range(self._population // 2):
121 self._proposals.append(("genetic_offspring", None, self._genetic_parameters()))
122 objective = self._next_objective
123 actor = self.policy_for(self._parent())
124 self._learners[objective].improve_offspring(actor, self._pg_steps, self._pg_rate)
125 self._proposals.append(("pg_offspring", objective, actor._parameters()))
126 self._next_objective = (objective + 1) % self._objectives
127
128 def _proposal(self):
129 if not self._proposals:
130 if not self._can_select():
131 return "random", self._new_actor(_seed(self._actor_rng))._parameters()
132 if (self._replay.size < self.td3.batch_size
133 or self._counts["evaluation_steps"] < self.td3.learning_starts):
134 return "genetic_offspring", self._genetic_parameters()
136 operator, objective, parameters = self._proposals.popleft()
137 if objective is not None:
138 self._objective_offspring[objective] += 1
139 return operator, parameters
140
141 def _admit_candidate(self, candidate):
142 if candidate is not None:
143 self._measured.append(candidate)
144 if not self._proposals:
145 self._commit_measured()
146
147 def _commit_measured(self):
148 if self._measured:
149 admitted = self.archive._merge_fronts(self._measured)
150 self._counts["archive_updates"] += len(admitted)
151 self._measured.clear()
152
153
154 def train(self, max_env_steps):
155 """Merge the measured prefix if an interaction limit ends a generation early."""
156 super().train(max_env_steps)
157 self._commit_measured()
158 return self.stats
Count genetic and objective-specific policy-gradient candidates.
Definition mome_pgx.py:38
Evolve local Pareto fronts with Iso+LineDD and per-objective TD3 mutations.
Definition mome_pgx.py:46
train(self, max_env_steps)
Score complete episodes within an additional step limit and merge their fronts.
Definition mome_pgx.py:154
stats(self)
Return cumulative environment, replay, and optimizer counts.
Definition mome_pgx.py:101
policy_for(self, individual, *, device=None, seed=0)
Rebuild an independent inference actor from an archived genome.
Definition search.py:226
_new_actor(self, seed, device=None)
Definition search.py:112
Cumulative optimizer, offspring, and replay counts for off-policy learners.
Definition td3.py:76
Settings for the shared TD3 actor, critics, and replay buffer.
Definition td3.py:25