QDpy
Loading...
Searching...
No Matches
mome_p2c.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5import argparse
6import json
7
8import gymnasium as gym
9import numpy as np
10import torch
11
12from qdpy.containers import ParetoGrid
13from qdpy.rl import MOMEP2C, PolicyConfig, TD3Config
14
15
16class TradeoffControl(gym.Env):
17 """Use one actuator for competing objectives and the other as a descriptor."""
18
19 observation_space = gym.spaces.Box(-1, 1, (1,), dtype=np.float32)
20 action_space = gym.spaces.Box(-1, 1, (2,), dtype=np.float32)
21
22 def reset(self, *, seed=None, options=None):
23 super().reset(seed=seed)
24 self.steps = 0
25 self.signal = float(self.np_random.choice([-.4, .4]))
26 return self._observe(), {}
27
28 def _observe(self):
29 return np.array([self.signal], dtype=np.float32)
30
31 def step(self, action):
32 positive, negative = self.signal + .55, self.signal - .55
33 rewards = (1 - .25 * (action[0] - positive)**2, 1 - .25 * (action[0] - negative)**2)
34 self.steps += 1
35 self.signal *= -1
36 return self._observe(), float(sum(rewards)), False, self.steps == 6, {"objectives": rewards}
37
38
39def reward_vector(observation, action, successor, info):
40 """Read the two task rewards from step info."""
41 return info["objectives"]
42
43
44def descriptor(episode):
45 """Use the mean of the second action coordinate as the behavior descriptor."""
46 return (np.asarray(episode.actions)[:, 1].mean(),)
47
48
49def assess(policy, seed):
50 """Measure conditioned actions on fresh rollouts at both preference extremes."""
51 env = TradeoffControl()
52 means = []
53 for goal in ((1., 0.), (0., 1.)):
54 obs, _ = env.reset(seed=seed)
55 result = np.zeros(2)
56 for _ in range(6):
57 obs, _, _, _, info = env.step(policy.act(obs, goal))
58 result += info["objectives"]
59 means.append(result.tolist())
60 env.close()
61 return means
62
63
64def benchmark(seed, steps):
65 """Keep the archive, policy layout and environment step budget fixed."""
66 for label, pg, injected in (("mome-p2c", 2, 3), ("genetic-only", 0, 0)):
67 archive = ParetoGrid(shape=(8,), features_domain=((-1, 1),), fitness_domain=((0, 6),) * 2,
68 max_items_per_bin=8, fitness_weights=(1, 1), truncation="crowding")
69 learner = TD3Config(batch_size=48, learning_starts=72, replay_capacity=8192,
70 critic_hidden_sizes=(24, 24), actor_learning_rate=.001,
71 critic_learning_rate=.001, tau=.02)
72 search = MOMEP2C(TradeoffControl, archive, reward_vector=reward_vector, descriptor=descriptor,
73 policy=PolicyConfig((16, 16)), td3=learner, pg_offspring=pg, injections=injected,
74 initial_policies=12, critic_steps=8, pg_steps=2, iso_sigma=.07, line_sigma=.3,
75 max_episode_steps=6, seed=seed)
76 stats = search.train(steps)
77 preferences = assess(search.conditioned_policy(), seed + 1000) if injected else None
78 yield dict(task="p2c", seed=seed, method=label, steps=stats.env_steps, cells=archive.filled_bins,
79 hypervolume=archive.qd_hypervolume((0, 0)), retained=len(archive),
80 optimizer_steps=stats.optimizer_steps, held_out=preferences,
81 assessment_steps=12 if injected else 0)
82
83
84if __name__ == "__main__":
85 parser = argparse.ArgumentParser(description=__doc__)
86 parser.add_argument("--steps", type=int, default=4608)
87 parser.add_argument("--seeds", nargs="+", type=int, default=[11, 22, 33])
88 args = parser.parse_args()
89 torch.set_num_threads(1)
90 for seed in args.seeds:
91 for result in benchmark(seed, args.steps):
92 print(json.dumps(result, sort_keys=True))
Store a bounded nondominated front in each occupied grid cell.
Definition pareto.py:143
Train preference-conditioned continuous policies for per-cell Pareto fronts.
Definition mome_p2c.py:267
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
Settings for the shared TD3 actor, critics, and replay buffer.
Definition td3.py:25