QDpy
Loading...
Searching...
No Matches
wqdil.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Measure-conditioned latent imitation rewards for continuous PPGA."""
7
8from dataclasses import dataclass
9from math import prod
10
11import numpy as np
12import torch
13from torch import nn
14from torch.nn import functional as F
15
16from .descriptor_policy import _DescriptorDomain
17from .policy import PolicyConfig, _integer, _mlp
18from .ppga import PPGA, PPGAStats
19from .rollout import _seed
20from .td3 import _checked_step
21
22__all__ = ["WQDIL", "WQDILStats"]
23
24
25
26@dataclass(frozen=True)
28 """Report paired reward-model updates and in-domain visitation statistics."""
29
30 reward_model_updates: int = 0
31 visit_steps: int = 0
32 visited_cells: int = 0
33
34
36 """Keep a sparse count grid distinct from the episodic policy archive."""
37
38 def __init__(self, domain, shape):
39 self.domain = domain
40 self.shape = shape
41 self.counts = {}
42 self.total = 0
43
44 def bonuses(self, measures, *, record):
45 domain = self.domain
46 result = np.zeros(len(measures))
47 inside = np.flatnonzero(((measures >= domain.low) & (measures <= domain.high)).all(axis=1))
48 fraction = ((measures[inside] * domain.factor - domain.origin) / domain.width).clip(0., 1.)
49 # Use Python integers at the upper boundary, even for wide grids.
50 for i, row in zip(inside, fraction):
51 cell = tuple(min(int(value * size), size - 1) for value, size in zip(row, self.shape))
52 seen = self.counts.get(cell, 0)
53 result[i] = 1. / (1. + seen / self.total) if self.total else 1.
54 if record:
55 self.counts[cell] = seen + 1
56 self.total += 1
57 return result
58
59
61 """Train a deterministic autoencoder and a Wasserstein critic in latent space."""
62
63 def __init__(self, width, latent, config, device, rng, rate, weight, penalty):
64 self.encoder = _mlp(width, latent, config, _seed(rng), device, nn.ReLU)
65 self.decoder = _mlp(latent, width, config, _seed(rng), device, nn.ReLU)
66 self.critic = _mlp(latent, 1, config, _seed(rng), device, nn.ReLU)
67 self.parameters = (*self.encoder.parameters(), *self.decoder.parameters())
68 self.reconstruction_optimizer = torch.optim.Adam(self.parameters, lr=rate)
69 self.critic_optimizer = torch.optim.Adam(self.critic.parameters(), lr=rate)
70 self.rng = torch.Generator(device=device).manual_seed(_seed(rng))
71 self.weight, self.penalty = weight, penalty
72
73 @torch.no_grad()
74 def score(self, rows):
75 """Return the expert-positive latent critic score of each transition."""
76 return self.critic(self.encoder(rows)).flatten()
77
78 def update(self, expert, policy):
79 """Fit the critic on fixed latent codes, then reconstruct and align those codes."""
80 expert_z, policy_z = self.encoder(expert), self.encoder(policy)
81 expert_fixed, policy_fixed = expert_z.detach(), policy_z.detach()
82 critic_loss = self.weight * (self.critic(policy_fixed).mean() - self.critic(expert_fixed).mean())
83 if self.penalty:
84 fraction = torch.rand((len(expert), 1), device=expert.device, generator=self.rng)
85 mixed = torch.lerp(expert_fixed, policy_fixed, fraction).requires_grad_(True)
86 gradient, = torch.autograd.grad(self.critic(mixed).sum(), mixed, create_graph=True)
87 critic_loss += self.penalty * (gradient.norm(dim=1) - 1.).square().mean()
88 if not torch.isfinite(critic_loss):
89 raise ValueError("WQDIL produced a nonfinite critic loss.")
90 self.critic_optimizer.zero_grad(set_to_none=True)
91 critic_loss.backward()
92 _checked_step(self.critic_optimizer)
93
94 reconstruction = F.mse_loss(self.decoder(expert_z), expert) + F.mse_loss(self.decoder(policy_z), policy)
95 loss = reconstruction + self.weight * (self.critic(expert_z).mean() - self.critic(policy_z).mean())
96 if not torch.isfinite(loss):
97 raise ValueError("WQDIL produced a nonfinite autoencoder loss.")
98 for parameter, gradient in zip(self.parameters, torch.autograd.grad(loss, self.parameters)):
99 parameter.grad = gradient
100 _checked_step(self.reconstruction_optimizer)
101
102
103
104class WQDIL(PPGA):
105 """Measure-conditioned WAE-WGAIL with Single-Step Archive Exploration.
106
107 Reconstruct state-action-measure triples and align their expert and
108 policy latent distributions through a regularized Wasserstein critic.
109 PPO uses the critic score plus a visit-frequency bonus. Candidate
110 scoring uses a frozen count snapshot, so evaluating one candidate
111 does not change the bonus of the next. Each generation trains its
112 reward model on the latest search-policy walk and the demonstrations.
113
114 :param env_factory: Continuous-control Gymnasium environment factory.
115 :param archive: Empty scalar Grid or CVTGrid for episodic descriptors.
116 :param demonstrations: Tuple (observations, actions, measures) with one
117 row per expert transition. Use physical units and the training measure.
118 :param visit_shape: Bin count for each timestep measure, defaulting to 10 each.
119 :param visit_domain: Finite bounds for timestep measures, defaulting to the
120 archive feature domain. Visits outside these bounds earn zero bonus.
121 :param bonus_weight: Nonnegative multiplier for the single-step bonus.
122 :param reward_model: Optional PolicyConfig for the encoder, decoder, and critic.
123 :param latent_size: Number of latent coordinates.
124 :param reward_updates: Paired critic and autoencoder updates per generation.
125 :param reward_batch_size: Minibatch size for each of the two transition sources.
126 :param reward_learning_rate: Adam learning rate for both reward-model optimizers.
127 :param wasserstein_weight: Positive weight of the latent matching terms.
128 :param gradient_penalty: Nonnegative coefficient of the latent gradient penalty.
129 :param kwargs: PPGA settings, including the measure callback and PPO configuration.
130 """
131
132 _stats_class = WQDILStats
133
134 def __init__(self, env_factory, archive, *, demonstrations, visit_shape=None, visit_domain=None,
135 bonus_weight=1., reward_model=None, latent_size=8, reward_updates=4, reward_batch_size=64,
136 reward_learning_rate=3e-4, wasserstein_weight=1., gradient_penalty=10., **kwargs):
137 if not (0 <= bonus_weight < np.inf and 0 <= gradient_penalty < np.inf
138 and 0 < reward_learning_rate < np.inf and 0 < wasserstein_weight < np.inf):
139 raise ValueError("Use finite nonnegative bonus and penalty, and positive rate and Wasserstein weight.")
140 if reward_model is not None and not isinstance(reward_model, PolicyConfig):
141 raise TypeError("reward_model must be a PolicyConfig.")
142 latent = _integer(latent_size, "latent_size")
143 self._reward_updates = _integer(reward_updates, "reward_updates")
144 self._reward_batch = _integer(reward_batch_size, "reward_batch_size")
145 self._bonus_weight = bonus_weight
146 super().__init__(env_factory, archive, **kwargs)
147 domain = _DescriptorDomain(archive.features_domain if visit_domain is None else visit_domain)
148 shape = ((10,) * self._measures if visit_shape is None
149 else tuple(_integer(size, "visit_shape element") for size in visit_shape))
150 if len(shape) != self._measures or len(domain.bounds) != self._measures:
151 raise ValueError("Provide one visit bin count and domain interval per timestep measure.")
152 self._visits = _StepVisits(domain, shape)
153 observations, actions, measures = (np.asarray(values, dtype=float) for values in demonstrations)
154 if (observations.ndim != len(self._actor._obs_shape) + 1 or not len(observations)
155 or observations.shape[1:] != self._actor._obs_shape
156 or actions.shape != (len(observations), *self._actor._actions.shape)
157 or measures.shape != (len(observations), self._measures)):
158 raise ValueError("Provide nonempty expert observations, actions, and measures with matching shapes.")
159 physical = actions.reshape(len(actions), prod(self._actor._actions.shape))
160 if (not np.isfinite(actions).all() or np.any(physical < self._actor._low)
161 or np.any(physical > self._actor._high)):
162 raise ValueError("Expert actions must respect the environment's Box bounds.")
163 self._experts = self._actor._tensor(self._rows(observations, actions, measures))
164 self._walk_rows = []
165 self._reward_rng = np.random.default_rng(_seed(self._training_rng))
166 config = PolicyConfig((64, 64)) if reward_model is None else reward_model
167 self._model = _LatentReward(self._experts.shape[1], latent, config, self._actor.device,
168 self._reward_rng, reward_learning_rate, wasserstein_weight, gradient_penalty)
169
170
171 @property
172 def stats(self):
173 """Report visits to the timestep grid separately from policy evaluations."""
174 return WQDILStats(**self._counts, visit_steps=self._visits.total,
175 visited_cells=len(self._visits.counts))
176
177 def _rows(self, observations, actions, measures):
178 states = np.asarray(observations, dtype=float).reshape(len(measures), -1)
179 domain = self._visits.domain
180 with np.errstate(over="ignore", invalid="ignore"):
181 normalized = 2 * ((measures * domain.factor - domain.origin) / domain.width) - 1
182 if (not np.isfinite(states).all() or not np.isfinite(normalized).all()
183 or np.any(np.abs(states) > np.finfo(np.float32).max)
184 or np.any(np.abs(normalized) > np.finfo(np.float32).max)):
185 raise ValueError("Imitation inputs must be finite and representable in float32.")
186 physical = np.asarray(actions).reshape(len(measures), -1)
187 return np.concatenate((states.astype(np.float32), self._actor._encode_actions(physical),
188 normalized.astype(np.float32)), axis=1)
189
190 def _imitation_reward(self, rows):
191 value = self._model.score(self._actor._tensor(rows)).cpu().numpy().astype(float)
192 if not np.isfinite(value).all():
193 raise ValueError("WQDIL produced a nonfinite reward.")
194 return value
195
196 def _trajectory_objective(self, observations, actions, rewards, measures):
197 result = self._imitation_reward(self._rows(observations, actions, measures))
198 return result + self._bonus_weight * self._visits.bonuses(measures, record=False)
199
200 def _reward(self, weights, *, stage=None):
201 def transform(observations, actions, successors, rewards, ended, infos):
202 measures = self._components(observations, actions, successors, infos)
203 bonus = self._visits.bonuses(measures, record=True)
204 result = measures @ weights[1:]
205 if weights[0] or stage == "walk_updates":
206 rows = self._rows(observations, actions, measures)
207 if stage == "walk_updates":
208 self._walk_rows.append(rows)
209 if weights[0]:
210 result += weights[0] * (self._imitation_reward(rows) + self._bonus_weight * bonus)
211 return result
212 return transform
213
214 def _after_generation(self):
215 if not self._walk_rows:
216 return
217 policy = self._actor._tensor(np.concatenate(self._walk_rows))
218 self._walk_rows.clear()
219 for _ in range(self._reward_updates):
220 expert = self._experts[self._reward_rng.integers(len(self._experts), size=self._reward_batch)]
221 agent = policy[self._reward_rng.integers(len(policy), size=self._reward_batch)]
222 self._model.update(expert, agent)
223 self._counts["reward_model_updates"] += 1
224 self._counts["optimizer_steps"] += 2
Architecture of the actor and, for PPO, the separate value network.
Definition policy.py:36
Report PPGA generations and step expenditures alongside native search statistics.
Definition ppga.py:52
Branch from PPO objective and descriptor directions and walk with xNES.
Definition ppga.py:62
_components(self, observations, actions, successors, infos)
Definition ppga.py:141
Count reward-model updates and training visits to timestep descriptor cells.
Definition wqdil.py:27
Learn a continuous policy repertoire using demonstrations and step visit counts.
Definition wqdil.py:104
stats(self)
Return cumulative optimizer, generation, and timestep-visit counts.
Definition wqdil.py:172
_imitation_reward(self, rows)
Definition wqdil.py:190
_rows(self, observations, actions, measures)
Definition wqdil.py:177
update(self, expert, policy)
Definition wqdil.py:78