5"""Run small CPU comparisons and write one JSON row per seed and method."""
8from dataclasses
import asdict
10from time
import perf_counter
13from scipy.spatial
import cKDTree
14from sklearn.cluster
import KMeans
15from threadpoolctl
import threadpool_limits
21def centroid_trials(seed):
22 """Compare initialization time and Monte Carlo cell-volume dispersion."""
23 for dimension
in (2, 12):
25 rng = np.random.default_rng(seed)
26 probe = rng.random((12_000, dimension))
27 domain = ((0., 1.),) * dimension
28 for method
in (
"kmeans",
"sobol",
"halton",
"blue-noise",
"uniform"):
29 begin = perf_counter()
30 if method ==
"kmeans":
31 points = rng.random((4096, dimension))
32 centers = KMeans(count, random_state=seed, n_init=1).fit(points).cluster_centers_
34 centers = generate_centroids(count, domain, method=method, seed=seed)
35 elapsed = perf_counter() - begin
36 cell = cKDTree(centers).query(probe)[1]
37 volumes = np.bincount(cell, minlength=count) / len(probe)
38 yield dict(method=method, seed=seed, dimension=dimension, cells=count, probes=len(probe),
39 setup_seconds=elapsed, volume_cv=float(volumes.std() / volumes.mean()),
40 missed_cells=int(np.count_nonzero(volumes == 0)))
44 """Refine six starts on a two-dimensional landscape with six local optima."""
45 peaks = np.asarray([(x, y)
for x
in (.17, .5, .83)
for y
in (.24, .76)])
46 heights = np.array([.94, .97, .96, 1., .95, .98])
49 return Grid(shape=(3, 2), features_domain=((0., 1.),) * 2,
50 fitness_domain=((0., 1.),), fitness_weights=(1.,))
53 quality = max(0., float((heights - 4. * ((peaks - point)**2).sum(axis=1)).max()))
54 return (quality,), point
56 def refine(start, objective, rng):
57 current = np.asarray(start)
58 best = objective(current)
59 axes = np.asarray(((1, 0), (-1, 0), (0, 1), (0, -1)))
60 for step
in (.12, .06, .03):
61 candidates = np.clip(current + step * axes, 0., 1.)
62 scores = [objective(row)
for row
in candidates]
63 nearest = np.argmin(scores)
64 if scores[nearest] < best:
65 best, current = scores[nearest], candidates[nearest]
67 for mode
in (
"archive",
"random"):
68 result = qd_seeded_refinement(archive(), archive(), evaluate, refine, dimension=2,
69 search_budget=96, starts=6, refinement_budget_per_start=13, initial_samples=60,
70 seed_selection=mode, seed=seed)
71 yield dict(method=mode, seed=seed, search_calls=result.search_evaluations,
72 refinement_calls=result.refinement_evaluations, starts=len(result.starts),
73 refined_cells=result.archive.filled_bins, qd_score=result.archive.qd_score(),
74 improved=sum(row.fitness > row.initial_fitness
for row
in result.starts))
77def llmatic_trials(seed):
78 """Train ridge readouts of small networks proposed by a local typed generator."""
79 rng = np.random.default_rng(154)
80 inputs = rng.uniform(-1., 1., (192, 3))
81 labels = np.where(np.sin(4 * inputs[:, 0]) + inputs[:, 1] * inputs[:, 2] > 0., 1., -1.)
82 widths = (4, 8, 12, 16, 20)
83 activations = (
"tanh",
"relu",
"sine")
84 prompts = (
"change width",
"alter depth",
"change activation",
"resample network")
87 layers, activation = spec
88 token = activations.index(activation)
89 rng = np.random.default_rng(np.random.SeedSequence([seed, token, *layers]))
93 source = features.shape[1]
94 hidden = features @ rng.normal(0., 2. / np.sqrt(source), (source, width)) + rng.uniform(-1., 1., width)
95 features = (np.tanh(hidden)
if token == 0
else np.maximum(hidden, 0.)
if token == 1
else np.sin(hidden))
96 operations += source * width
97 features = np.column_stack((features, np.ones(len(features))))
98 train, valid = features[:128], features[128:]
99 weights = np.linalg.solve(train.T @ train + .04 * np.eye(train.shape[1]), train.T @ labels[:128])
100 accuracy = float(((valid @ weights > 0.) == (labels[128:] > 0.)).mean())
101 return accuracy, (max(layers) / len(layers), float(operations + len(weights)))
103 def generate(request, rng):
104 layers, activation = request.parents[0]
105 if request.crossover:
106 other, second_activation = request.parents[1]
107 layers = (*layers[:rng.integers(1, len(layers) + 1)], *other[rng.integers(len(other)):])[:3]
108 activation = second_activation
if rng.random() < request.temperature
else activation
109 elif request.prompt ==
"change width":
110 slot = int(rng.integers(len(layers)))
111 alternatives = tuple(width
for width
in widths
if width != layers[slot])
112 layers = (*layers[:slot], int(rng.choice(alternatives)), *layers[slot + 1:])
113 elif request.prompt ==
"alter depth":
114 layers = (*layers, int(rng.choice(widths)))
if len(layers) < 3
else layers[:-1]
115 elif request.prompt ==
"change activation":
116 activation = str(rng.choice([choice
for choice
in activations
if choice != activation]))
118 layers = tuple(map(int, rng.choice(widths, size=int(rng.integers(1, 4)))))
119 activation = str(rng.choice(activations))
120 return layers, activation
122 for mode, exploration
in ((
"curiosity", .25), (
"uniform-prompts", 1.)):
123 network = Grid(shape=(8, 8), features_domain=((0., 20.), (0., 900.)), fitness_domain=((0., 1.),))
124 prompt = Grid(shape=(4, 6), features_domain=((0., 1.),) * 2, fitness_domain=((0., np.inf),))
125 result = llmatic(network, prompt, initial=((4,),
"tanh"), prompts=prompts, generate=generate,
126 evaluate=evaluate, proposal_budget=192, evaluation_budget=56, batch_size=8,
127 crossover_neighbors=2, prompt_exploration=exploration, seed=seed)
128 yield dict(method=mode, seed=seed, proposal_calls=result.proposals, architecture_calls=result.evaluations,
129 duplicates=result.duplicates, filled=network.filled_bins, prompt_cells=prompt.filled_bins,
130 qd_score=network.qd_score(), best_accuracy=network.best.fitness.values[0])
133def acdc_trials(seed):
134 """Compare mutable and fixed arithmetic task panels on a separate audit."""
135 cells = tuple((operation, difficulty, 0)
for operation, difficulty
in enumerate((3, 3, 2, 3)))
136 seeds = ((4, 1, 1, 1), (1, 4, 1, 1), (2, 2, 2, 2), (1, 1, 1, 4))
137 audit = tuple((operation, difficulty, 1)
for operation
in range(4)
for difficulty
in (2, 3, 4))
139 def operation(slot, x, y):
140 return (x + y, x - y, x * y, (x + y) % 2)[slot]
142 def evaluate(model, task):
143 slot, difficulty, variant = task
144 rng = np.random.default_rng(np.random.SeedSequence([slot, difficulty, variant]))
145 x, y = rng.integers(-difficulty, difficulty + 1, (2, 12))
147 expected = operation(slot, x, y)
148 actual = operation(slot, np.clip(x, -limit, limit), np.clip(y, -limit, limit))
149 return float(np.mean(expected == actual))
151 def evolve(parents, rng):
152 first, second = parents[0], parents[-1]
153 child = np.where(rng.random(4) < .5, first, second)
154 child[rng.integers(4)] += rng.choice((-1, 1))
155 return tuple(map(int, np.clip(child, 1, 5)))
157 def propose(request, rng):
158 slot, difficulty, _ = request.parent
159 delta = {
"easier": -1,
"harder": 1,
"novel": 0}[request.direction]
160 if rng.random() < .35:
161 slot = int(rng.integers(4))
162 return slot, int(np.clip(difficulty + delta, 1, 6)), 0
165 slot, difficulty, _ = task
166 codes = tuple(float(i == slot)
for i
in range(4))
167 return (*codes, difficulty / 6.)
169 settings = ((
"coevolution", propose,
"novelty"), (
"fixed-tasks",
None,
"novelty"),
170 (
"quality-only", propose,
"quality"))
171 for mode, scientist, selection
in settings:
172 result = acdc(seeds, cells, vary_model=evolve, propose_task=scientist, evaluate=evaluate,
173 task_descriptor=embedding, budget=176, rounds=80, model_capacity=4, offspring_size=10,
174 active_task_capacity=4, task_period=1, task_proposals=4, task_novelty=.002,
175 valid_model=
lambda model: sum(model) <= 9, passing_score=.8, team_size=3,
176 team_budget=0, selection=selection, seed=seed)
177 audit_scores = np.asarray([[evaluate(model, task)
for task
in audit]
for model
in result.team])
178 yield dict(method=mode, seed=seed, assessments=result.assessments, task_proposals=result.task_proposals,
179 accepted_tasks=result.accepted_tasks, audit_calls=audit_scores.size,
180 audit_coverage=float((audit_scores >= .8).any(axis=0).mean()),
181 active_coverage=float((np.asarray(result.skill_vectors) >= .8).any(axis=0).mean()))
184def team_trials(seed):
185 """Compare novelty-driven and uniform role updates with equal simulator work."""
186 import gymnasium
as gym
189 from qdpy.rl import MADECM, MADECMConfig, PolicyConfig
191 torch.set_num_threads(1)
193 class PairedTracking(gym.Env):
194 observation_space = gym.spaces.Box(-1., 1., (2, 2), dtype=np.float32)
195 action_space = gym.spaces.Box(-1., 1., (2, 1), dtype=np.float32)
198 return np.column_stack((self.position, self.target)).astype(np.float32)
200 def reset(self, *, seed=None, options=None):
201 super().reset(seed=seed)
203 self.position = self.np_random.uniform(-.3, .3, 2)
204 self.target = self.np_random.uniform(-.85, .85, 2)
205 return self.observe(), {}
207 def step(self, action):
208 self.position = np.clip(self.position + .3 * action[:, 0], -1., 1.)
209 gap = self.position - self.target
210 reward = 1. - float(.45 * (gap**2).sum() + .1 * (gap[0] - gap[1])**2)
212 return self.observe(), reward, self.step_count == 6,
False, {}
214 for mode
in (
"curiosity",
"uniform"):
215 grid = Grid(shape=(8, 8), features_domain=((-1., 1.),) * 2, fitness_domain=((-40., 6.),))
216 search = MADECM(PairedTracking, grid, descriptor=
lambda episode: episode.observations[-1, :, 0],
217 config=MADECMConfig(batch_size=16, learning_starts=12, critic_hidden_sizes=(16,),
218 allocation=mode, extra_updates=4),
219 policy=PolicyConfig((12,)), population_size=3, max_episode_steps=6, seed=seed)
220 stats = search.train(960)
221 policy = search.best_policy()
223 with PairedTracking()
as env:
224 for panel_seed
in range(810, 826):
225 observation, _ = env.reset(seed=panel_seed)
228 observation, reward, _, _, _ = env.step(policy.act(observation))
230 returns.append(total)
231 yield dict(method=mode, seed=seed, audit_return=float(np.mean(returns)), audit_steps=len(returns) * 6,
232 env_steps=stats.env_steps, cells=grid.filled_bins, **asdict(stats))
236 """Run one comparison with a fixed list of private search seeds."""
237 choices = dict(centroids=centroid_trials, starts=qdid_trials, architectures=llmatic_trials,
238 tasks=acdc_trials, teams=team_trials)
239 parser = argparse.ArgumentParser(description=__doc__)
240 parser.add_argument(
"task", choices=tuple(choices))
241 parser.add_argument(
"--seeds", type=int, nargs=
"+", default=(11, 22, 33, 44, 55))
242 args = parser.parse_args()
243 with threadpool_limits(limits=1):
244 for seed
in args.seeds:
245 for row
in choices[args.task](seed):
246 print(json.dumps(row, sort_keys=
True), flush=
True)
249if __name__ ==
"__main__":