# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Compare diverse initialization, coupled archives, and cooperative curiosity. """Run small CPU comparisons and write one JSON row per seed and method.""" import argparse from dataclasses import asdict import json from time import perf_counter import numpy as np from scipy.spatial import cKDTree from sklearn.cluster import KMeans from threadpoolctl import threadpool_limits from qdpy.algorithms import acdc, llmatic, qd_seeded_refinement from qdpy.containers import Grid, generate_centroids def centroid_trials(seed): """Compare initialization time and Monte Carlo cell-volume dispersion.""" for dimension in (2, 12): count = 64 rng = np.random.default_rng(seed) probe = rng.random((12_000, dimension)) domain = ((0., 1.),) * dimension for method in ("kmeans", "sobol", "halton", "blue-noise", "uniform"): begin = perf_counter() if method == "kmeans": points = rng.random((4096, dimension)) centers = KMeans(count, random_state=seed, n_init=1).fit(points).cluster_centers_ else: centers = generate_centroids(count, domain, method=method, seed=seed) elapsed = perf_counter() - begin cell = cKDTree(centers).query(probe)[1] volumes = np.bincount(cell, minlength=count) / len(probe) yield dict(method=method, seed=seed, dimension=dimension, cells=count, probes=len(probe), setup_seconds=elapsed, volume_cv=float(volumes.std() / volumes.mean()), missed_cells=int(np.count_nonzero(volumes == 0))) def qdid_trials(seed): """Refine six starts on a two-dimensional landscape with six local optima.""" peaks = np.asarray([(x, y) for x in (.17, .5, .83) for y in (.24, .76)]) heights = np.array([.94, .97, .96, 1., .95, .98]) def archive(): return Grid(shape=(3, 2), features_domain=((0., 1.),) * 2, fitness_domain=((0., 1.),), fitness_weights=(1.,)) def evaluate(point): quality = max(0., float((heights - 4. * ((peaks - point)**2).sum(axis=1)).max())) return (quality,), point def refine(start, objective, rng): current = np.asarray(start) best = objective(current) axes = np.asarray(((1, 0), (-1, 0), (0, 1), (0, -1))) for step in (.12, .06, .03): candidates = np.clip(current + step * axes, 0., 1.) scores = [objective(row) for row in candidates] nearest = np.argmin(scores) if scores[nearest] < best: best, current = scores[nearest], candidates[nearest] for mode in ("archive", "random"): result = qd_seeded_refinement(archive(), archive(), evaluate, refine, dimension=2, search_budget=96, starts=6, refinement_budget_per_start=13, initial_samples=60, seed_selection=mode, seed=seed) yield dict(method=mode, seed=seed, search_calls=result.search_evaluations, refinement_calls=result.refinement_evaluations, starts=len(result.starts), refined_cells=result.archive.filled_bins, qd_score=result.archive.qd_score(), improved=sum(row.fitness > row.initial_fitness for row in result.starts)) def llmatic_trials(seed): """Train ridge readouts of small networks proposed by a local typed generator.""" rng = np.random.default_rng(154) inputs = rng.uniform(-1., 1., (192, 3)) labels = np.where(np.sin(4 * inputs[:, 0]) + inputs[:, 1] * inputs[:, 2] > 0., 1., -1.) widths = (4, 8, 12, 16, 20) activations = ("tanh", "relu", "sine") prompts = ("change width", "alter depth", "change activation", "resample network") def evaluate(spec): layers, activation = spec token = activations.index(activation) rng = np.random.default_rng(np.random.SeedSequence([seed, token, *layers])) features = inputs operations = 0 for width in layers: source = features.shape[1] hidden = features @ rng.normal(0., 2. / np.sqrt(source), (source, width)) + rng.uniform(-1., 1., width) features = (np.tanh(hidden) if token == 0 else np.maximum(hidden, 0.) if token == 1 else np.sin(hidden)) operations += source * width features = np.column_stack((features, np.ones(len(features)))) train, valid = features[:128], features[128:] weights = np.linalg.solve(train.T @ train + .04 * np.eye(train.shape[1]), train.T @ labels[:128]) accuracy = float(((valid @ weights > 0.) == (labels[128:] > 0.)).mean()) return accuracy, (max(layers) / len(layers), float(operations + len(weights))) def generate(request, rng): layers, activation = request.parents[0] if request.crossover: other, second_activation = request.parents[1] layers = (*layers[:rng.integers(1, len(layers) + 1)], *other[rng.integers(len(other)):])[:3] activation = second_activation if rng.random() < request.temperature else activation elif request.prompt == "change width": slot = int(rng.integers(len(layers))) alternatives = tuple(width for width in widths if width != layers[slot]) layers = (*layers[:slot], int(rng.choice(alternatives)), *layers[slot + 1:]) elif request.prompt == "alter depth": layers = (*layers, int(rng.choice(widths))) if len(layers) < 3 else layers[:-1] elif request.prompt == "change activation": activation = str(rng.choice([choice for choice in activations if choice != activation])) else: layers = tuple(map(int, rng.choice(widths, size=int(rng.integers(1, 4))))) activation = str(rng.choice(activations)) return layers, activation for mode, exploration in (("curiosity", .25), ("uniform-prompts", 1.)): network = Grid(shape=(8, 8), features_domain=((0., 20.), (0., 900.)), fitness_domain=((0., 1.),)) prompt = Grid(shape=(4, 6), features_domain=((0., 1.),) * 2, fitness_domain=((0., np.inf),)) result = llmatic(network, prompt, initial=((4,), "tanh"), prompts=prompts, generate=generate, evaluate=evaluate, proposal_budget=192, evaluation_budget=56, batch_size=8, crossover_neighbors=2, prompt_exploration=exploration, seed=seed) yield dict(method=mode, seed=seed, proposal_calls=result.proposals, architecture_calls=result.evaluations, duplicates=result.duplicates, filled=network.filled_bins, prompt_cells=prompt.filled_bins, qd_score=network.qd_score(), best_accuracy=network.best.fitness.values[0]) def acdc_trials(seed): """Compare mutable and fixed arithmetic task panels on a separate audit.""" cells = tuple((operation, difficulty, 0) for operation, difficulty in enumerate((3, 3, 2, 3))) seeds = ((4, 1, 1, 1), (1, 4, 1, 1), (2, 2, 2, 2), (1, 1, 1, 4)) audit = tuple((operation, difficulty, 1) for operation in range(4) for difficulty in (2, 3, 4)) def operation(slot, x, y): return (x + y, x - y, x * y, (x + y) % 2)[slot] def evaluate(model, task): slot, difficulty, variant = task rng = np.random.default_rng(np.random.SeedSequence([slot, difficulty, variant])) x, y = rng.integers(-difficulty, difficulty + 1, (2, 12)) limit = model[slot] expected = operation(slot, x, y) actual = operation(slot, np.clip(x, -limit, limit), np.clip(y, -limit, limit)) return float(np.mean(expected == actual)) def evolve(parents, rng): first, second = parents[0], parents[-1] child = np.where(rng.random(4) < .5, first, second) child[rng.integers(4)] += rng.choice((-1, 1)) return tuple(map(int, np.clip(child, 1, 5))) def propose(request, rng): slot, difficulty, _ = request.parent delta = {"easier": -1, "harder": 1, "novel": 0}[request.direction] if rng.random() < .35: slot = int(rng.integers(4)) return slot, int(np.clip(difficulty + delta, 1, 6)), 0 def embedding(task): slot, difficulty, _ = task codes = tuple(float(i == slot) for i in range(4)) return (*codes, difficulty / 6.) settings = (("coevolution", propose, "novelty"), ("fixed-tasks", None, "novelty"), ("quality-only", propose, "quality")) for mode, scientist, selection in settings: result = acdc(seeds, cells, vary_model=evolve, propose_task=scientist, evaluate=evaluate, task_descriptor=embedding, budget=176, rounds=80, model_capacity=4, offspring_size=10, active_task_capacity=4, task_period=1, task_proposals=4, task_novelty=.002, valid_model=lambda model: sum(model) <= 9, passing_score=.8, team_size=3, team_budget=0, selection=selection, seed=seed) audit_scores = np.asarray([[evaluate(model, task) for task in audit] for model in result.team]) yield dict(method=mode, seed=seed, assessments=result.assessments, task_proposals=result.task_proposals, accepted_tasks=result.accepted_tasks, audit_calls=audit_scores.size, audit_coverage=float((audit_scores >= .8).any(axis=0).mean()), active_coverage=float((np.asarray(result.skill_vectors) >= .8).any(axis=0).mean())) def team_trials(seed): """Compare novelty-driven and uniform role updates with equal simulator work.""" import gymnasium as gym import torch from qdpy.rl import MADECM, MADECMConfig, PolicyConfig torch.set_num_threads(1) class PairedTracking(gym.Env): observation_space = gym.spaces.Box(-1., 1., (2, 2), dtype=np.float32) action_space = gym.spaces.Box(-1., 1., (2, 1), dtype=np.float32) def observe(self): return np.column_stack((self.position, self.target)).astype(np.float32) def reset(self, *, seed=None, options=None): super().reset(seed=seed) self.step_count = 0 self.position = self.np_random.uniform(-.3, .3, 2) self.target = self.np_random.uniform(-.85, .85, 2) return self.observe(), {} def step(self, action): self.position = np.clip(self.position + .3 * action[:, 0], -1., 1.) gap = self.position - self.target reward = 1. - float(.45 * (gap**2).sum() + .1 * (gap[0] - gap[1])**2) self.step_count += 1 return self.observe(), reward, self.step_count == 6, False, {} for mode in ("curiosity", "uniform"): grid = Grid(shape=(8, 8), features_domain=((-1., 1.),) * 2, fitness_domain=((-40., 6.),)) search = MADECM(PairedTracking, grid, descriptor=lambda episode: episode.observations[-1, :, 0], config=MADECMConfig(batch_size=16, learning_starts=12, critic_hidden_sizes=(16,), allocation=mode, extra_updates=4), policy=PolicyConfig((12,)), population_size=3, max_episode_steps=6, seed=seed) stats = search.train(960) policy = search.best_policy() returns = [] with PairedTracking() as env: for panel_seed in range(810, 826): observation, _ = env.reset(seed=panel_seed) total = 0. for _ in range(6): observation, reward, _, _, _ = env.step(policy.act(observation)) total += reward returns.append(total) yield dict(method=mode, seed=seed, audit_return=float(np.mean(returns)), audit_steps=len(returns) * 6, env_steps=stats.env_steps, cells=grid.filled_bins, **asdict(stats)) def main(): """Run one comparison with a fixed list of private search seeds.""" choices = dict(centroids=centroid_trials, starts=qdid_trials, architectures=llmatic_trials, tasks=acdc_trials, teams=team_trials) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("task", choices=tuple(choices)) parser.add_argument("--seeds", type=int, nargs="+", default=(11, 22, 33, 44, 55)) args = parser.parse_args() with threadpool_limits(limits=1): for seed in args.seeds: for row in choices[args.task](seed): print(json.dumps(row, sort_keys=True), flush=True) if __name__ == "__main__": main()