5"""Compare learned codebook niches or cooperating representations using qdpy[rl]."""
8from collections
import deque
10from time
import perf_counter
12import gymnasium
as gym
20from qdpy.rl import CCQD, PolicyConfig, RefQD, TD3Config
23def _placement_grid(domain):
24 return Grid(shape=(4, 4), features_domain=(domain, domain),
25 fitness_domain=((0., 2.),), fitness_weights=(1.,))
28def _insert(archive, point, fitness, descriptor, observation):
29 archive.add(Individual(list(point), fitness=Fitness((fitness,), weights=(1.,)),
30 features=Features(descriptor), scores={
"raw": observation}))
34def sample_trajectory(point):
35 """Return a scalar objective and twelve observation values."""
37 t = np.linspace(0., 1., 6)
38 values = np.column_stack((t * x + .2 * np.sin(2 * np.pi * (t + y)),
39 t * y + .2 * np.cos(2 * np.pi * (t + x))))
40 return float(1.8 - (x - .65)**2 - (y - .35)**2), tuple(values.ravel())
44 """Paired AURORA-style control using a continuous latent grid."""
46 def __init__(self, seed, period, batch_size, epochs):
47 self.
archive = _placement_grid((-1., 1.))
48 self.
rng = np.random.default_rng(seed)
49 with torch.random.fork_rng(devices=[]):
50 torch.random.default_generator.manual_seed(seed)
51 self.
encoder = nn.Sequential(nn.Linear(12, 16), nn.ReLU(), nn.Linear(16, 2), nn.Tanh())
52 self.
decoder = nn.Sequential(nn.Linear(2, 16), nn.ReLU(), nn.Linear(16, 12))
58 def _place(self, rows):
60 data = torch.tensor([row[2]
for row
in rows], dtype=torch.float32)
62 latents = self.
encoder(data).numpy()
63 for (point, fitness, raw), latent
in zip(rows, latents):
64 _insert(self.
archive, point, fitness, tuple(latent), raw)
66 def observe(self, point, fitness, raw):
67 row = (point, fitness, raw)
73 data = torch.tensor([row[2]
for row
in self.
records], dtype=torch.float32)
74 for _
in range(self.
epochs):
75 order = self.
rng.permutation(len(data))
76 for start
in range(0, len(data), self.
batch_size):
77 observed = data[order[start:start + self.
batch_size]]
78 loss = nn.functional.mse_loss(self.
decoder(self.
encoder(observed)), observed)
79 self.
optimizer.zero_grad(set_to_none=
True)
83 retained = ([(tuple(elite), elite.fitness.values[0], elite.scores[
"raw"])
85 self.
archive = _placement_grid((-1., 1.))
91def vq_trial(seed, budget):
92 """Report each archive's placements in a second grid with shared physical coordinates."""
93 rng = np.random.default_rng(seed)
94 rows = [(tuple(point), *sample_trajectory(point))
for point
in rng.random((budget, 2))]
95 period, batch_size, epochs = 32, 16, 4
96 for method
in (
"vq",
"continuous"):
97 start = perf_counter()
99 search =
VQElites(2, 12, cells=16, hidden_size=16, fitness_domain=(0., 2.),
100 training_period=period, training_capacity=96, batch_size=batch_size,
101 epochs=epochs, seed=seed)
106 archive = _placement_grid((0., 1.))
107 for elite
in search.archive:
108 _insert(archive, elite, elite.fitness.values[0], tuple(elite), ())
109 refits = search.stats.refits
if method ==
"vq" else search.refits
110 steps = search.stats.optimizer_steps
if method ==
"vq" else search.steps
111 yield dict(study=
"vq", method=method, seed=seed, observations=len(rows), refits=refits,
112 optimizer_steps=steps, learned_cells=len(search.archive), physical_cells=len(archive),
113 physical_qd_score=archive.qd_score(
False), elapsed_s=perf_counter() - start)
118 """Position two actuators toward a target while exposing mean action as the descriptor."""
120 observation_space = gym.spaces.Box(-1., 1., shape=(4,), dtype=np.float32)
121 action_space = gym.spaces.Box(-1., 1., shape=(2,), dtype=np.float32)
124 def reset(self, *, seed=None, options=None):
125 super().reset(seed=seed)
126 self.
position = np.zeros(2, dtype=np.float32)
127 self.
target = np.asarray([.6, self.np_random.uniform(-.5, .5)], dtype=np.float32)
131 def step(self, action):
135 return (np.concatenate((self.
position, self.
target)), float(reward),
140def action_descriptor(episode):
141 """Fit the two bounded mean actions into a fixed grid."""
142 return tuple(np.mean(episode.actions, axis=0))
146def ccqd_trial(seed, budget):
147 """Audit all available elites under a held-out reset stream and separate cost cap."""
148 for method
in (
"ccqd",
"refqd"):
149 start = perf_counter()
150 grid =
Grid(shape=(5, 5), features_domain=((-1., 1.),) * 2,
151 fitness_domain=((-8., 16.),), fitness_weights=(1.,))
152 common = dict(descriptor=action_descriptor, policy=
PolicyConfig((12,)), batch_size=6,
153 pg_steps=2, td3=
TD3Config(critic_hidden_sizes=(16,), batch_size=16,
154 learning_starts=24, replay_capacity=2048),
155 max_episode_steps=TwoAxisControl.horizon, seed=seed)
157 search =
CCQD(TwoAxisControl, grid, representations=2, critic_steps=2, **common)
159 search =
RefQD(TwoAxisControl, grid, critic_steps=4, depth=3, refresh_every=4, **common)
160 stats = search.train(budget)
161 audit = search.audit(25 * TwoAxisControl.horizon, seed=10_000 + seed)
162 ccqd = method ==
"ccqd"
163 yield dict(study=
"ccqd", method=method, seed=seed, training_steps=stats.env_steps,
164 evaluated_policies=stats.evaluated_policies, critic_updates=stats.critic_updates,
165 actor_updates=stats.actor_updates, pg_steps=stats.policy_gradient_steps,
166 representation_cells=search.representation_counts
if ccqd
else None,
167 replacements=stats.representation_replacements
if ccqd
else None,
168 refresh_steps=0
if ccqd
else stats.refresh_steps, audit_steps=audit.steps,
169 audit_policies=audit.policies
if ccqd
else audit.evaluated_heads,
170 audit_cells=len(audit.archive), audit_qd_score=audit.archive.qd_score(),
171 best=
None if audit.archive.best
is None else audit.archive.best.fitness.values[0],
172 elapsed_s=perf_counter() - start)
176 parser = argparse.ArgumentParser(description=__doc__)
177 parser.add_argument(
"method", choices=(
"vq",
"ccqd"))
178 parser.add_argument(
"--budget", type=int, help=
"Measurements for VQ-Elites or environment steps for CCQD")
179 parser.add_argument(
"--seeds", nargs=
"+", type=int, default=[7, 13, 23])
180 args = parser.parse_args()
181 if args.budget
is not None and args.budget < 1:
182 parser.error(
"--budget must be positive")
183 torch.set_num_threads(1)
184 for seed
in args.seeds:
185 trial = (vq_trial(seed, args.budget
or 128)
if args.method ==
"vq"
186 else ccqd_trial(seed, args.budget
or 576))
188 print(json.dumps(row, allow_nan=
False))
191if __name__ ==
"__main__":
Learn archive niches using a vector-quantized autoencoder.
Combine live representations with archived decision heads and measure the resulting policies.
Architecture of the actor and, for PPO, the separate value network.
Train one shared policy encoder and archive lightweight decision heads.
Settings for the shared TD3 actor, critics, and replay buffer.
A short custom continuous-control task with random target y at reset.