# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Compare DQS and DOMiNO on a seeded continuous task with several rewarding behaviors. """Explore a continuous line with two rewarding targets and fixed-step episodes.""" import argparse import json from time import perf_counter import gymnasium as gym import numpy as np import torch from qdpy.containers import Grid from qdpy.rl import DOMiNO, DiverseQualitySpecies, PPOConfig, PolicyConfig, TD3Config ## @brief Continuous controls can move toward either of two rewarding positions. class TwoPeaks(gym.Env): """Use one signed action to move along a line and measure the center of each trajectory.""" observation_space = gym.spaces.Box(-1., 1., shape=(2,), dtype=np.float32) action_space = gym.spaces.Box(-1., 1., shape=(1,), dtype=np.float32) horizon = 12 def reset(self, *, seed=None, options=None): super().reset(seed=seed) self.position = float(self.np_random.uniform(-.08, .08)) self.target = float(self.np_random.uniform(.62, .78)) self.tick = 0 return self._observe(), {} def _observe(self): return np.array([self.position, self.target], dtype=np.float32) def step(self, action): self.position = float(np.clip(self.position + .21 * float(action[0]), -1., 1.)) reward = max(0., 1. - 1.45 * abs(abs(self.position) - self.target)) self.tick += 1 return self._observe(), reward, self.tick == self.horizon, False, {} def _grid(): return Grid(shape=(9,), features_domain=((-1., 1.),), fitness_domain=((0., float(TwoPeaks.horizon)),), fitness_weights=(1.,)) ## @brief Fit and audit fixed species and latent skills at matched transition budgets. def trial(seed, budget): """Report coverage of achieved bins and rewarding directions using an independent reset panel.""" horizon = TwoPeaks.horizon config = PolicyConfig((24, 24)) for method in ("dqs", "dqs_no_bonus", "domino"): start = perf_counter() discriminator_updates = offspring = 0 geometry = _grid() if method == "domino": trainer = DOMiNO(TwoPeaks, feature=lambda observation, action, info: (observation[0],), feature_dimension=1, num_skills=4, policy=config, reward_floor=.55, config=PPOConfig(rollout_steps=24, epochs=3, batch_size=12, learning_rate=2e-3), max_episode_steps=horizon, seed=seed) stats = trainer.train(budget) audit = trainer.evaluate(episodes_per_skill=5, seed=80_000 + seed) panel = [(row.occupancy, row.return_mean) for row in audit.skills] audit_steps = audit.steps else: trainer = DiverseQualitySpecies(TwoPeaks, num_species=4, species_size=3, elites=1, policy=config, td3=TD3Config(replay_capacity=4096, critic_hidden_sizes=(32, 32), batch_size=32, learning_starts=96, actor_learning_rate=2e-3), update_frequency=3, gradient_steps=16, max_episode_steps=horizon, diversity_scale=.25 if method == "dqs" else 0., seed=seed) stats = trainer.train(budget) # Score the best measured member of each species to match the four DOMiNO policies. audit = trainer.evaluate(episodes=5, seed=80_000 + seed, descriptor=lambda episode: (float(episode.observations[:-1, 0].mean()),), archive=geometry, best_per_species=True) panel = [(row.descriptor, row.return_) for row in audit.policies] audit_steps = audit.env_steps discriminator_updates, offspring = stats.discriminator_updates, stats.pg_offspring best_by_cell, directions = {}, set() for behavior, score in panel: cell = geometry.index_grid(behavior) best_by_cell[cell] = max(best_by_cell.get(cell, 0.), score) if score / horizon >= .55 and abs(behavior[0]) >= .2: directions.add(int(np.sign(behavior[0]))) yield dict(method=method, seed=seed, env_steps=stats.env_steps, audit_steps=audit_steps, occupied=len(best_by_cell), score=sum(best_by_cell.values()), high_return_directions=len(directions), mean_return=float(np.mean([score for _, score in panel])), updates=stats.optimizer_steps, discriminator_updates=discriminator_updates, refined=offspring, elapsed_s=perf_counter() - start) def main(): """Run seeded CPU comparisons and print JSON records.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--seeds", type=int, nargs="+", default=[7]) parser.add_argument("--steps", type=int, default=1440) args = parser.parse_args() if args.steps < 4 * 3 * TwoPeaks.horizon: parser.error("--steps must be at least one full DQS generation (144 steps)") torch.set_num_threads(1) for seed in args.seeds: for record in trial(seed, args.steps): print(json.dumps(record)) if __name__ == "__main__": main()