74 """Train sparse controllers with branch-private critics and memories.
76 Alternate diagonal CEM parameter proposals, branch continuation,
77 and Bernoulli mask proposals at explicit sparsity regimes. The
78 bounded training pool retains one branch per descriptor cell and
79 tier. Admission uses raw return and dissimilarity in behaviour, mask,
80 and critic predictions. Nearest-better roots guide continuation.
81 The native grid independently records raw evaluated return.
83 :param env_factory: Callable returning a fresh Box/Box environment.
84 :param archive: Empty, parentless, maximizing Grid or CVTGrid.
85 :param descriptor: Descriptor callback on each completed episode.
86 :param policy: PolicyConfig for a deterministic actor with a hidden layer.
87 :param td3: TD3Config for each branch's learning state.
88 :param branch_capacity: Maximum number of retained learning branches.
89 :param training_steps_per_candidate: Training interaction cap per proposal.
90 :param keep_fractions: Mean hidden-neuron keep fractions for mask proposals.
91 :param sparsity_edges: Increasing thresholds between structural tiers.
92 :param novelty_weight: Weight of normalized nearest-branch distance.
93 :param masks: Enable hidden-neuron masking.
94 :param private_critics: Keep a separate TD3 critic pair for each branch.
95 :param evaluation_episodes: Number of complete episodes per measurement.
96 :param max_episode_steps: External rollout horizon.
97 :param seed: Private initialization, proposal, collection, and evaluation seed.
98 :param device: Torch CPU or CUDA device.
101 def __init__(self, env_factory, archive, *, descriptor, policy=None, td3=None, branch_capacity=12,
102 training_steps_per_candidate=48, keep_fractions=(1., .5, .25),
103 sparsity_edges=(.10, .60, .85), novelty_weight=.25, masks=
True,
104 private_critics=
True, evaluation_episodes=1, max_episode_steps=300, seed=0, device=
"cpu"):
105 self.
config = (
TD3Config(replay_capacity=2048, batch_size=32, learning_starts=32,
106 critic_hidden_sizes=(32, 32))
if td3
is None else td3)
107 if not isinstance(self.
config, TD3Config):
108 raise TypeError(
"td3 must be a TD3Config.")
109 if type(masks)
is not bool
or type(private_critics)
is not bool:
110 raise TypeError(
"masks and private_critics must be Boolean.")
111 fractions, edges = tuple(map(float, keep_fractions)), tuple(map(float, sparsity_edges))
112 if (
not fractions
or not all(0. < value <= 1.
for value
in fractions)
113 or not all(lo < hi
for lo, hi
in zip((0., *edges), (*edges, 1.)))
114 or not 0. <= novelty_weight < np.inf):
115 raise ValueError(
"Use positive keep fractions, increasing sparsity edges and finite novelty weight.")
116 self.
_capacity = _integer(branch_capacity,
"branch_capacity")
117 self.
_training_steps = _integer(training_steps_per_candidate,
"training_steps_per_candidate")
120 self.
_mask_rng = np.random.default_rng(np.random.SeedSequence(_integer(seed,
"seed", 0), spawn_key=(4,)))
121 policy =
PolicyConfig((32, 32))
if policy
is None else policy
122 if not isinstance(policy, PolicyConfig)
or not policy.hidden_sizes:
123 raise ValueError(
"Use a PolicyConfig with at least one hidden layer.")
124 super().__init__(env_factory, archive, descriptor=descriptor, policy=policy,
125 evaluation_episodes=evaluation_episodes, max_episode_steps=max_episode_steps,
126 seed=seed, device=device)
127 domain = np.asarray(archive.features_domain, dtype=float)
128 self.
_span = domain[:, 1] - domain[:, 0]
129 if not (self.
_span > 0.).all()
or not np.isfinite(self.
_span).all():
130 raise ValueError(
"SV-QD-RL requires finite, increasing descriptor intervals.")
131 self.
_widths = policy.hidden_sizes
132 self.
_mean = self.
_actor._parameters().astype(float)
138 def _build_actor(self, env, config, seed, device):
139 return ContinuousPolicy(env.observation_space, env.action_space, config=config, seed=seed, device=device)
143 """Return real interaction counts, optimizer work, and live state size."""
144 pool = tuple(self.
_entries.values())
146 distinct_masks=len({entry[0].mask
for entry
in pool}),
147 replay_size=sum(entry[1].learner.replay.size
for entry
in pool))
151 """Return measured branches in cell and tier order."""
152 return tuple(summary
for _, (summary, _)
in sorted(self.
_entries.items()))
154 def _sample_mask(self, structural):
160 probabilities = np.clip(keep + frequency - frequency.mean(), .03, .97)
161 layer = self.
_mask_rng.random(len(frequency)) < probabilities
163 layer[int(self.
_mask_rng.integers(len(layer)))] =
True
164 mask.extend(map(bool, layer))
167 def _new_branch(self, structural):
172 for layer, width
in enumerate(self.
_widths):
173 position = 2 * layer + 1
174 gate =
_Gate(mask[offset:offset + width], actor.device)
175 actor._network[position] = nn.Sequential(actor._network[position], gate)
180 self.
_shared = (learner.critics, learner.critic_targets, learner.critic_optimizer)
181 learner.critics, learner.critic_targets, learner.critic_optimizer = self.
_shared
186 for tier
in sorted({key[1]
for key
in self.
_entries}):
187 group = [entry
for key, entry
in self.
_entries.items()
if key[1] == tier]
188 distances = [min((self.
_behaviour(row, other)
for other, _
in group
189 if other.fitness > row.fitness), default=np.inf)
for row, _
in group]
190 finite = [distance
for distance
in distances
if np.isfinite(distance)]
191 threshold = np.median(finite)
if finite
else np.inf
192 roots.extend(branch
for (_, branch), distance
in zip(group, distances, strict=
True)
193 if not np.isfinite(distance)
or distance > threshold)
195 shared = {}
if self.
_shared is None else {id(item): item
for item
in self.
_shared}
196 return deepcopy(branch, shared)
198 def _collect(self, env, budget, branch):
199 actor, learner = branch.actor, branch.learner
202 old_counts = learner.counts.copy()
203 for _
in range(allowed):
206 observation = cursor.observation
207 with torch.no_grad():
208 mean = actor._normalized(actor._tensor(observation)).cpu().numpy()
209 noise = self.
_training_rng.normal(0., self.
config.exploration_noise, prod(actor._actions.shape))
210 action = actor._decode(np.clip(mean + noise, -1., 1.))
211 recorded = action.copy()
212 reward, terminated, _, _ = cursor.step(action, budget,
"training_steps")
213 learner.record(observation, recorded, reward, cursor.observation, terminated)
215 if learner.ready(branch.steps):
217 self.
_counts.update(learner.counts - old_counts)
219 def _behaviour(self, first, second):
220 return float(np.linalg.norm((np.asarray(first.descriptor) - second.descriptor) / self.
_span)
221 / np.sqrt(len(self.
_span)))
223 def _score(self, summary, reference):
224 def separation(other):
225 mask = np.mean(np.not_equal(summary.mask, other.mask))
226 values, competitor = np.asarray(summary.value_profile), np.asarray(other.value_profile)
227 profile = np.mean(abs(values - competitor) / (1. + abs(values) + abs(competitor)))
228 return (self.
_behaviour(summary, other) + mask + profile) / 3.
230 return summary.fitness + self.
_novelty_weight * min(map(separation, reference), default=0.)
232 def _admit(self, summary, branch):
233 key = (summary.cell, summary.tier)
235 rivals = [key]
if key
in self.
_entries else []
236 tiers = Counter(tier
for _, tier
in self.
_entries)
238 crowded = max(tiers, key=
lambda tier: (tiers[tier], -tier))
240 tier = summary.tier
if tiers[summary.tier] == 1
else crowded
241 rivals = [stored
for stored
in self.
_entries if stored[1] == tier]
245 [item
for coordinate, (item, _)
in self.
_entries.items()
246 if coordinate != stored])
248 rival = min(rivals, key=score)
249 others = [item
for stored, (item, _)
in self.
_entries.items()
if stored != rival]
250 if tiers[summary.tier]
and self.
_score(summary, others) <= score(rival):
253 self.
_entries[key] = (summary, branch)
254 self.
_counts[
"branch_updates"] += 1
257 def _folded(self, branch):
260 plain._set_parameters(branch.actor._parameters())
262 for layer, width
in enumerate(self.
_widths):
263 bits = torch.tensor(branch.mask[offset:offset + width], dtype=torch.bool, device=plain.device)
264 plain._network[2 * (layer + 1)].weight.mul_(bits)
270 """Return a standard ContinuousPolicy that supports portable NPZ export."""
273 def _report(self, episodes, branch, phase):
274 quality = float(np.mean([episode.return_
for episode
in episodes]))
275 rows = [np.asarray(self.
_descriptor(episode), dtype=float)
for episode
in episodes]
276 self.
_offer(episodes, phase, descriptors=rows, quality=quality, parameters=self.
_folded(branch)._parameters())
277 descriptor = tuple(map(float, np.mean(rows, axis=0)))
278 if (
not self.
archive.in_bounds(descriptor, self.
archive.features_domain)
279 or not self.
archive.in_bounds((quality,), self.
archive.fitness_domain)):
282 self.
_anchors = branch.actor._tensor(episodes[0].observations[:min(8, episodes[0].steps)])
283 with torch.no_grad():
284 actions = branch.actor._normalized(self.
_anchors)
285 values = torch.stack([_critic(net, self.
_anchors, actions)
for net
in branch.learner.critics])
286 profile = values.mean(dim=0).cpu().tolist()
287 if not np.isfinite(profile).all():
288 raise ValueError(
"SV-QD-RL critic profiles must be finite.")
289 sparsity = 1. - sum(branch.mask) / len(branch.mask)
290 tier = int(np.searchsorted(self.
_edges, sparsity, side=
"right"))
291 cell = self.
archive.index_grid(descriptor)
292 self.
_admit(
SVBranchSummary(cell, tier, quality, descriptor, branch.mask, sparsity, tuple(profile)), branch)
294 def _fit_proposals(self):
295 rows = sorted(self.
_entries.values(), key=
lambda entry: entry[0].fitness, reverse=
True)
297 top = rows[:max(1, (len(rows) + 1) // 2)]
298 parameters = np.stack([branch.actor._parameters()
for _, branch
in top])
299 self.
_mean = .75 * self.
_mean + .25 * parameters.mean(axis=0, dtype=float)
300 self.
_std = np.maximum(.04, .75 * self.
_std + .25 * parameters.std(axis=0, dtype=float))
301 masks = [row.mask
for row, _
in rows
if row.sparsity > 0.]
303 selected = masks[:max(1, (len(masks) + 1) // 2)]
308 """Retain only fully evaluated candidates and account for partial rollouts."""
310 with _open_environment(self.
_factory)
as env:
311 _check_spaces(env, self.
_actor)
312 while budget.remaining:
313 turn = self.
_counts[
"candidate_attempts"] % 3
314 self.
_counts[
"candidate_attempts"] += 1
316 phase, branch =
"continuations", self.
_continue()
318 structural = self.
_masks and turn == 2
319 phase =
"mask_proposals" if structural
else "parameter_proposals"
324 episodes = [_evaluate_episode(cursor, branch.actor, budget)
for _
in range(self.
_episodes)]
325 if any(episode
is None for episode
in episodes):
327 self.
_counts[
"evaluated_policies"] += 1
328 self.
_report(episodes, branch, phase)