61 """Train a deterministic autoencoder and a Wasserstein critic in latent space."""
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)
70 self.
rng = torch.Generator(device=device).manual_seed(_seed(rng))
75 """Return the expert-positive latent critic score of each transition."""
79 """Fit the critic on fixed latent codes, then reconstruct and align those codes."""
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())
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.")
91 critic_loss.backward()
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.")
99 parameter.grad = gradient
105 """Measure-conditioned WAE-WGAIL with Single-Step Archive Exploration.
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.
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.
132 _stats_class = WQDILStats
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")
144 self.
_reward_batch = _integer(reward_batch_size,
"reward_batch_size")
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))
151 raise ValueError(
"Provide one visit bin count and domain interval per timestep measure.")
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.")
166 config =
PolicyConfig((64, 64))
if reward_model
is None else reward_model
168 self.
_reward_rng, reward_learning_rate, wasserstein_weight, gradient_penalty)
173 """Report visits to the timestep grid separately from policy evaluations."""
175 visited_cells=len(self.
_visits.counts))
177 def _rows(self, observations, actions, measures):
178 states = np.asarray(observations, dtype=float).reshape(len(measures), -1)
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)
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.")
196 def _trajectory_objective(self, observations, actions, rewards, measures):
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":
214 def _after_generation(self):
222 self.
_model.update(expert, agent)
223 self.
_counts[
"reward_model_updates"] += 1
224 self.
_counts[
"optimizer_steps"] += 2