33 """Store raw rewards, normalized transition features and achieved context."""
35 def __init__(self, capacity, actor, dimension):
36 super().__init__(capacity, prod(actor._obs_shape), prod(actor._actions.shape))
38 self.
features = np.empty((capacity, dimension), dtype=np.float32)
41 def add_episode(self, episode, features, goal):
42 rewards = np.asarray(episode.rewards)
43 if np.any(np.abs(rewards) > np.finfo(np.float32).max):
44 raise ValueError(
"BRPG rewards must be representable in float32.")
46 start = max(0, count - self.
capacity)
48 observations = episode.observations.reshape(count + 1, -1)
49 actions = np.asarray(episode.actions, dtype=np.float64).reshape(count, -1)
52 self.
actions[indices] = self.
actor._encode_actions(actions[start:])
53 self.
rewards[indices] = rewards[start:]
54 self.
features[indices] = features[start:]
55 self.
goals[indices] = goal
57 self.
terminated[indices[-1]] = episode.terminated
61 def sample_conditioned(self, count, rng, device, fraction):
62 rows = rng.integers(self.
size, size=count)
63 observations, actions, rewards, successors, terminated = self.
batch(rows, device)
64 goals = self.
goals[rows]
65 relabel = rng.random(count) < fraction
66 goals[relabel] = rng.uniform(-1, 1, size=(relabel.sum(), goals.shape[1]))
67 targets = torch.as_tensor(goals, device=device)
68 return (torch.cat((observations, targets), dim=-1), actions, rewards,
69 torch.cat((successors, targets), dim=-1), terminated,
70 torch.as_tensor(self.
features[rows], device=device), targets)
88 """Apply TD3 reward updates and a separate normalized successor-feature update."""
90 def __init__(self, actor, config, seed, counts, replay, search):
91 super().__init__(actor, config, seed, counts, replay=replay)
93 dim = len(search._domain.bounds)
94 self.
behavior = _mlp(prod(actor._obs_shape) + prod(actor._actions.shape), dim,
102 self.
search.goal_relabel_fraction)
104 def _update_reward(self):
105 observations, actions, rewards, successors, terminated, _, _ = self.
_batch()
106 target = self.
_targets(actions, rewards, successors, terminated)
107 loss = _critic_loss(self.
critics, observations, actions, target)
112 self.
counts[
"critic_updates"] += 1
113 self.
counts[
"optimizer_steps"] += 1
115 def _update_behavior(self):
116 observations, actions, _, successors, terminated, features, _ = self.
_batch()
117 with torch.no_grad():
118 noise = torch.randn(actions.shape, device=actions.device, generator=self.
noise_rng, dtype=actions.dtype)
119 noise = (noise * self.
config.target_noise).clamp(-self.
config.noise_clip, self.
config.noise_clip)
120 next_actions = (self.
actor_target(successors).tanh() + noise).clamp(-1, 1)
121 successor = self.
behavior_target(torch.cat((successors, next_actions), dim=-1))
122 target = _behavior_target(features, terminated, successor, self.
search.behavior_gamma)
123 predicted = self.
behavior(torch.cat((observations, actions), dim=-1))
124 loss = F.mse_loss(predicted, target)
125 if not torch.isfinite(loss):
126 raise ValueError(
"BRPG produced a nonfinite behavior-estimator loss.")
131 self.
counts[
"behavior_updates"] += 1
132 self.
counts[
"optimizer_steps"] += 1
134 def step_policy(self, actor, optimizer, observations, conditioned, goals, *, update_scale=False):
135 actions = actor._normalized(observations)
136 reward_loss = -_critic(self.
critics[0], conditioned, actions).mean()
137 error = self.
behavior(torch.cat((conditioned, actions), dim=-1)) - goals
138 square = error.square().sum(dim=-1)
139 radius = square.detach().sqrt().clamp_min(torch.finfo(square.dtype).tiny)
140 active = radius > self.
search.descriptor_tolerance
141 weight = active * (2.5 * self.
search.behavior_prior / radius).clamp(max=1.)
142 behavior_loss = (square * weight).mean() / 2
143 if not (torch.isfinite(reward_loss)
and torch.isfinite(behavior_loss)):
144 raise ValueError(
"BRPG produced a nonfinite policy loss.")
145 parameters = tuple(actor._trainable_parameters())
146 reward_grad = nn.utils.parameters_to_vector(torch.autograd.grad(reward_loss, parameters, retain_graph=
True))
147 behavior_grad = nn.utils.parameters_to_vector(torch.autograd.grad(behavior_loss, parameters))
149 norms = torch.stack((reward_grad.norm(), behavior_grad.norm() / square.detach().mean().sqrt().clamp_min(1e-8)))
151 if self.
_norms is not None:
152 first, second = self.
_norms
153 scale = first / (second * self.
search.behavior_prior).clamp_min(1e-8)
154 behavior_grad = behavior_grad * torch.where((first > 0) & (second > 0), scale, 1.)
155 combined = _combine_gradients(reward_grad, behavior_grad)
156 for parameter, grad
in zip(parameters, combined.split([p.numel()
for p
in parameters])):
157 parameter.grad = grad.view_as(parameter)
158 _checked_step(optimizer)
159 self.
counts[
"optimizer_steps"] += 1
161 def train_generation(self, critic_steps, behavior_steps):
162 for _
in range(critic_steps):
164 for _
in range(behavior_steps):
166 observations, _, _, _, _, _, goals = self.
_batch()
169 self.
counts[
"actor_updates"] += 1
174 """Behavior-Regulated Policy-Gradient MAP-Elites for bounded Box actions.
176 Supply a Markov feature for each transition, in the physical coordinates
177 of the reporting grid. A completed episode's descriptor is the mean of
178 those features. The reward critic trains on the original step rewards.
179 A separate estimator learns normalized successor features. The shared
180 actor and elite PG mutations remove parts of the reward gradient that
181 conflict with behavior compliance. Genetic proposals and actor injection
182 use the same schedule as DCRL-MAP-Elites.
184 :param env_factory: Factory for a single Gymnasium environment.
185 :param archive: Best-only single-objective Grid or CVTGrid, as in DCRL.
186 :param feature: Callable ``feature(obs, action, next_obs, info)``. Return a
187 finite vector within ``archive.features_domain`` on every transition.
188 :param behavior_steps: Estimator updates per offspring generation.
189 :param behavior_gamma: Successor-feature discount in [0, 1).
190 :param descriptor_tolerance: Behavior error tolerance in normalized space.
191 :param behavior_prior: Positive behavior error scale in normalized space.
192 :param goal_relabel_fraction: Expected fraction of transitions relabeled
193 with uniform goals during learner updates.
194 :param gradient_ema: Exponential averaging rate for gradient norms.
195 :param kwargs: DCRL policy, variation, evaluation, and TD3 settings.
196 ``critic_steps`` controls reward updates before a single actor update.
199 def __init__(self, env_factory, archive, *, feature, behavior_steps=4, behavior_gamma=.98,
200 descriptor_tolerance=.025, behavior_prior=.05, goal_relabel_fraction=.75,
201 gradient_ema=.01, **kwargs):
202 if not callable(feature):
203 raise TypeError(
"feature must be callable.")
204 if "descriptor" in kwargs
or "length_scale" in kwargs:
205 raise TypeError(
"BRPG derives descriptors from features and uses the original rewards.")
206 if (
not 0 <= behavior_gamma < 1
or not 0 <= goal_relabel_fraction <= 1
207 or not 0 < gradient_ema <= 1
208 or not isfinite(descriptor_tolerance)
or descriptor_tolerance < 0
209 or not 0 < behavior_prior < np.inf):
210 raise ValueError(
"Use valid BRPG discounts, tolerances, scales, and probabilities.")
215 super().__init__(env_factory, archive, descriptor=self.
_mean_descriptor, **kwargs)
217 def _mean_descriptor(self, features):
219 mean = np.sum(np.stack(features) / len(features), axis=0)
222 def _make_learner(self, length_scale):
229 """Return cumulative search, reward-critic, and behavior-estimator costs."""
232 def _collect_episode(self, cursor, budget, phase, proposal):
233 features, normalized = [], []
235 def record(observation, action, reward, successor, terminated, truncated, info):
236 values = np.array(self.
feature(observation, action, successor, info), dtype=float, copy=
True)
237 normalized.append(self.
_domain.normalize(values, goal=
True))
238 features.append(values)
240 episode = _evaluate_episode(cursor, self.
_actor, budget, phase=phase, transition_info=record)
244 self.
_learner.replay.add_episode(episode, np.stack(normalized), self.
_domain.normalize(descriptor))
245 return episode, descriptor
247 def _train_learner(self):
250 def _improve(self, parent, goal):
252 optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=self.
pg_learning_rate)
254 goal = actor._tensor(goal)
256 observations = replay.sample_observations(self.
td3.batch_size, self.
_learner.sample_rng, actor.device)
257 targets = goal.expand(len(observations), -1)
258 conditioned = torch.cat((observations, targets), dim=-1)
259 self.
_learner.step_policy(actor, optimizer, observations, conditioned, targets)
260 self.
_counts[
"policy_gradient_steps"] += 1
261 return _Proposal(_Operator.PG, actor._parameters())