# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Two-role, grid-free quality-diversity self-play.
# @see https://openreview.net/pdf/665567eb8c04e3260cc3107acede6f4fdccd36da.pdf
"""Discover distinct strategies, then improve each against shared opponent panels."""
from dataclasses import dataclass
from math import dist, fsum, isfinite
import numpy as np
from .modern import _positive_int
__all__ = ["QDSelfPlay", "QDSelfPlayContext", "QDSelfPlayStats"]
## @brief Information supplied to the strategy proposal callback.
[docs]
@dataclass(frozen=True)
class QDSelfPlayContext:
"""Store one observed matchup and similar strategies for the side to mutate.
:ivar role: Index of the side for which a strategy is requested.
:ivar parents: Sampled pair, in fixed role-0, role-1 order.
:ivar payoffs: Observed scores for the sampled pair, in role order.
:ivar neighbors: Up to k other archived strategies near the active parent.
"""
role: int
parents: tuple
payoffs: tuple
neighbors: tuple
## @brief Cumulative callback costs and archive changes.
[docs]
@dataclass(frozen=True)
class QDSelfPlayStats:
"""Count matches, proposals, duplicate strategies, admissions, and local wins."""
matches: int
proposals: int
duplicates: int
novel_admissions: int
local_replacements: int
## @brief Admit novel strategies and improve incumbents through matched competition.
[docs]
class QDSelfPlay:
"""Alternate between two unstructured archives for opposing roles.
A sampled matchup gives the proposer context. If its candidate is
novel enough, the archive keeps it as a stepping stone. Otherwise the
candidate must beat its closest archived neighbor on a common panel
of opponents. Scores are interpreted in the current role's units and
larger is better for both roles. Archives hold the strategy and its
immutable embedding. Match outcomes are local to their comparison.
:param initial: One hashable immutable seed strategy per role.
:param play: Callable taking (role_0_strategy, role_1_strategy) and
returning a finite pair of scores in that order.
:param propose: Callable taking (QDSelfPlayContext, rng) and
returning a strategy or None to skip the proposal.
:param embed: Callable taking (role, strategy) and returning a finite vector.
:param novelty_radius: Candidate distance above which a strategy is considered novel.
:param neighbors: Maximum nearest strategies supplied to the proposer or novelty callback.
:param opponents: Maximum distinct opponents used in each local comparison.
:param is_novel: Optional callable taking (role, strategy, neighbors)
and returning a boolean, to replace the radius decision.
:param seed: Private random seed.
"""
def __init__(self, initial, *, play, propose, embed, novelty_radius=.1,
neighbors=3, opponents=3, is_novel=None, seed=0):
self._play, self._propose, self._embed = play, propose, embed
if not all(map(callable, (play, propose, embed))) or (is_novel is not None and not callable(is_novel)):
raise TypeError("Provide callable match, proposal, and embedding functions.")
if not 0 <= novelty_radius < np.inf:
raise ValueError("novelty_radius must be finite and nonnegative.")
first, second = initial
if first is None or second is None:
raise ValueError("Provide one seed strategy per role.")
self._archives = ({first: self._embedding(0, first)}, {second: self._embedding(1, second)})
self._is_novel, self.novelty_radius = is_novel, novelty_radius
self.neighbors = _positive_int(neighbors, "neighbors")
self.opponents = _positive_int(opponents, "opponents")
self._rng = np.random.default_rng(seed)
self._role = 0
self._matches = self._proposals = self._duplicates = self._novel = self._replaced = 0
@property
def archives(self):
"""Return immutable snapshots of the strategies in role order."""
return tuple(tuple(archive) for archive in self._archives)
@property
def stats(self):
"""Return cumulative accounting, including attempted callback calls."""
return QDSelfPlayStats(self._matches, self._proposals, self._duplicates, self._novel, self._replaced)
def _embedding(self, role, strategy, width=None):
vector = tuple(map(float, self._embed(role, strategy)))
if not vector or (width is not None and len(vector) != width) or not all(map(isfinite, vector)):
raise ValueError("Supply a finite embedding with a fixed width per role.")
return vector
def _closest(self, archive, vector, exclude=None):
distances = [(dist(vector, other), strategy) for strategy, other in archive.items() if strategy != exclude]
return sorted(distances, key=lambda row: row[0])[:self.neighbors]
def _match(self, pair):
self._matches += 1
first, second = map(float, self._play(*pair))
if not isfinite(first) or not isfinite(second):
raise ValueError("Matches must return two finite payoffs.")
return first, second
def _duel(self, role, candidate, incumbent, opponents, count):
chosen = self._rng.choice(len(opponents), size=min(len(opponents), count), replace=False)
proposed, retained = [], []
for index in chosen:
opponent = opponents[index]
proposal_pair, incumbent_pair = (candidate, opponent), (incumbent, opponent)
if role == 1:
proposal_pair, incumbent_pair = proposal_pair[::-1], incumbent_pair[::-1]
proposed.append(self._match(proposal_pair)[role])
retained.append(self._match(incumbent_pair)[role])
return fsum(value / len(chosen) for value in proposed) > fsum(value / len(chosen) for value in retained)
## @brief Continue search using at most budget additional match calls.
[docs]
def run(self, budget):
"""Use the same sampled opponent panel for both members of a duel.
Each proposal costs one context match. A local update needs at
least two more calls. A run can leave up to two calls unused.
The final panel can be smaller than opponents when budget is low.
"""
stop = self._matches + _positive_int(budget, "budget")
while stop - self._matches >= 3:
role = self._role
self._role = 1 - role
archive = self._archives[role]
red, blue = self.archives
parents = red[self._rng.integers(len(red))], blue[self._rng.integers(len(blue))]
scores = self._match(parents)
parent = parents[role]
context = QDSelfPlayContext(role, parents, scores,
tuple(item for _, item in self._closest(archive, archive[parent], parent)))
self._proposals += 1
new = self._propose(context, self._rng)
if new is None:
continue
if new in archive:
self._duplicates += 1
continue
embedding = self._embedding(role, new, len(archive[parent]))
nearest = self._closest(archive, embedding)
distance, incumbent = nearest[0]
if self._is_novel is None:
novel = distance > self.novelty_radius
else:
novel = self._is_novel(role, new, tuple(item for _, item in nearest))
if not isinstance(novel, (bool, np.bool_)):
raise ValueError("is_novel must return a boolean.")
if novel:
archive[new] = embedding
self._novel += 1
elif self._duel(role, new, incumbent, blue if role == 0 else red,
min(self.opponents, (stop - self._matches) // 2)):
del archive[incumbent]
archive[new] = embedding
self._replaced += 1
return self.stats