QDpy
Loading...
Searching...
No Matches
batched_neural_map_elites.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Measure sequential and batched neural MAP-Elites at a matched step budget."""
6
7import argparse
8from dataclasses import asdict
9import json
10from pathlib import Path
11import platform
12from time import perf_counter
13
14import gymnasium as gym
15import numpy as np
16import torch
17
18from qdpy import __version__
19from qdpy.containers import Grid
20from qdpy.rl import NeuralMAPElites, PolicyConfig
21
22
23TASKS = ("CartPole-v1", "Pendulum-v1")
24
25
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))
29
30
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.")
42 return {
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],
47 }
48
49
50def main(argv=None):
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)
62 report = {
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
68 ],
69 }
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")
72
73
74if __name__ == "__main__":
75 main()