# SPDX-License-Identifier: LGPL-3.0-or-later ## @file # @brief Compare populations of categorical agents at similar return levels. """Train policies for a toy picking task with two equally valuable styles.""" import argparse import json import gymnasium as gym import numpy as np import torch from qdpy.rl import PPOConfig, PolicyConfig, QSDPBT ## @brief Pick from either of two productive sides or skip the pick. class TwoStyles(gym.Env): """Eight picks share the same value on either side of the aisle.""" observation_space = gym.spaces.Box(0., 1., (1,), dtype=np.float32) action_space = gym.spaces.Discrete(3) def reset(self, *, seed=None, options=None): super().reset(seed=seed) self.steps = 0 return np.zeros(1, dtype=np.float32), {} def step(self, action): self.steps += 1 reward = 1. if action in (0, 1) else .2 return np.array([self.steps / 8.], dtype=np.float32), reward, self.steps == 8, False, {} def describe(episode): """Measure leftward preference and the fraction of consecutive side changes.""" actions = np.asarray(episode.actions) bias = np.mean((actions == 0).astype(float) - (actions == 1)) changes = np.mean((actions[:-1] < 2) & (actions[1:] < 2) & (actions[1:] != actions[:-1])) return bias, changes def trial(seed, budget): """Compare diversity training with the same PPO population trained for reward.""" for label, strength in (("QSD-PBT", 5.), ("Independent PPO", 0.)): search = QSDPBT(TwoStyles, descriptor=describe, descriptor_size=2, population_size=4, max_episode_steps=8, ppo=PPOConfig(rollout_steps=48, epochs=3, batch_size=24, learning_rate=.003), policy=PolicyConfig((12,)), initial_weight=strength, decay_steps=700, seed=seed) stats = search.train(budget) audit = search.evaluate(episodes_per_policy=64, seed=510 + seed) yield dict(method=label, seed=seed, steps=stats.training_steps, audit_steps=audit.steps, mean_return=float(np.mean(audit.returns)), return_span=float(np.ptp(audit.returns)), diversity_by_quality=audit.diversity_by_quality((0., 6., 7., 8.000001)), diversity=audit.diversity_by_quality((0., 8.000001))[0], returns=audit.returns, weights=stats.diversity_weights) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--budget", type=int, default=6144) parser.add_argument("--seeds", nargs="+", type=int, default=[11, 22, 33]) args = parser.parse_args() torch.set_num_threads(1) for seed in args.seeds: for record in trial(seed, args.budget): print(json.dumps(record, sort_keys=True, allow_nan=False))