30 """GAIL with Extrinsic Behavioral Curiosity from Wan et al. (ICML 2025).
32 The discriminator estimates whether a state-action pair came from an
33 expert. PPO uses softplus of its logit as the imitation reward. If the
34 completed episode's mean measure falls in a currently empty cell, each
35 transition in the episode earns the same curiosity bonus. The resulting
36 PPGA archive contains policies ranked by the imitation reward at the
37 time of evaluation. Use independent environment evaluation for stable
38 external comparisons when the discriminator is still changing.
40 :param env_factory: Factory for a continuous-control Gymnasium environment.
41 :param archive: Empty best-only reporting Grid or CVTGrid.
42 :param demonstrations: Pair of arrays (observations, actions) with one
43 row per expert transition. Use the environment's shapes and units.
44 :param curiosity_weight: Nonnegative per-step empty-cell bonus. Zero gives GAIL.
45 :param discriminator: Optional PolicyConfig for the discriminator MLP.
46 :param discriminator_updates: Number of Adam updates after each PPGA generation.
47 :param discriminator_batch_size: Number of examples of each class per update.
48 :param discriminator_learning_rate: Positive Adam learning rate.
49 :param replay_capacity: Maximum number of recent agent transitions retained.
50 :param kwargs: Continuous PPGA settings, including timestep measure and PPO.
51 Set PPO rollout_steps to at least max_episode_steps.
54 _whole_episodes =
True
55 _stats_class = EBCStats
57 def __init__(self, env_factory, archive, *, demonstrations, curiosity_weight=2.,
58 discriminator=None, discriminator_updates=4, discriminator_batch_size=64,
59 discriminator_learning_rate=3e-4, replay_capacity=50_000, **kwargs):
60 if not (0 <= curiosity_weight < np.inf
and 0 < discriminator_learning_rate < np.inf):
61 raise ValueError(
"Use a finite nonnegative curiosity weight and positive discriminator learning rate.")
64 capacity = _integer(replay_capacity,
"replay_capacity")
65 if discriminator
is not None and not isinstance(discriminator, PolicyConfig):
66 raise TypeError(
"discriminator must be a PolicyConfig.")
68 super().__init__(env_factory, archive, **kwargs)
70 observations, actions = (np.asarray(value, dtype=float)
for value
in demonstrations)
71 action_shape = self.
_actor._actions.shape
72 if (observations.ndim != len(self.
_actor._obs_shape) + 1
or not len(observations)
73 or observations.shape[1:] != self.
_actor._obs_shape
74 or actions.shape != (len(observations), *action_shape)
or not np.isfinite(actions).all()):
75 raise ValueError(
"Provide nonempty expert observations and actions with their environment shapes.")
76 actions = actions.reshape(len(actions), prod(action_shape))
77 if np.any(actions < self.
_actor._low)
or np.any(actions > self.
_actor._high):
78 raise ValueError(
"Expert actions must respect the environment's Box bounds.")
80 self.
_replay = np.empty((capacity, self.
_experts.shape[1]), dtype=np.float32)
83 config =
PolicyConfig((64, 64))
if discriminator
is None else discriminator
85 self.
_actor.device, torch.nn.ReLU)
88 def _pairs(self, observations, actions):
89 states = np.asarray(observations, dtype=float).reshape(len(observations), -1)
90 if not np.isfinite(states).all()
or np.any(np.abs(states) > np.finfo(np.float32).max):
91 raise ValueError(
"Discriminator observations must be finite float32 values.")
92 physical = np.asarray(actions).reshape(len(states), -1)
93 normalized = self.
_actor._encode_actions(physical)
94 return np.concatenate((states.astype(np.float32), normalized), axis=1)
96 def _remember(self, pairs):
98 newest = pairs[-size:]
99 rows = (self.
_position + np.arange(len(newest))) % size
102 self.
_size = min(size, self.
_size + len(newest))
104 def _logits(self, pairs):
108 def _objective(self, observations, actions, rewards):
109 pairs = self.
_pairs(observations, actions)
111 return F.softplus(self.
_logits(pairs)).cpu().numpy().astype(float)
113 def _bonus(self, measures, ended):
116 bonus = np.zeros(len(measures))
118 for end
in np.flatnonzero(ended) + 1:
119 features = tuple(measures[start:end].mean(axis=0))
120 if (self.
archive.in_bounds(features, self.
archive.features_domain)
121 and not self.
archive.solutions[self.
archive.index_grid(features)]):
123 self.
_counts[
"curiosity_episodes"] += 1
127 def _coefficient_weights(self, weights):
128 result = weights.copy()
129 result[..., 0] = np.abs(result[..., 0])
132 def _after_generation(self):
137 agent = self.
_replay[rng.integers(self.
_size, size=count)]
138 loss = F.softplus(-self.
_logits(expert)).mean() + F.softplus(self.
_logits(agent)).mean()
139 if not torch.isfinite(loss):
140 raise ValueError(
"GAIL produced a nonfinite discriminator loss.")
144 self.
_counts[
"optimizer_steps"] += 1
145 self.
_counts[
"discriminator_updates"] += 1