# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Run CPU comparisons of RePPO, QDOS, and MIQD. """Compare policy populations, trajectory skill composition, and team coordination.""" import argparse import json from dataclasses import asdict import gymnasium as gym import numpy as np import torch from qdpy.containers import Grid from qdpy.rl import (Episode, MASQD, MIQD, PPOConfig, PolicyConfig, QDOS, QDOSConfig, RePPO, SAC, SACConfig, TD3Config) class TwoRoutes(gym.Env): """Reward decisive travel in either direction with an independent throttle target.""" observation_space = gym.spaces.Box(-1., 1., (2,), np.float32) def __init__(self, discrete=False): self.discrete = discrete self.action_space = (gym.spaces.MultiDiscrete([3, 2]) if discrete else gym.spaces.Box(-1., 1., (2,), np.float32)) def reset(self, *, seed=None, options=None): super().reset(seed=seed) self.tick = 0 self.throttle = float(self.np_random.choice([-1., 1.])) return self._state(), {} def _state(self): return np.array((self.throttle, self.tick / 3 - 1), dtype=np.float32) def step(self, action): if not self.action_space.contains(action): raise ValueError("Action outside the selected space.") direction, throttle = action if self.discrete: direction, throttle = direction - 1, 2 * throttle - 1 reward = 1. - .3 * (1. - abs(direction)) - .15 * (throttle - self.throttle) ** 2 self.tick += 1 return self._state(), float(reward), self.tick == 6, False, {"direction": float(direction)} def route_feature(observation, action, successor, info): """Measure the executed horizontal command in either action space.""" return (info["direction"],) def _episodes(factory, act, seeds, reset_actor=None): """Yield independent, complete deterministic audit episodes.""" env = factory() try: for seed in seeds: observation, initial = env.reset(seed=seed) if reset_actor is not None: reset_actor() states, actions, rewards = [observation.copy()], [], [] measures = [] while True: action = act(observation) observation, reward, terminal, truncated, info = env.step(action) states.append(observation.copy()) actions.append(np.array(action, copy=True)) rewards.append(reward) if "direction" in info: measures.append(info["direction"]) if terminal or truncated: yield Episode(np.stack(states), tuple(actions), tuple(rewards), dict(initial), dict(info), terminal, truncated), measures break finally: env.close() def population_trial(seed, budget): """Train both action spaces with equal steps for independent PPO and RePPO.""" audit_seeds = range(299, 305) for discrete in (False, True): def factory(): return TwoRoutes(discrete) for cap in (1., 0.): learner = RePPO(factory, feature=route_feature, feature_bounds=((-1., 1.),), population_size=4, bandwidth=1.2, repulsion_cap=cap, policy=PolicyConfig((16,)), ppo=PPOConfig(rollout_steps=48, epochs=3, batch_size=24, learning_rate=.003), max_episode_steps=6, seed=seed) stats = learner.train(budget) returns, descriptors, audit_steps = [], [], 0 for policy in learner.policies(): records = list(_episodes(factory, policy.act, audit_seeds)) returns.append(float(np.mean([episode.return_ for episode, _ in records]))) descriptors.append(float(np.mean([signals for _, signals in records]))) audit_steps += sum(episode.steps for episode, _ in records) routes = {int(np.sign(value)) for value, quality in zip(descriptors, returns) if abs(value) > .4 and quality >= 4.} yield dict(method="reppo" if cap else "independent-ppo", seed=seed, action_space=( "multidiscrete" if discrete else "box"), audit_steps=audit_steps, mean_returns=returns, descriptors=descriptors, verified_routes=len(routes), descriptor_span=max(descriptors) - min(descriptors), **asdict(stats)) class TwoGates(gym.Env): """Require a left maneuver in the first window and a right maneuver in the second.""" observation_space = gym.spaces.Box(-1., 1., (3,), np.float32) action_space = gym.spaces.Box(-1., 1., (1,), np.float32) def reset(self, *, seed=None, options=None): super().reset(seed=seed) self.tick = 0 self.progress = float(self.np_random.uniform(-.12, .12)) self.first = False return self._state(), {} def _state(self): return np.array((-1. if self.tick < 2 else 1., self.progress, float(self.first)), dtype=np.float32) def step(self, action): if not self.action_space.contains(action): raise ValueError("Expected a bounded action.") self.progress = float(np.clip(self.progress + .5 * action[0], -1., 1.)) self.tick += 1 if self.tick == 2: self.first = self.progress < -.55 self.progress = 0. success = self.first and self.tick == 4 and self.progress > .55 return self._state(), float(success), self.tick == 4, False, {"success": success} def gate_log(seed, size=96): """Collect a mix of complete successful, avoidant and exploratory trajectories.""" rng = np.random.default_rng(seed) episodes = [] for i in range(size): def behavior(observation): direction = observation[0] if i % 3 == 0 else 0. if i % 3 == 1 else -observation[0] return np.array([np.clip(.86 * direction + rng.normal(0., .22 if direction else .52), -.97, .97)], np.float32) for episode, _ in _episodes(TwoGates, behavior, [i + 1700]): episodes.append(episode) return episodes def hierarchy_trial(seed, budget, pretrain): """Audit learned skill sequences and compare with flat SAC trained online.""" log = gate_log(seed) sac = SACConfig(batch_size=32, replay_capacity=4000, learning_starts=32, critic_hidden_sizes=(24, 24), actor_learning_rate=.002, critic_learning_rate=.002, initial_temperature=.05) network = PolicyConfig((24, 24)) audit_seeds = range(9000, 9024) for method in ("qdos", "unweighted-qdos"): weighted = method == "qdos" cfg = QDOSConfig(skill_horizon=2, latent_size=1, batch_size=32, learning_rate=.003, advantage_weighted=weighted, information_weight=.1 if weighted else 0., updates_per_skill=1) learner = QDOS(TwoGates, episodes=log, config=cfg, policy=network, max_episode_steps=4, sac=sac, seed=seed) learner.pretrain(pretrain) stats = learner.train(budget) policy = learner.policy() episodes = [episode for episode, _ in _episodes(TwoGates, policy.act, audit_seeds, policy.reset)] separation = [np.linalg.norm(policy.select_skill(e.observations[0]) - policy.select_skill(e.observations[2])) for e in episodes] yield dict(method=method, seed=seed, logged_steps=sum(episode.steps for episode in log), logged_successes=sum(episode.return_ for episode in log), audit_steps=sum(e.steps for e in episodes), success_rate=float(np.mean([e.return_ for e in episodes])), first_gate_rate=float(np.mean([e.observations[2, 2] for e in episodes])), mean_skill_separation=float(np.mean(separation)), **asdict(stats)) learner = SAC(TwoGates, policy=network, config=sac, max_episode_steps=4, seed=seed) stats = learner.train(budget) episodes = [episode for episode, _ in _episodes(TwoGates, learner.policy.act, audit_seeds)] yield dict(method="flat-sac", seed=seed, logged_steps=0, logged_successes=0., audit_steps=sum(e.steps for e in episodes), success_rate=float(np.mean([e.return_ for e in episodes])), first_gate_rate=float(np.mean([e.observations[2, 2] for e in episodes])), **asdict(stats)) class RelayTeam(gym.Env): """Give two agents staged joint targets and observe their latest actions.""" observation_space = gym.spaces.Box(-1., 1., (2, 3), np.float32) action_space = gym.spaces.Box(-1., 1., (2, 1), np.float32) def reset(self, *, seed=None, options=None): super().reset(seed=seed) self.tick = 0 self.target = float(self.np_random.uniform(.25, .55)) self.last = np.zeros(2, dtype=np.float32) return self._state(), {} def _state(self): sign = 1. if self.tick < 2 else -1. return np.column_stack((np.full(2, sign * self.target), self.last, [-1., 1.])).astype(np.float32) def step(self, action): if not self.action_space.contains(action): raise ValueError("Expected two bounded actions in fixed role order.") target = self._state()[0, 0] self.last = action[:, 0].copy() reward = 1.6 - abs(float(self.last.mean() - target)) self.tick += 1 return self._state(), reward, self.tick == 4, False, {} def team_descriptor(episode): """Summarize how much work each role takes across the completed episode.""" return np.asarray(episode.actions).mean(axis=0).ravel() def role_feature(observation): """Extract the latest commands from the two local role observations.""" return observation[:, 1] def team_trial(seed, budget): """Audit both archive methods on common unseen reset seeds.""" for method in ("miqd", "miqd-no-information", "masqd"): archive = Grid(shape=(8, 8), features_domain=((-1., 1.),) * 2, fitness_domain=((0., 6.4),), fitness_weights=(1.,)) algorithm = MASQD if method == "masqd" else MIQD extra = {} if method == "masqd" else dict(fragment_feature=role_feature, fragment_radius=1, information_weight=.15 if method == "miqd" else 0.) learner = algorithm(RelayTeam, archive, descriptor=team_descriptor, policy=PolicyConfig((12,)), td3=TD3Config(batch_size=16, learning_starts=16, replay_capacity=4000, critic_hidden_sizes=(24,), actor_learning_rate=.005), population_size=6, critic_steps=4, gradient_steps=2, initial_sigma=.32, max_episode_steps=4, anchor_interval=3, seed=seed, **extra) stats = learner.train(budget) returns, audit_steps = [], 0 for individual in archive: team = learner.policy_for(individual) records = [episode for episode, _ in _episodes(RelayTeam, team.act, range(11000, 11004))] returns.append(float(np.mean([episode.return_ for episode in records]))) audit_steps += sum(episode.steps for episode in records) yield dict(method=method, seed=seed, cells=archive.filled_bins, qd_score=archive.qd_score(), audit_steps=audit_steps, best_audited_return=max(returns, default=None), **asdict(stats)) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("task", choices=("population", "hierarchy", "team")) parser.add_argument("--budget", type=int, default=2304) parser.add_argument("--pretrain", type=int, default=550) parser.add_argument("--seeds", type=int, nargs="+", default=[11, 22, 33]) args = parser.parse_args() torch.set_num_threads(1) for seed in args.seeds: if args.task == "population": records = population_trial(seed, args.budget) elif args.task == "hierarchy": records = hierarchy_trial(seed, args.budget, args.pretrain) else: records = team_trial(seed, args.budget) for record in records: print(json.dumps(record, sort_keys=True))