QDpy
Loading...
Searching...
No Matches
brpg.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Train independent reward and behavior models with transition-level targets."""
6
7from copy import deepcopy
8from dataclasses import dataclass
9from math import isfinite, prod
10
11import numpy as np
12import torch
13from torch import nn
14from torch.nn import functional as F
15
16from .descriptor_search import DCRLMAPElites, DescriptorTrainingStats, _Operator, _Proposal
17from .policy import PolicyConfig, _integer, _mlp
18from .rollout import _evaluate_episode, _seed
19from .td3 import _Replay, _TD3Learner, _checked_step, _critic, _critic_loss, _polyak
20
21__all__ = ["BRPGMAPElites", "BRPGStats"]
22
23
24
25@dataclass(frozen=True)
27 """Cumulative statistics, including normalized successor-feature updates."""
28
29 behavior_updates: int = 0
30
31
33 """Store raw rewards, normalized transition features and achieved context."""
34
35 def __init__(self, capacity, actor, dimension):
36 super().__init__(capacity, prod(actor._obs_shape), prod(actor._actions.shape))
37 self.actor = actor
38 self.features = np.empty((capacity, dimension), dtype=np.float32)
39 self.goals = np.empty_like(self.features)
40
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.")
45 count = episode.steps
46 start = max(0, count - self.capacity)
47 indices = (self.position + np.arange(start, count)) % self.capacity
48 observations = episode.observations.reshape(count + 1, -1)
49 actions = np.asarray(episode.actions, dtype=np.float64).reshape(count, -1)
50 self.observations[indices] = observations[start:-1]
51 self.next_observations[indices] = observations[start + 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
56 self.terminated[indices] = False
57 self.terminated[indices[-1]] = episode.terminated
58 self.position = (self.position + count) % self.capacity
59 self.size = min(self.size + count, self.capacity)
60
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)
71
72
73def _behavior_target(features, terminated, predicted, gamma):
74 """Bootstrap normalized successor features only on nonterminal transitions."""
75 return (1 - gamma) * features + gamma * predicted.masked_fill(terminated[:, None], 0.)
76
77
78def _combine_gradients(reward, behavior):
79 """Remove the part of the reward-loss gradient opposing behavior compliance."""
80 maximum = behavior.abs().amax()
81 scaled = behavior / torch.where(maximum > 0, maximum, 1.)
82 norm = torch.linalg.vector_norm(scaled)
83 direction = scaled / torch.where(norm > 0, norm, 1.)
84 return reward + behavior - torch.minimum(torch.dot(reward, direction), reward.new_zeros(())) * direction
85
86
88 """Apply TD3 reward updates and a separate normalized successor-feature update."""
89
90 def __init__(self, actor, config, seed, counts, replay, search):
91 super().__init__(actor, config, seed, counts, replay=replay)
92 self.search = search
93 dim = len(search._domain.bounds)
94 self.behavior = _mlp(prod(actor._obs_shape) + prod(actor._actions.shape), dim,
95 PolicyConfig(config.critic_hidden_sizes), _seed(self.sample_rng), actor.device, nn.ReLU)
96 self.behavior_target = deepcopy(self.behavior).requires_grad_(False)
97 self.behavior_optimizer = torch.optim.Adam(self.behavior.parameters(), lr=config.critic_learning_rate)
98 self._norms = None
99
100 def _batch(self):
101 return self.replay.sample_conditioned(self.config.batch_size, self.sample_rng, self.actor.device,
102 self.search.goal_relabel_fraction)
103
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)
108 self.critic_optimizer.zero_grad(set_to_none=True)
109 loss.backward()
110 _checked_step(self.critic_optimizer)
111 _polyak(self.critics, self.critic_targets, self.config.tau)
112 self.counts["critic_updates"] += 1
113 self.counts["optimizer_steps"] += 1
114
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.")
127 self.behavior_optimizer.zero_grad(set_to_none=True)
128 loss.backward()
129 _checked_step(self.behavior_optimizer)
130 _polyak(self.behavior, self.behavior_target, self.config.tau)
131 self.counts["behavior_updates"] += 1
132 self.counts["optimizer_steps"] += 1
133
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))
148 if update_scale:
149 norms = torch.stack((reward_grad.norm(), behavior_grad.norm() / square.detach().mean().sqrt().clamp_min(1e-8)))
150 self._norms = norms if self._norms is None else self._norms.lerp(norms, self.search.gradient_ema)
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
160
161 def train_generation(self, critic_steps, behavior_steps):
162 for _ in range(critic_steps):
163 self._update_reward()
164 for _ in range(behavior_steps):
165 self._update_behavior()
166 observations, _, _, _, _, _, goals = self._batch()
167 self.step_policy(self.actor, self.actor_optimizer, observations, observations, goals, update_scale=True)
168 _polyak(self.actor._network, self.actor_target, self.config.tau)
169 self.counts["actor_updates"] += 1
170
171
172
174 """Behavior-Regulated Policy-Gradient MAP-Elites for bounded Box actions.
175
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.
183
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.
197 """
198
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.")
211 self.feature = feature
212 self.behavior_steps = _integer(behavior_steps, "behavior_steps")
213 self.behavior_gamma, self.descriptor_tolerance = behavior_gamma, descriptor_tolerance
214 self.behavior_prior, self.goal_relabel_fraction, self.gradient_ema = behavior_prior, goal_relabel_fraction, gradient_ema
215 super().__init__(env_factory, archive, descriptor=self._mean_descriptor, **kwargs)
216
217 def _mean_descriptor(self, features):
218 # Average before summing to avoid overflow for wide physical domains.
219 mean = np.sum(np.stack(features) / len(features), axis=0)
220 return np.clip(mean, self._domain.low, self._domain.high)
221
222 def _make_learner(self, length_scale):
223 replay = _BehaviorReplay(self.td3.replay_capacity, self._actor, len(self._domain.bounds))
224 return _BRPGLearner(self._conditioned._model, self.td3, _seed(self._training_rng),
225 self._counts, replay, self)
226
227 @property
228 def stats(self):
229 """Return cumulative search, reward-critic, and behavior-estimator costs."""
230 return BRPGStats(**self._counts, replay_size=self._learner.replay.size)
231
232 def _collect_episode(self, cursor, budget, phase, proposal):
233 features, normalized = [], []
234
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)
239
240 episode = _evaluate_episode(cursor, self._actor, budget, phase=phase, transition_info=record)
241 if episode is None:
242 return None, None
243 descriptor = self._descriptor(features)
244 self._learner.replay.add_episode(episode, np.stack(normalized), self._domain.normalize(descriptor))
245 return episode, descriptor
246
247 def _train_learner(self):
248 self._learner.train_generation(self.critic_steps, self.behavior_steps)
249
250 def _improve(self, parent, goal):
251 actor = self.policy_for(parent)
252 optimizer = torch.optim.Adam(actor._trainable_parameters(), lr=self.pg_learning_rate)
253 replay = self._learner.replay
254 goal = actor._tensor(goal)
255 for _ in range(self.pg_steps):
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())
Evolve continuous actors using separate reward and behavior gradients.
Definition brpg.py:173
_mean_descriptor(self, features)
Definition brpg.py:217
Count behavior-estimator steps in addition to reward and actor updates.
Definition brpg.py:26
step_policy(self, actor, optimizer, observations, conditioned, goals, *, update_scale=False)
Definition brpg.py:134
Add specialized conditioned actors to the MAP-Elites offspring batch.
Separate the costs of replay-only actor evaluations and archive candidates.
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
policy_for(self, individual, *, device=None, seed=0)
Rebuild an independent inference actor from an archived genome.
Definition search.py:226
batch(self, rows, device)
Definition td3.py:122
_targets(self, actions, rewards, successors, terminated)
Definition td3.py:219