# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Run CPU MASQD and descriptor-conditioned policy diffusion comparisons. """Small reproducible cooperative-control and offline policy-generation studies.""" import argparse import json from pathlib import Path import random from time import perf_counter import gymnasium as gym import numpy as np import torch from qdpy.algorithms import MixME from qdpy.containers import Grid from qdpy.phenotype import Features, Fitness, Individual from qdpy.rl import (ContinuousPolicy, MASQD, PolicyConfig, PolicyDiffusion, PolicyDiffusionConfig, TD3Config, evaluate_skills) ## @brief Two agents control a joint action against a common target and role disturbance. class CooperativeBox(gym.Env): """Expose matching leading agent axes and a single nonnegative team reward.""" observation_space = gym.spaces.Box(-1., 1., shape=(2, 2), dtype=np.float32) action_space = gym.spaces.Box(-1., 1., shape=(2, 1), dtype=np.float32) def __init__(self, weak=False): self.weak = weak def reset(self, *, seed=None, options=None): super().reset(seed=seed) self.tick = 0 self.target = float(self.np_random.uniform(-.8, .8)) self.observation = np.array([[self.target, -1.], [self.target, 1.]], dtype=np.float32) return self.observation.copy(), {} def step(self, action): if not self.action_space.contains(action): raise ValueError("Expected two bounded continuous actions.") self.tick += 1 left, right = action[:, 0] total = (left + (.3 if self.weak else 1.) * right) / 2 reward = 2. - abs(total - self.target) - .15 * abs(left - right) return self.observation.copy(), float(reward), self.tick >= 4, False, {} def _roll_team(act, seed, weak=False): env = CooperativeBox(weak) observation, _ = env.reset(seed=seed) actions, rewards = [], [] for _ in range(4): action = act(observation) observation, reward, _, _, _ = env.step(action) actions.append(action[:, 0].copy()) rewards.append(reward) env.close() return float(sum(rewards)), tuple(np.mean(actions, axis=0)) def _team_grid(): return Grid(shape=(7, 7), features_domain=((-1., 1.),) * 2, fitness_domain=((0., 8.),), fitness_weights=(1.,)) def _mix_me(seed, budget, archive, config): observation = gym.spaces.Box(-1., 1., shape=(2,), dtype=np.float32) action = gym.spaces.Box(-1., 1., shape=(1,), dtype=np.float32) count = len(ContinuousPolicy(observation, action, config=config)._parameters()) def team_for(vector): roles = [ContinuousPolicy(observation, action, config=config) for _ in range(2)] for i, role in enumerate(roles): role._set_parameters(vector[i * count:(i + 1) * count]) return lambda joint: np.stack([actor.act(obs) for actor, obs in zip(roles, joint)]) random.seed(seed) np.random.seed(seed) algorithm = MixME(archive, budget // 4, (count, count), role_bounds=((-1., 1.),) * 2, batch_size=1) rng = np.random.default_rng(seed) for _ in range(budget // 4): candidate, = algorithm.ask_batch() quality, features = _roll_team(team_for(candidate), int(rng.integers(2**32))) algorithm.tell_batch([((quality,), features)]) return team_for ## @brief Compare complete teams at equal joint interaction budgets. def team_trial(seed, budget): """Select the adaptation policy on one reset panel and audit it on another.""" if budget < 4 or budget % 4: raise ValueError("Use a positive multiple of the four-step team horizon.") config = PolicyConfig((8,)) for method in ("masqd", "team_cem", "mix_me"): start = perf_counter() archive = _team_grid() critic_updates = refined = 0 if method == "mix_me": decode = _mix_me(seed, budget, archive, config) else: learner = MASQD(CooperativeBox, archive, descriptor=lambda episode: np.asarray(episode.actions).mean(axis=0).ravel(), policy=config, population_size=8, anchor_interval=3, td3=TD3Config(replay_capacity=4096, batch_size=24, learning_starts=24, critic_hidden_sizes=(16,)), gradient_steps=3 if method == "masqd" else 0, critic_steps=6, initial_sigma=.28, seed=seed) stats = learner.train(budget) critic_updates, refined = stats.critic_updates, stats.pg_offspring def decode(individual): return learner.policy_for(individual).act actors = [decode(individual) for individual in archive] probe = [30_000 + seed * 10 + k for k in range(3)] held = [80_000 + seed * 10 + k for k in range(5)] def panel(act, seeds, weak): return float(np.mean([_roll_team(act, value, weak)[0] for value in seeds])) adapted = max(actors, key=lambda act: panel(act, probe, True)) test_nominal = panel(adapted, held, False) test_damaged = panel(adapted, held, True) yield dict(method=method, seed=seed, steps=budget, coverage=archive.filled_bins / 49, qd_score=archive.qd_score(), best=archive.best.fitness.values[0], critic_updates=critic_updates, refined=refined, audit_steps=(len(actors) * len(probe) + 2 * len(held)) * 4, adapted_nominal=test_nominal, adapted_weak=test_damaged, elapsed_s=perf_counter() - start) ## @brief Single-agent test task with a measured mean action and seeded reward target. class SkillBox(gym.Env): """Supply an independent reset target to the controller at every rollout.""" observation_space = gym.spaces.Box(-1., 1., (1,), np.float32) action_space = gym.spaces.Box(-1., 1., (1,), np.float32) def reset(self, *, seed=None, options=None): super().reset(seed=seed) self.t = 0 self.target = np.array([self.np_random.uniform(-.8, .8)], dtype=np.float32) return self.target.copy(), {} def step(self, action): self.t += 1 return self.target.copy(), 2. - abs(float(action[0] - self.target[0])), self.t == 4, False, {} def _teacher_archive(): environment = SkillBox() config = PolicyConfig(()) archive = Grid(shape=(31,), features_domain=((-1., 1.),), fitness_domain=((0., 8.),), fitness_weights=(1.,)) for goal in np.linspace(-.95, .95, 31): weights = [0., float(np.arctanh(goal))] archive.add(Individual(weights, fitness=Fitness((4.,), weights=(1.,)), features=Features((goal,)))) return environment, config, archive ## @brief Audit generated policies against nearest-elite lookup on fixed held-out targets. def diffusion_trial(seed, vae_epochs, diffusion_epochs, output): """Fit only teacher parameters and descriptors, then evaluate sampled actors.""" env, policy, archive = _teacher_archive() dataset = np.asarray([list(ind) for ind in archive], dtype=np.float32) config = PolicyDiffusionConfig(latent_size=2, hidden_sizes=(24, 24), diffusion_steps=24) model = PolicyDiffusion(env.observation_space, env.action_space, archive.features_domain, policy=policy, config=config, seed=seed) start = perf_counter() stats = model.fit_archive(archive, vae_epochs=vae_epochs, diffusion_epochs=diffusion_epochs, batch_size=16) output.parent.mkdir(parents=True, exist_ok=True) model.save(output) restored = PolicyDiffusion.load(output) training_elapsed = perf_counter() - start goals = [(x,) for x in np.linspace(-.8, .8, 10)] for method in ("diffusion", "nearest"): start = perf_counter() instances = {} for i, goal in enumerate(goals): if method == "diffusion": instances[goal] = restored.sample_policy(goal, seed=40_000 + seed * 100 + i) else: individual = min(archive, key=lambda ind: abs(ind.features.values[0] - goal[0])) actor = ContinuousPolicy(env.observation_space, env.action_space, config=policy) actor._set_parameters(individual) instances[goal] = actor audit = evaluate_skills(SkillBox, lambda obs, goal: instances[goal].act(obs), goals, feature=lambda obs, action, info: action, skill_bounds=archive.features_domain, archive=archive, episodes=4, max_episode_steps=4, tolerance=.15, seed=1230 + seed) yield dict(method=method, seed=seed, policies=stats.policies, vae_updates=stats.vae_updates if method == "diffusion" else 0, diffusion_updates=stats.diffusion_updates if method == "diffusion" else 0, training_s=training_elapsed if method == "diffusion" else 0., audit_steps=audit.env_steps, error=audit.mean_distance, coverage=audit.coverage, achieved_coverage=audit.archive_coverage, qd_score=audit.archive_qd_score, mean_return=audit.mean_return, bytes=output.stat().st_size if method == "diffusion" else dataset.nbytes, elapsed_s=perf_counter() - start) def main(): """Print JSON records for a small CPU run and optionally write a model.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("study", choices=("team", "diffusion")) parser.add_argument("--seeds", type=int, nargs="+", default=[0]) parser.add_argument("--budget", type=int, default=512) parser.add_argument("--vae-epochs", type=int, default=140) parser.add_argument("--diffusion-epochs", type=int, default=300) parser.add_argument("--output", type=Path, default=Path("policy-diffusion.npz")) args = parser.parse_args() torch.set_num_threads(1) for seed in args.seeds: records = (team_trial(seed, args.budget) if args.study == "team" else diffusion_trial(seed, args.vae_epochs, args.diffusion_epochs, args.output)) for row in records: print(json.dumps(row)) if __name__ == "__main__": main()