# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Explore a sparse-reward sequence puzzle with replay and snapshots. import argparse import json from time import perf_counter import numpy as np from qdpy.algorithms import GoExplore class SequencePuzzle: """Advance by finding the right sequence of three possible actions.""" def __init__(self, code): self.code = code self.calls = 0 self.first_solution = None def reset(self, *, seed): self.depth = self.elapsed = 0 return self.depth, {} def step(self, action): self.calls += 1 self.elapsed += 1 self.depth = self.depth + 1 if action == self.code[self.depth] else 0 solved = self.depth == len(self.code) if solved and self.first_solution is None: self.first_solution = self.calls return self.depth, float(solved), solved, self.elapsed >= 36, {} def close(self): pass def restore(env, state): """Restore progress and the simulator's time limit.""" env.depth, env.elapsed = state return env.depth, {} def benchmark(seed, budget): """Charge replay and exploration against the same hard simulator budget.""" task_seed, exploration_seed = np.random.SeedSequence(seed).spawn(2) code = np.random.default_rng(task_seed).integers(3, size=12) exploration_seed = int(exploration_seed.generate_state(1)[0]) def sample(_, info, rng): return int(rng.integers(3)) for mode in ("replay", "snapshots", "random-restarts"): start = perf_counter() env = SequencePuzzle(code) if mode == "random-restarts": env.reset(seed=exploration_seed) rng = np.random.default_rng(exploration_seed) visited, best = {0}, 0. for _ in range(budget): depth, reward, terminated, truncated, _ = env.step(sample(None, None, rng)) visited.add(depth) best = max(best, reward) if terminated or truncated: env.reset(seed=exploration_seed) env.close() steps, replay, cells = budget, 0, len(visited) else: adapter = dict(snapshot=lambda env: (env.depth, env.elapsed), restore=restore) if mode == "snapshots" else {} search = GoExplore(lambda: env, cell=lambda depth, _: depth, sample_action=sample, exploration_steps=6, seed=exploration_seed, **adapter) stats = search.explore(budget) steps, replay, cells, best = stats.env_steps, stats.replay_steps, stats.occupied_cells, search.best.return_ yield dict(method=mode, seed=seed, steps=steps, replay_steps=replay, cells=cells, best=best, first_solution=env.first_solution, seconds=perf_counter() - start) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--budget", type=int, default=1600) parser.add_argument("--seeds", nargs="+", type=int, default=[11, 22, 33]) args = parser.parse_args() for seed in args.seeds: for result in benchmark(seed, args.budget): print(json.dumps(result, sort_keys=True))