QDpy
Loading...
Searching...
No Matches
phasic_invariance.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Compare optional PyTorch diversity objectives with their disabled controls."""
6
7import argparse
8import json
9from dataclasses import asdict
10
11import numpy as np
12
13
14def pdo_trial(seed, budget):
15 """Train on bounded tracking and audit return and descriptor coverage on shared seeds."""
16 import gymnasium as gym
17
18 from qdpy.rl import PDO, PolicyConfig, PPOConfig
19
20 class Tracking(gym.Env):
21 observation_space = gym.spaces.Box(-1., 1., (2,), dtype=np.float32)
22 action_space = gym.spaces.Box(-1., 1., (1,), dtype=np.float32)
23
24 def reset(self, *, seed=None, options=None):
25 super().reset(seed=seed)
26 self.target = self.np_random.uniform(-.7, .7)
27 self.position = self.np_random.uniform(-.4, .4)
28 self.steps = 0
29 return np.asarray([self.position, self.target], dtype=np.float32), {}
30
31 def step(self, action):
32 self.position = float(np.clip(self.position + .35 * float(action[0]), -1., 1.))
33 self.steps += 1
34 observation = np.asarray([self.position, self.target], dtype=np.float32)
35 return observation, 1. - .5 * (self.position - self.target)**2, self.steps == 6, False, {}
36
37 def behavior(episode):
38 return (episode.observations[-1, 0],)
39
40 for updates in (0, 3):
41 search = PDO(Tracking, descriptor=behavior, archive_size=8, population_size=3,
42 evaluation_episodes=1, diversity_updates=updates, diversity_learning_rate=.03,
43 ppo=PPOConfig(rollout_steps=12, batch_size=12, epochs=2, learning_rate=.005),
44 policy=PolicyConfig((12,)), max_episode_steps=6, exploit_period=2, seed=seed)
45 stats = search.train(budget)
46 audit = search.evaluate(episodes_per_policy=8, seed=109)
47 cells = {}
48 for row in audit.measurements:
49 cell = int(np.clip(np.floor((row.descriptor[0] + 1.) * 5), 0, 9))
50 cells[cell] = max(cells.get(cell, 0.), row.return_)
51 yield dict(method="PDO" if updates else "PBT control", seed=seed, **asdict(stats),
52 audit_steps=audit.steps, audit_cells=len(cells), best_return=max(cells.values(), default=None),
53 audit_qd_score=sum(cells.values()) / 6)
54
55
56def vision_trial(seed, updates):
57 """Train small visual encoders and test frozen features on two downstream labels."""
58 import torch
59 import torch.nn.functional as functional
60
61 from qdpy.vision import invariance_descriptors, visual_qd_loss
62
63 def panels(samples, data_seed):
64 generator = torch.Generator().manual_seed(data_seed)
65 attributes = torch.randint(0, 2, (3, samples), generator=generator)
66 orientation, appearance, task = attributes
67 images = .2 * torch.randn(samples, 8, 8, generator=generator)
68 images[orientation == 0, 1:7, 2] += .8
69 images[orientation == 1, 2, 1:7] += .8
70 images[:, 6:8, 6:8] += (.5 * (2 * appearance - 1))[:, None, None]
71 images[:, 3:5, 3:5] += (.6 * (2 * task - 1))[:, None, None]
72 return images, orientation, appearance, task
73
74 train, _, _, targets = panels(128, seed + 100)
75 support, support_orientation, support_appearance, _ = panels(32, 501)
76 test, test_orientation, test_appearance, _ = panels(128, 607)
77 transformed = torch.stack((train.rot90(dims=(-2, -1)), -train))
78
79 def features(model, images):
80 return model(images.flatten(start_dim=-2))
81
82 def representation(models, images):
83 return torch.cat([features(model, images) for model in models], dim=-1)
84
85 def accuracy(train_features, train_labels, test_features, test_labels):
86 train_features = functional.pad(train_features, (0, 1), value=1.)
87 test_features = functional.pad(test_features, (0, 1), value=1.)
88 gram = train_features.T @ train_features + .1 * torch.eye(train_features.shape[1])
89 targets = functional.one_hot(train_labels, 2).float()
90 weights = torch.linalg.solve(gram, train_features.T @ targets)
91 return float(((test_features @ weights).argmax(dim=1) == test_labels).float().mean())
92
93 for weight in (0., 2.):
94 with torch.random.fork_rng():
95 torch.manual_seed(seed)
96 models = torch.nn.ModuleList([torch.nn.Sequential(torch.nn.Linear(64, 12), torch.nn.Tanh())
97 for _ in range(3)])
98 heads = torch.nn.ModuleList([torch.nn.Linear(12, 2) for _ in models])
99 optimizer = torch.optim.Adam([*models.parameters(), *heads.parameters()], lr=.012)
100
101 def objective():
102 clean = [features(model, train) for model in models]
103 losses = torch.stack([functional.cross_entropy(head(values), targets)
104 for head, values in zip(heads, clean)])
105 augmented = torch.stack([features(model, transformed) for model in models])
106 invariances = invariance_descriptors(torch.stack(clean), augmented)
107 return visual_qd_loss(losses, invariances, diversity_weight=weight)
108
109 for _ in range(updates):
110 loss = objective()
111 optimizer.zero_grad(set_to_none=True)
112 loss.total.backward()
113 optimizer.step()
114 with torch.no_grad():
115 metrics = objective()
116 fit, measurements = representation(models, support), representation(models, test)
117 yield dict(method="visual QD" if weight else "quality only", seed=seed, updates=updates,
118 training_loss=float(metrics.quality), invariance_penalty=float(metrics.diversity),
119 orientation_accuracy=accuracy(fit, support_orientation, measurements, test_orientation),
120 appearance_accuracy=accuracy(fit, support_appearance, measurements, test_appearance))
121
122
123if __name__ == "__main__":
124 parser = argparse.ArgumentParser(description=__doc__)
125 parser.add_argument("task", choices=("pdo", "vision"))
126 parser.add_argument("--budget", type=int)
127 parser.add_argument("--seeds", type=int, nargs="+", default=[11, 22, 33])
128 args = parser.parse_args()
129
130 import torch
131 torch.set_num_threads(1)
132 trial, default = (pdo_trial, 666) if args.task == "pdo" else (vision_trial, 60)
133 for seed in args.seeds:
134 for metrics in trial(seed, default if args.budget is None else args.budget):
135 print(json.dumps(metrics, sort_keys=True))