QDpy
Loading...
Searching...
No Matches
bfm_qd.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Behavioral Foundation Model Quality-Diversity with caller-supplied inference."""
6
7from dataclasses import dataclass
8from math import sqrt
9
10import numpy as np
11import torch
12
13from qdpy.tools import iso_line_dd
14from .policy import _action_layout, _flatten_observation, _integer, _observation_shape
15from .rollout import TrainingStats
16from .search import NeuralMAPElites
17
18
19
20@dataclass(frozen=True)
22 """Report real evaluation cost and attempts guided by a backward model."""
23
24 backward_offspring: int = 0
25
26
28 """Bind a read-only spherical code to a frozen controller."""
29
30 def __init__(self, state_shape, action_space, controller, dimension, radius):
31 self._obs_shape, self._space = state_shape, action_space
32 self._actions = _action_layout(action_space)
33 self._controller = controller
34 self._dimension, self._radius = dimension, radius
35 self._code = None
36
37 def _observation(self, observation):
38 return _flatten_observation(observation, self._obs_shape)
39
40 def _set_parameters(self, code):
41 values = np.array(code, dtype=float, copy=True)
42 if (values.shape != (self._dimension,) or not np.isfinite(values).all()
43 or np.abs(values).max() > self._radius * (1 + 1e-6)
44 or not np.isclose(np.linalg.norm(values / self._radius), 1., rtol=1e-6, atol=0.)):
45 raise ValueError("Supply a finite latent code on the configured sphere.")
46 values.setflags(write=False)
47 self._code = values
48
49 def _parameters(self):
50 return self._code.copy()
51
52 @torch.no_grad()
53 def _greedy(self, observation):
54 action = self._controller(observation.reshape(self._obs_shape), self._code)
55 if not self._space.contains(action):
56 raise ValueError("The frozen controller returned an action outside its Gymnasium space.")
57 return action
58
59
60 def act(self, observation):
61 """Return the wrapped controller's action for one environment observation."""
62 return self._greedy(self._observation(observation))
63
64
65def _project(values, radius):
66 """Project a nonzero direction onto the latent sphere without overflow."""
67 scale = np.abs(values).max()
68 if not scale:
69 return None
70 direction = values / scale
71 return radius * (direction / np.linalg.norm(direction))
72
73
74
76 """Behavioral Foundation Models for QD following Bendib et al. (2026 preprint).
77
78 The same frozen controller evaluates every candidate. Gaussian and
79 optional backward-inference variation propose latent codes that are
80 projected back onto the sphere. The archive stores codes and measured
81 returns and descriptors. Training the controller is a separate stage.
82
83 :param env_factory: Factory for a single Gymnasium environment.
84 :param archive: Empty scalar one-elite Grid or CVTGrid.
85 :param controller: Deterministic function of (observation, latent_code)
86 returning an action in the environment's original space.
87 :param descriptor: Function of a completed Episode returning the descriptor.
88 :param latent_size: Dimension of the supplied controller's latent space.
89 :param radius: Latent sphere radius, default square root of latent_size.
90 :param backward_features: Optional frozen function of successor
91 observation returning one backward feature per latent coordinate.
92 The replay estimator uses the observed reward for that transition.
93 :param backward_probability: Probability of directed variation.
94 Defaults to 0.5 with backward features and zero otherwise.
95 :param backward_step: Interpolation fraction toward the inferred code.
96 :param replay_capacity: Maximum number of observed feature-reward pairs.
97 :param backward_batch_size: Number of replay pairs sampled per estimate.
98 :param kwargs: Native evaluation and seed settings. A nonzero line_sigma
99 opts into Iso+LineDD. The default Gaussian iso_sigma is 1.
100 """
101
102 def __init__(self, env_factory, archive, *, controller, descriptor, latent_size,
103 radius=None, backward_features=None, backward_probability=None,
104 backward_step=.02, replay_capacity=10_000, backward_batch_size=128, **kwargs):
105 if not callable(controller) or (backward_features is not None and not callable(backward_features)):
106 raise TypeError("controller and backward_features must be callable when supplied.")
107 self._controller = controller
108 self._latent_size = _integer(latent_size, "latent_size", 2)
109 self._radius = sqrt(self._latent_size) if radius is None else float(radius)
110 if backward_probability is None:
111 backward_probability = .5 if backward_features is not None else 0.
112 if (not np.finfo(float).tiny <= self._radius <= np.sqrt(np.finfo(float).max / self._latent_size)
113 or not 0 <= backward_probability <= 1 or not 0 < backward_step < 1):
114 raise ValueError("Invalid latent sphere radius, backward probability, or interpolation step.")
115 if backward_probability and backward_features is None:
116 raise ValueError("Backward-inference variation requires backward_features.")
117 self._backward = backward_features
118 self._probability, self._fraction = backward_probability, backward_step
119 capacity = _integer(replay_capacity, "replay_capacity")
120 self._backward_batch_size = _integer(backward_batch_size, "backward_batch_size")
121 self._features = np.empty((capacity, self._latent_size)) if backward_features is not None else None
122 self._rewards = np.empty(capacity) if backward_features is not None else None
123 self._position = self._size = 0
124 kwargs.setdefault("iso_sigma", 1.)
125 kwargs.setdefault("line_sigma", 0.)
126 super().__init__(env_factory, archive, descriptor=descriptor, **kwargs)
127 self._transition = self._remember if backward_features is not None else None
128
129 def _build_actor(self, env, config, seed, device):
130 if config is not None or device != "cpu":
131 raise ValueError("Configure the caller-supplied BFM controller directly.")
132 return _LatentPolicy(_observation_shape(env.observation_space), env.action_space,
133 self._controller, self._latent_size, self._radius)
134
135 @property
136 def stats(self):
137 """Return cumulative real evaluation statistics."""
138 return BFMQDStats(**self._counts)
139
140 @torch.no_grad()
141 def _remember(self, observation, action, reward, successor, terminated):
142 features = np.asarray(self._backward(successor.reshape(self._actor._obs_shape)), dtype=float)
143 if features.shape != (self._latent_size,) or not np.isfinite(features).all():
144 raise ValueError("backward_features must return a finite vector of latent_size values.")
145 self._features[self._position] = features
146 self._rewards[self._position] = reward
147 self._position = (self._position + 1) % len(self._rewards)
148 self._size = min(self._size + 1, len(self._rewards))
149
150 def _infer_direction(self):
151 positions = self._training_rng.integers(self._size, size=self._backward_batch_size)
152 rewards = self._rewards[positions]
153 values = self._features[positions]
154 reward_scale, feature_scale = np.abs(rewards).max(), np.abs(values).max()
155 if not reward_scale or not feature_scale:
156 return None
157 # SVD gives the minimum-norm solution to the reward projection
158 # even when the sampled feature covariance is singular.
159 projected = np.linalg.lstsq(values / feature_scale, rewards / reward_scale, rcond=None)[0]
160 return _project(projected, self._radius)
161
162 def _prepare(self, cursor, budget):
163 if not self._can_select():
164 code = _project(self._actor_rng.standard_normal(self._latent_size), self._radius)
165 emitter = "bfm-random"
166 else:
167 parent = self._parent()
168 direction = (self._infer_direction() if self._size and self._probability
169 and self._selection_rng.random() < self._probability else None)
170 if direction is None:
171 if self._line_sigma:
172 mutated = iso_line_dd(parent, self._parent(), iso_sigma=self._iso_sigma,
173 line_sigma=self._line_sigma, rng=self._selection_rng)
174 else:
175 mutated = np.asarray(parent) + self._selection_rng.normal(scale=self._iso_sigma,
176 size=self._latent_size)
177 code = _project(mutated, self._radius)
178 emitter = "bfm-genetic"
179 else:
180 # Interpolate unit vectors before projection, including near extreme radii.
181 code = _project((1 - self._fraction) * (np.asarray(parent) / self._radius)
182 + self._fraction * (direction / self._radius), self._radius)
183 emitter = "bfm-backward"
184 if code is not None:
185 self._counts["backward_offspring"] += 1
186 if code is None:
187 code = np.asarray(parent)
188 self._actor._set_parameters(code)
189 return emitter
190
191
192 def policy_for(self, individual, *, device=None, seed=0):
193 """Return an independent code binding using the existing inference function."""
194 if device not in (None, "cpu"):
195 raise ValueError("Configure the caller-supplied BFM controller directly.")
196 actor = _LatentPolicy(self._actor._obs_shape, self._actor._space,
197 self._controller, self._latent_size, self._radius)
198 actor._set_parameters(individual)
199 return actor
Report the directed candidates generated by backward inference.
Definition bfm_qd.py:21
Run MAP-Elites over a pretrained controller's latent sphere.
Definition bfm_qd.py:75
policy_for(self, individual, *, device=None, seed=0)
Bind an archived latent code to this search's frozen controller.
Definition bfm_qd.py:192
_remember(self, observation, action, reward, successor, terminated)
Definition bfm_qd.py:141
_observation(self, observation)
Definition bfm_qd.py:37
act(self, observation)
Invoke the fixed controller at this policy's chosen latent code.
Definition bfm_qd.py:60
_greedy(self, observation)
Definition bfm_qd.py:53
Cumulative search costs and evaluated-candidate counts.
Definition rollout.py:51
Illuminate a fixed QDpy archive by evaluating and mutating neural policies.
Definition search.py:24