5"""Measure sequential and batched neural MAP-Elites at a matched step budget."""
8from dataclasses
import asdict
10from pathlib
import Path
12from time
import perf_counter
14import gymnasium
as gym
18from qdpy
import __version__
20from qdpy.rl import NeuralMAPElites, PolicyConfig
23TASKS = (
"CartPole-v1",
"Pendulum-v1")
26def descriptor(episode):
27 """Return two clipped summaries of the first observation coordinates."""
28 return tuple(np.clip(np.mean(episode.observations[:, :2], axis=0) / 2 + 0.5, 0, 1))
31def run_trial(task, width, seed, steps):
32 """Run one fresh search and time the training call."""
33 archive = Grid(shape=(8, 8), fitness_domain=((-np.inf, np.inf),),
34 features_domain=((0.0, 1.0),) * 2)
35 search = NeuralMAPElites(
lambda: gym.make(task), archive, descriptor=descriptor,
36 max_episode_steps=96, policy=PolicyConfig((32, 32)), seed=seed)
37 started = perf_counter()
38 stats = search.train(steps, evaluation_batch_size=width)
39 duration = perf_counter() - started
40 if stats.env_steps != steps:
41 raise RuntimeError(
"The search did not spend the configured interaction budget.")
43 "task": task,
"batch_size": width,
"seed": seed,
44 "elapsed_seconds": duration,
"steps_per_second": stats.env_steps / duration,
45 "stats": asdict(stats),
"occupied_cells": archive.filled_bins,
46 "best_return":
None if archive.best
is None else archive.best.fitness.values[0],
51 """Write the measurements for every task, seed, and rollout width."""
52 parser = argparse.ArgumentParser(description=__doc__)
53 parser.add_argument(
"--tasks", choices=TASKS, nargs=
"+", default=TASKS)
54 parser.add_argument(
"--steps", type=int, default=4096)
55 parser.add_argument(
"--seeds", type=int, nargs=
"+", default=[7, 13, 23])
56 parser.add_argument(
"--batch-sizes", type=int, nargs=
"+", default=[1, 4, 16])
57 parser.add_argument(
"--output", type=Path, required=
True)
58 args = parser.parse_args(argv)
59 if args.steps < 1
or min(args.batch_sizes) < 1
or min(args.seeds) < 0:
60 parser.error(
"Use positive step budgets and batch sizes, and nonnegative seeds.")
61 torch.set_num_threads(1)
63 "schema_version": 1,
"qdpy": __version__,
"python": platform.python_version(),
64 "numpy": np.__version__,
"gymnasium": gym.__version__,
"torch": str(torch.__version__),
65 "budget": args.steps,
"trials": [
66 run_trial(task, width, seed, args.steps)
67 for seed
in args.seeds
for task
in args.tasks
for width
in args.batch_sizes
70 args.output.parent.mkdir(parents=
True, exist_ok=
True)
71 args.output.write_text(json.dumps(report, indent=2, allow_nan=
False) +
"\n", encoding=
"utf-8")
74if __name__ ==
"__main__":