QDpy
Loading...
Searching...
No Matches
portfolio_transfer.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Small reproducible pilots for portfolios and behaviour repertoires."""
6
7import argparse
8from dataclasses import asdict
9from itertools import combinations, product
10import json
11from pathlib import Path
12
13import numpy as np
14from scipy.optimize import LinearConstraint
15
16from qdpy.algorithms import fit_tabular_successor_features, solve_binary_portfolio
17from qdpy.containers import Grid
18
19
20def _distance(first, second):
21 return sum(a != b for a, b in zip(first, second, strict=True))
22
23
24
25def portfolio_trials(seed):
26 """Write exact, quality-ranked, and greedy portfolios for a binary selection task."""
27 rng = np.random.default_rng(seed)
28 objective = rng.permutation(np.arange(1, 8))
29 constraint = LinearConstraint([[1] * 7, [1, 1, 0, 0, 0, 0, 0]], [3., 0.], [3., 1.])
30 exact = solve_binary_portfolio(objective, 3, quality_loss=4., constraints=constraint)
31 candidates = sorted((int(objective @ point), point) for point in product((0, 1), repeat=7)
32 if sum(point) == 3 and sum(point[:2]) <= 1)
33 best = candidates[-1][0]
34 candidates = [(quality, point) for quality, point in reversed(candidates) if quality >= best - 4]
35 points = [point for _, point in candidates]
36 expected = max(min(_distance(a, b) for a, b in combinations(group, 2))
37 for group in combinations(points, 3))
38 assert exact.status == "optimal" and exact.minimum_distance == expected and exact.optimum == best
39 greedy = points[:1]
40 while len(greedy) < 3:
41 greedy.append(max((p for p in points if p not in greedy),
42 key=lambda p: min(_distance(p, q) for q in greedy)))
43 for method, designs in (("joint-milp", exact.designs), ("quality-rank", points[:3]), ("greedy", greedy)):
44 yield dict(task="portfolio", method=method, seed=seed, reference_optimum=best,
45 eligible_designs=len(points), oracle_distance=expected,
46 mean_quality=float(np.mean([objective @ point for point in designs])),
47 distance=min(_distance(a, b) for a, b in combinations(designs, 2)),
48 solver_calls=exact.solver_calls if method == "joint-milp" else 0)
49
50
51
52def transfer_trials(seed):
53 """Preserve two source policies for a sequence of gates with different payoffs."""
54 rng = np.random.default_rng(seed)
55 dynamics = np.zeros((5, 2, 5))
56 dynamics[np.arange(4), :, np.arange(1, 5)] = 1.
57 features = np.zeros((5, 2, 2))
58 regimes = np.array([0, 1, 0, 1, 1])
59 features[np.arange(5), 0, regimes] = rng.uniform(1.3, 2.3, 5)
60 features[np.arange(5), 1, 1 - regimes] = rng.uniform(1.3, 2.3, 5)
61 source = np.stack((regimes, 1 - regimes))
62 gamma = .9
63 repertoire = fit_tabular_successor_features(dynamics, features, source, gamma=gamma)
64 results = {"gpi": [], "best-source": [], "oracle": []}
65 for ratio in np.linspace(.1, .9, 9):
66 reward = np.array([ratio, 1 - ratio])
67 table = features @ reward
68 discount = gamma ** np.arange(len(table))
69 indices = np.arange(len(table))
70 results["gpi"].append(float(discount @ table[indices, repertoire.action_table(reward)]))
71 results["best-source"].append(float(np.max(table[indices, source] @ discount)))
72 results["oracle"].append(float(discount @ table.max(axis=1)))
73 for method, values in results.items():
74 yield dict(task="transfer", method=method, seed=seed, heldout_weights=len(values),
75 mean_return=float(np.mean(values)), regret=float(np.mean(np.subtract(results["oracle"], values))),
76 source_policies=len(source), real_steps=0)
77
78
79
80def branch_trials(seed, budget):
81 """Use one native grid and matched real-step budgets across all methods."""
82 import gymnasium as gym
83 import torch
84
85 from qdpy.rl import PGAMAPElites, PolicyConfig, SVQDRL, TD3Config
86
87 torch.set_num_threads(1)
88
89 class Velocity(gym.Env):
90 observation_space = gym.spaces.Box(-1., 1., (2,), dtype=np.float32)
91 action_space = gym.spaces.Box(-1., 1., (1,), dtype=np.float32)
92
93 def reset(self, *, seed=None, options=None):
94 super().reset(seed=seed)
95 self.velocity, self.goal = self.np_random.uniform(-.2, .2), self.np_random.uniform(-.7, .7)
96 return np.array([self.velocity, self.goal], np.float32), {}
97
98 def step(self, action):
99 self.velocity = .65 * self.velocity + .35 * float(action[0])
100 reward = 1. / (1. + (self.velocity - self.goal) ** 2)
101 return np.array([self.velocity, self.goal], np.float32), reward, False, False, {}
102
103 horizon = 12
104
105 def descriptor(episode):
106 return (float(episode.observations[1:, 0].mean(dtype=np.float64)),)
107
108 def geometry():
109 return Grid(shape=9, features_domain=((-1., 1.),), fitness_domain=((0., horizon),),
110 fitness_weights=(1.,))
111
112 def audit(search):
113 cells, returns, steps = {}, [], 0
114 with Velocity() as env:
115 for elite in search.archive:
116 actor = search.policy_for(elite)
117 positions, scores = [], []
118 for reset in range(3):
119 observation, _ = env.reset(seed=100000 + 4 * seed + reset)
120 run = []
121 for _ in range(horizon):
122 observation, reward, _, _, _ = env.step(actor.act(observation))
123 positions.append(float(observation[0]))
124 run.append(reward)
125 steps += 1
126 scores.append(sum(run))
127 quality = float(np.mean(scores))
128 cell = search.archive.index_grid([np.mean(positions)])
129 cells[cell] = max(cells.get(cell, 0.), quality)
130 returns.append(quality)
131 return dict(audit_cells=len(cells), audit_qd_score=sum(cells.values()), audit_steps=steps,
132 audit_mean_return=float(np.mean(returns)) if returns else None)
133
134 td3 = TD3Config(replay_capacity=96, batch_size=12, learning_starts=12, critic_hidden_sizes=(16,))
135 for method in ("sv-qd-rl", "dense-branches", "shared-critic", "pga-me"):
136 archive = geometry()
137 options = dict(descriptor=descriptor, policy=PolicyConfig((12, 8)), td3=td3,
138 max_episode_steps=horizon, seed=seed)
139 if method == "pga-me":
140 search = PGAMAPElites(Velocity, archive, initial_policies=4, batch_size=4,
141 critic_steps=4, pg_steps=2, **options)
142 else:
143 search = SVQDRL(Velocity, archive, branch_capacity=8, training_steps_per_candidate=24,
144 keep_fractions=(.5, .25), masks=method != "dense-branches",
145 private_critics=method != "shared-critic", **options)
146 result = search.train(budget)
147 sparsity = [entry.sparsity for entry in getattr(search, "branches", ())]
148 yield dict(task="velocity-branches", method=method, seed=seed, env_steps=result.env_steps,
149 archive_cells=len(archive), archive_qd_score=archive.qd_score(),
150 mean_branch_sparsity=float(np.mean(sparsity)) if sparsity else None,
151 **audit(search), **asdict(result))
152
153
154
155def main():
156 parser = argparse.ArgumentParser(description=__doc__)
157 parser.add_argument("task", choices=("portfolio", "transfer", "branches"), nargs="?")
158 parser.add_argument("--seeds", nargs="+", type=int, default=[11, 23, 47])
159 parser.add_argument("--steps", type=int, default=1536)
160 parser.add_argument("--output", type=Path)
161 args = parser.parse_args()
162 if args.steps < 1:
163 parser.error("--steps must be positive.")
164 trials = dict(portfolio=portfolio_trials, transfer=transfer_trials,
165 branches=lambda seed: branch_trials(seed, args.steps))
166 records = []
167 for task in (args.task,) if args.task else ("portfolio", "transfer"):
168 for seed in args.seeds:
169 for row in trials[task](seed):
170 line = json.dumps(row, allow_nan=False, sort_keys=True)
171 print(line)
172 records.append(line)
173 if args.output is not None:
174 args.output.parent.mkdir(parents=True, exist_ok=True)
175 args.output.write_text("\n".join(records) + "\n", encoding="utf-8")
176
177
178if __name__ == "__main__":
179 main()