60 """Train policy-conditioned TD3 critics for a single representation slot."""
62 def __init__(self, actor, config, replay, counts, seed):
64 self.
rng = np.random.default_rng(seed)
65 self.
noise = torch.Generator(device=actor.device).manual_seed(_seed(self.
rng))
67 self.
head_size = _head_vector(actor).numel()
68 self.
encoder = actor._network[:-1]
72 _seed(self.
rng), actor.device, nn.ReLU)
for _
in range(2))
74 self.
actor_optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=config.actor_learning_rate)
78 def update(self, heads):
80 state, action, rewards, next_state, terminated = self.
replay.sample(
81 config.batch_size, self.
rng, actor.device)
82 head = actor._tensor(heads[self.
rng.integers(len(heads), size=len(state))])
83 critic_state = torch.cat((state, head), dim=-1)
85 noise = torch.randn(action.shape, generator=self.
noise, device=actor.device)
86 noise = (noise * config.target_noise).clamp(-config.noise_clip, config.noise_clip)
88 target_state = torch.cat((next_state, head), dim=-1)
89 first, second = (_critic(target, target_state, next_actions)
for target
in self.
targets)
90 target = _bellman_target(rewards, terminated, first, second, config.gamma)
91 loss = _critic_loss(self.
critics, critic_state, action, target)
96 self.
counts[
"critic_updates"] += 1
97 self.
counts[
"optimizer_steps"] += 1
98 if self.
updates % config.policy_delay == 0:
100 cooperative = _apply_heads(hidden, head, self.
action_size)
101 greedy_head = _head_vector(actor).expand(len(state), -1)
102 greedy_state = torch.cat((state, greedy_head), dim=-1)
103 greedy = actor._network[-1](hidden).tanh()
104 loss = -.5 * (_critic(self.
critics[0], critic_state, cooperative).mean()
105 + _critic(self.
critics[0], greedy_state, greedy).mean())
106 if not torch.isfinite(loss):
107 raise ValueError(
"CCQD produced a nonfinite representation loss.")
108 parameters = actor._trainable_parameters()
109 for parameter, grad
in zip(parameters, torch.autograd.grad(loss, parameters)):
110 parameter.grad = grad
114 self.
counts[
"actor_updates"] += 1
115 self.
counts[
"optimizer_steps"] += 1
117 def improve(self, head, steps):
118 actor = _DecisionActor.borrow(self.
actor)
119 actor._set_parameters(head)
120 optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=self.
config.actor_learning_rate)
121 for _
in range(steps):
122 state = self.
replay.sample_observations(self.
config.batch_size, self.
rng, actor.device)
123 context = _head_vector(actor).expand(len(state), -1)
124 _step_actor(actor, optimizer, self.
critics[0], state,
125 critic_observations=torch.cat((state, context), dim=-1))
126 self.
counts[
"policy_gradient_steps"] += 1
127 self.
counts[
"optimizer_steps"] += 1
128 return actor._parameters()
130 def replace_from(self, other):
131 self.
actor._network.load_state_dict(other.actor._network.state_dict())
132 self.
target_encoder.load_state_dict(other.target_encoder.state_dict())
133 self.
critics.load_state_dict(other.critics.state_dict())
134 self.
targets.load_state_dict(other.targets.state_dict())
142 """Cooperatively evolve fixed-layout deterministic Box policies.
144 Each representation has a greedy actor and policy-conditioned twin
145 TD3 critics. The critics consume raw decision-head weights as context,
146 with shared environment replay. At each generation archived heads
147 pair with current representations. Decision variation uses Iso+LineDD
148 or actor gradients. The fixed reporting archive stores the measured
149 full policy weights, so changing a representation cannot mutate
150 previously measured policies.
152 :param env_factory: Factory for a single Gymnasium environment.
153 :param archive: Empty parentless maximizing Grid or CVTGrid.
154 :param descriptor: Callback mapping a complete episode to its measured descriptors.
155 :param policy: PolicyConfig with at least one hidden layer.
156 :param td3: TD3Config for all representation learners.
157 :param representations: Number of live policy representations.
158 :param batch_size: Completed policies per generation, at least the number of representations.
159 :param critic_steps: TD3 minibatch updates per representation per eligible generation.
160 :param pg_steps: Gradient updates of each gradient offspring.
161 :param iso_sigma: Independent Iso+LineDD noise for genetic heads.
162 :param line_sigma: Shared direction noise for genetic heads.
163 :param max_episode_steps: Hard maximum steps per episode.
164 :param seed: Separate seed streams for initialization and rollouts.
165 :param device: CPU or CUDA Torch device.
168 def __init__(self, env_factory, archive, *, descriptor, policy=None, td3=None, representations=3,
169 batch_size=12, critic_steps=4, pg_steps=2, iso_sigma=.02, line_sigma=.2,
170 max_episode_steps=300, seed=0, device="cpu"):
171 NeuralMAPElites._validate_archive(archive)
172 if not callable(env_factory)
or not callable(descriptor):
173 raise TypeError(
"env_factory and descriptor must be callable.")
174 if not 0. <= iso_sigma < np.inf
or not 0. <= line_sigma < np.inf:
175 raise ValueError(
"Use finite nonnegative mutation scales.")
178 self.
_count = _integer(representations,
"representations", 2)
179 self.
_batch = _integer(batch_size,
"batch_size", self.
_count)
181 self.
_pg_steps = _integer(pg_steps,
"pg_steps")
182 self.
_horizon = _integer(max_episode_steps,
"max_episode_steps")
184 if not isinstance(self.
_config, TD3Config):
185 raise TypeError(
"td3 must be a TD3Config.")
186 self.
_rng, self.
_rollouts = (np.random.default_rng(stream)
for stream
in
187 np.random.SeedSequence(_integer(seed,
"seed", 0)).spawn(2))
188 with _open_environment(env_factory)
as env:
190 seed=_seed(self.
_rng), device=device)
191 if not self.
_actor.config.hidden_sizes:
192 raise ValueError(
"Use at least one hidden layer for the shared representation.")
195 prod(self.
_actor._actions.shape))
198 for _
in range(self.
_count)]
204 """Return cumulative costs, including all representation learner updates."""
209 """Count archived full policies associated with each representation slot."""
210 counts = Counter(ind.scores[
"ccqd_representation"]
for ind
in self.
archive)
211 return tuple(counts[i]
for i
in range(self.
_count))
215 and self.
_counts[
"evaluation_steps"] >= self.
_config.learning_starts)
217 pool = np.asarray([ind[-self.
_head_size:]
for ind
in self.
archive], dtype=np.float32)
222 head_radius = self.
_actor._network[-1].in_features ** -.5
223 for index
in range(self.
_batch):
224 slot = int(self.
_rng.integers(self.
_count))
if ready
else index % self.
_count
227 first, second = self.
_rng.integers(len(pool), size=2)
229 head = learner.improve(pool[first], self.
_pg_steps)
232 head = iso_line_dd(pool[first], pool[second], iso_sigma=self.
_iso_sigma,
236 head = self.
_rng.uniform(-head_radius, head_radius, size=self.
_head_size)
238 parameters = np.concatenate((encoders[slot], head))
239 self.
_queue.append((slot, parameters.astype(np.float32), gradient))
241 def _measure(self, archive, episode):
242 descriptor = np.asarray(self.
_descriptor(episode), dtype=float)
243 quality = episode.return_
244 if (descriptor.shape != (len(archive.features_domain),)
or not np.isfinite(descriptor).all()
245 or not isfinite(quality)):
246 raise ValueError(
"CCQD needs finite return and a descriptor for each grid dimension.")
247 if not (archive.in_bounds((quality,), archive.fitness_domain)
248 and archive.in_bounds(descriptor, archive.features_domain)):
250 return quality, tuple(descriptor)
253 def _offer(archive, measurement, parameters, representation):
254 quality, descriptor = measurement
255 cell = archive.index_grid(descriptor)
256 if archive.free < 1
and not archive.solutions[cell]:
260 scores={
"ccqd_representation": representation}))
is not None
263 for slot, parameters, measurement
in self.
_measured:
268 source = int(np.argmax(counts))
269 for slot, count
in enumerate(counts):
272 self.
_counts[
"representation_replacements"] += 1
273 self.
_counts[
"generations"] += 1
275 def _record(self, observation, action, reward, successor, terminated):
276 self.
_replay.add(observation, self.
_actor._encode(action), reward, successor, terminated)
280 """Retain replay from budget-cut episodes and retry their candidates."""
282 with _open_environment(self.
_factory)
as env:
283 _check_spaces(env, self.
_actor)
285 while budget.remaining:
288 slot, parameters, gradient = self.
_queue[0]
289 self.
_actor._set_parameters(parameters)
290 self.
_counts[
"candidate_attempts"] += 1
291 before = budget.remaining
292 episode = _evaluate_episode(cursor, self.
_actor, budget, on_transition=self.
_record)
294 self.
_counts[
"prefix_steps"] += before - budget.remaining
297 self.
_counts[
"evaluated_policies"] += 1
298 self.
_counts[
"pg_offspring"] += gradient
300 if measurement
is None:
301 self.
_counts[
"out_of_domain"] += 1
303 self.
_measured.append((slot, parameters, measurement))
310 """Return a portable ContinuousPolicy with the original measured weights."""
311 actor = self.
_actor._new(0, device)
312 actor._set_parameters(individual)
317 """Return an independently exportable actor after at least one archive admission."""
319 raise RuntimeError(
"The decision archive has no measured elite.")
323 def audit(self, max_env_steps, *, seed=0):
324 """Return fresh measured placements without updating replay or the decision archive."""
325 archive = _stage_archive(self.
archive)
329 actor = self.
_actor._new(0)
331 with _open_environment(self.
_factory)
as env:
332 _check_spaces(env, actor)
333 rng = np.random.default_rng(_integer(seed,
"seed", 0))
335 actor._set_parameters(record)
337 episode = _evaluate_episode(cursor, actor, budget)
341 measurement = self.
_measure(archive, episode)
342 if measurement
is not None:
343 self.
_offer(archive, measurement, actor._parameters(), record.scores[
"ccqd_representation"])
344 return CCQDAudit(archive, counts[
"evaluation_steps"], episodes)