QDpy
Loading...
Searching...
No Matches
qd_self_play.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Discover distinct strategies, then improve each against shared opponent panels."""
7
8from dataclasses import dataclass
9from math import dist, fsum, isfinite
10
11import numpy as np
12
13from .modern import _positive_int
14
15__all__ = ["QDSelfPlay", "QDSelfPlayContext", "QDSelfPlayStats"]
16
17
18
19@dataclass(frozen=True)
21 """Store one observed matchup and similar strategies for the side to mutate.
22
23 :ivar role: Index of the side for which a strategy is requested.
24 :ivar parents: Sampled pair, in fixed role-0, role-1 order.
25 :ivar payoffs: Observed scores for the sampled pair, in role order.
26 :ivar neighbors: Up to k other archived strategies near the active parent.
27 """
28
29 role: int
30 parents: tuple
31 payoffs: tuple
32 neighbors: tuple
33
34
35
36@dataclass(frozen=True)
38 """Count matches, proposals, duplicate strategies, admissions, and local wins."""
39
40 matches: int
41 proposals: int
42 duplicates: int
43 novel_admissions: int
44 local_replacements: int
45
46
47
49 """Alternate between two unstructured archives for opposing roles.
50
51 A sampled matchup gives the proposer context. If its candidate is
52 novel enough, the archive keeps it as a stepping stone. Otherwise the
53 candidate must beat its closest archived neighbor on a common panel
54 of opponents. Scores are interpreted in the current role's units and
55 larger is better for both roles. Archives hold the strategy and its
56 immutable embedding. Match outcomes are local to their comparison.
57
58 :param initial: One hashable immutable seed strategy per role.
59 :param play: Callable taking (role_0_strategy, role_1_strategy) and
60 returning a finite pair of scores in that order.
61 :param propose: Callable taking (QDSelfPlayContext, rng) and
62 returning a strategy or None to skip the proposal.
63 :param embed: Callable taking (role, strategy) and returning a finite vector.
64 :param novelty_radius: Candidate distance above which a strategy is considered novel.
65 :param neighbors: Maximum nearest strategies supplied to the proposer or novelty callback.
66 :param opponents: Maximum distinct opponents used in each local comparison.
67 :param is_novel: Optional callable taking (role, strategy, neighbors)
68 and returning a boolean, to replace the radius decision.
69 :param seed: Private random seed.
70 """
71
72 def __init__(self, initial, *, play, propose, embed, novelty_radius=.1,
73 neighbors=3, opponents=3, is_novel=None, seed=0):
74 self._play, self._propose, self._embed = play, propose, embed
75 if not all(map(callable, (play, propose, embed))) or (is_novel is not None and not callable(is_novel)):
76 raise TypeError("Provide callable match, proposal, and embedding functions.")
77 if not 0 <= novelty_radius < np.inf:
78 raise ValueError("novelty_radius must be finite and nonnegative.")
79 first, second = initial
80 if first is None or second is None:
81 raise ValueError("Provide one seed strategy per role.")
82 self._archives = ({first: self._embedding(0, first)}, {second: self._embedding(1, second)})
83 self._is_novel, self.novelty_radius = is_novel, novelty_radius
84 self.neighbors = _positive_int(neighbors, "neighbors")
85 self.opponents = _positive_int(opponents, "opponents")
86 self._rng = np.random.default_rng(seed)
87 self._role = 0
88 self._matches = self._proposals = self._duplicates = self._novel = self._replaced = 0
89
90 @property
91 def archives(self):
92 """Return immutable snapshots of the strategies in role order."""
93 return tuple(tuple(archive) for archive in self._archives)
94
95 @property
96 def stats(self):
97 """Return cumulative accounting, including attempted callback calls."""
98 return QDSelfPlayStats(self._matches, self._proposals, self._duplicates, self._novel, self._replaced)
99
100 def _embedding(self, role, strategy, width=None):
101 vector = tuple(map(float, self._embed(role, strategy)))
102 if not vector or (width is not None and len(vector) != width) or not all(map(isfinite, vector)):
103 raise ValueError("Supply a finite embedding with a fixed width per role.")
104 return vector
105
106 def _closest(self, archive, vector, exclude=None):
107 distances = [(dist(vector, other), strategy) for strategy, other in archive.items() if strategy != exclude]
108 return sorted(distances, key=lambda row: row[0])[:self.neighbors]
109
110 def _match(self, pair):
111 self._matches += 1
112 first, second = map(float, self._play(*pair))
113 if not isfinite(first) or not isfinite(second):
114 raise ValueError("Matches must return two finite payoffs.")
115 return first, second
116
117 def _duel(self, role, candidate, incumbent, opponents, count):
118 chosen = self._rng.choice(len(opponents), size=min(len(opponents), count), replace=False)
119 proposed, retained = [], []
120 for index in chosen:
121 opponent = opponents[index]
122 proposal_pair, incumbent_pair = (candidate, opponent), (incumbent, opponent)
123 if role == 1:
124 proposal_pair, incumbent_pair = proposal_pair[::-1], incumbent_pair[::-1]
125 proposed.append(self._match(proposal_pair)[role])
126 retained.append(self._match(incumbent_pair)[role])
127 return fsum(value / len(chosen) for value in proposed) > fsum(value / len(chosen) for value in retained)
128
129
130 def run(self, budget):
131 """Use the same sampled opponent panel for both members of a duel.
132
133 Each proposal costs one context match. A local update needs at
134 least two more calls. A run can leave up to two calls unused.
135 The final panel can be smaller than opponents when budget is low.
136 """
137 stop = self._matches + _positive_int(budget, "budget")
138 while stop - self._matches >= 3:
139 role = self._role
140 self._role = 1 - role
141 archive = self._archives[role]
142 red, blue = self.archives
143 parents = red[self._rng.integers(len(red))], blue[self._rng.integers(len(blue))]
144 scores = self._match(parents)
145 parent = parents[role]
146 context = QDSelfPlayContext(role, parents, scores,
147 tuple(item for _, item in self._closest(archive, archive[parent], parent)))
148 self._proposals += 1
149 new = self._propose(context, self._rng)
150 if new is None:
151 continue
152 if new in archive:
153 self._duplicates += 1
154 continue
155
156 embedding = self._embedding(role, new, len(archive[parent]))
157 nearest = self._closest(archive, embedding)
158 distance, incumbent = nearest[0]
159 if self._is_novel is None:
160 novel = distance > self.novelty_radius
161 else:
162 novel = self._is_novel(role, new, tuple(item for _, item in nearest))
163 if not isinstance(novel, (bool, np.bool_)):
164 raise ValueError("is_novel must return a boolean.")
165 if novel:
166 archive[new] = embedding
167 self._novel += 1
168 elif self._duel(role, new, incumbent, blue if role == 0 else red,
169 min(self.opponents, (stop - self._matches) // 2)):
170 del archive[incumbent]
171 archive[new] = embedding
172 self._replaced += 1
173 return self.stats
Information supplied to the strategy proposal callback.
Cumulative callback costs and archive changes.
Admit novel strategies and improve incumbents through matched competition.
run(self, budget)
Continue search using at most budget additional match calls.
_closest(self, archive, vector, exclude=None)
_duel(self, role, candidate, incumbent, opponents, count)
_embedding(self, role, strategy, width=None)