28 """Bind a read-only spherical code to a frozen controller."""
30 def __init__(self, state_shape, action_space, controller, dimension, radius):
32 self.
_actions = _action_layout(action_space)
37 def _observation(self, observation):
38 return _flatten_observation(observation, self.
_obs_shape)
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)
49 def _parameters(self):
50 return self.
_code.copy()
53 def _greedy(self, observation):
55 if not self.
_space.contains(action):
56 raise ValueError(
"The frozen controller returned an action outside its Gymnasium space.")
60 def act(self, observation):
61 """Return the wrapped controller's action for one environment observation."""
76 """Behavioral Foundation Models for QD following Bendib et al. (2026 preprint).
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.
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.
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.")
108 self.
_latent_size = _integer(latent_size,
"latent_size", 2)
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.")
119 capacity = _integer(replay_capacity,
"replay_capacity")
122 self.
_rewards = np.empty(capacity)
if backward_features
is not None else None
124 kwargs.setdefault(
"iso_sigma", 1.)
125 kwargs.setdefault(
"line_sigma", 0.)
126 super().__init__(env_factory, archive, descriptor=descriptor, **kwargs)
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,
137 """Return cumulative real evaluation statistics."""
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.")
150 def _infer_direction(self):
154 reward_scale, feature_scale = np.abs(rewards).max(), np.abs(values).max()
155 if not reward_scale
or not feature_scale:
159 projected = np.linalg.lstsq(values / feature_scale, rewards / reward_scale, rcond=
None)[0]
160 return _project(projected, self.
_radius)
162 def _prepare(self, cursor, budget):
165 emitter =
"bfm-random"
170 if direction
is None:
177 code = _project(mutated, self.
_radius)
178 emitter =
"bfm-genetic"
183 emitter =
"bfm-backward"
185 self.
_counts[
"backward_offspring"] += 1
187 code = np.asarray(parent)
188 self.
_actor._set_parameters(code)
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.")
198 actor._set_parameters(individual)