QDpy
Loading...
Searching...
No Matches
ppo.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""PPO for one synchronous categorical or bounded continuous environment."""
6
7from collections import Counter
8from copy import deepcopy
9from dataclasses import dataclass
10from math import inf, isfinite, log1p, prod
11
12import numpy as np
13import torch
14
15from .policy import _integer, _make_policy, _mlp
16from .rollout import TrainingStats, _Cursor, _StepBudget, _check_spaces, _open_environment, _seed
17
18
19
20@dataclass(frozen=True)
22 """Configure fresh rollouts, GAE, and minibatch reuse of each rollout.
23
24 :param rollout_steps: Maximum number of transitions in a collection.
25 :param epochs: Minibatch passes over one collection.
26 :param batch_size: Maximum number of samples per optimizer update.
27 :param learning_rate: Adam learning rate.
28 :param gamma: Discount factor in [0, 1].
29 :param gae_lambda: GAE continuation factor in [0, 1].
30 :param clip_ratio: Relative bound for PPO's clipped surrogate.
31 :param entropy_coef: Nonnegative weight for the joint action entropy bonus.
32 :param value_coef: Nonnegative weight for the value loss.
33 :param max_grad_norm: Positive gradient norm limit.
34 """
35
36 rollout_steps: int = 128
37 epochs: int = 4
38 batch_size: int = 32
39 learning_rate: float = 3e-4
40 gamma: float = 0.99
41 gae_lambda: float = 0.95
42 clip_ratio: float = 0.2
43 entropy_coef: float = 0.01
44 value_coef: float = 0.5
45 max_grad_norm: float = 0.5
46
47 def __post_init__(self):
48 for name in ("rollout_steps", "epochs", "batch_size"):
49 object.__setattr__(self, name, _integer(getattr(self, name), name))
50 for name in ("learning_rate", "max_grad_norm"):
51 value = getattr(self, name)
52 if not isfinite(value) or value <= 0:
53 raise ValueError(f"{name} must be finite and positive.")
54 for name in ("gamma", "gae_lambda", "clip_ratio"):
55 value = getattr(self, name)
56 if not 0 <= value <= 1:
57 raise ValueError(f"{name} must be in [0, 1].")
58 for name in ("entropy_coef", "value_coef"):
59 value = getattr(self, name)
60 if not isfinite(value) or value < 0:
61 raise ValueError(f"{name} must be finite and nonnegative.")
62
63
64def _advantages(rewards, values, next_values, terminated, truncated, gamma, gae_lambda):
65 """Bootstrap at a truncation and stop the trace at every reset."""
66 deltas = rewards + gamma * next_values * (~terminated) - values
67 advantages = torch.empty_like(deltas)
68 running = 0.0
69 for t in range(len(deltas) - 1, -1, -1):
70 running = deltas[t] + gamma * gae_lambda * running * (~(terminated[t] | truncated[t]))
71 advantages[t] = running
72 return advantages
73
74
75def _surrogate_loss(log_probability, old_log_probability, advantages, clip_ratio):
76 log_ratio = log_probability - old_log_probability
77 lower = log1p(-clip_ratio) if clip_ratio < 1 else -inf
78 lower_clipped = (advantages < 0) & (log_ratio < lower)
79 upper_clipped = (advantages > 0) & (log_ratio > log1p(clip_ratio))
80 ratio = log_ratio.masked_fill(lower_clipped | upper_clipped | (advantages == 0), 0).exp()
81 ratio = ratio.masked_fill(lower_clipped, 1 - clip_ratio).masked_fill(upper_clipped, 1 + clip_ratio)
82 return -(ratio * advantages).mean()
83
84
86 """Instrument a single actor and value network with independent Adam state."""
87
88 def __init__(self, actor, config, seed):
89 self.actor, self.config = actor, config
90 self.value = _mlp(prod(actor._obs_shape), 1, actor.config, seed, actor.device)
91 self.parameters = [*actor._trainable_parameters(), *self.value.parameters()]
92 self.optimizer = torch.optim.Adam(self.parameters, lr=config.learning_rate)
93 self.rng = torch.Generator(device=actor.device).manual_seed(seed)
94
95 def update(self, cursor, budget, limit, *, reward_transform=None, whole_episodes=False, observations_out=None):
96 count = min(limit, budget.remaining, self.config.rollout_steps)
97 if count == 0:
98 return
99 observations, successors, samples, old_logps = [], [], [], []
100 rewards, terminations, truncations = [], [], []
101 physical_actions, infos = [], []
102 for step in range(count):
103 if cursor.ended:
104 if whole_episodes and count - step < cursor.horizon:
105 break
106 cursor.reset()
107 observations.append(cursor.observation)
108 action, sample, logp = self.actor._draw(cursor.observation, False, self.rng)
109 if reward_transform is not None:
110 physical_actions.append(np.array(action, copy=True))
111 reward, terminated, truncated, info = cursor.step(action, budget, "training_steps")
112 if reward_transform is not None:
113 infos.append(deepcopy(info))
114 successors.append(cursor.observation)
115 samples.append(sample)
116 old_logps.append(logp)
117 rewards.append(reward)
118 terminations.append(terminated)
119 truncations.append(truncated)
120
121 count = len(rewards)
122 if not count:
123 return
124 if observations_out is not None:
125 observations_out.extend(observations)
126 if reward_transform is not None:
127 rewards = np.asarray(reward_transform(observations, physical_actions, successors,
128 rewards, np.asarray(terminations) | truncations, infos))
129 if rewards.shape != (count,) or not np.isfinite(rewards).all():
130 raise ValueError("PPO reward transform must return one finite reward per transition.")
131
132 config, device = self.config, self.actor.device
133 obs = self.actor._tensor(np.stack(observations))
134 next_obs = self.actor._tensor(np.stack(successors))
135 actions, old_logps = torch.stack(samples), torch.stack(old_logps)
136 with torch.no_grad():
137 values = self.value(obs).flatten()
138 advantages = _advantages(
139 self.actor._tensor(rewards), values, self.value(next_obs).flatten(),
140 torch.tensor(terminations, dtype=torch.bool, device=device),
141 torch.tensor(truncations, dtype=torch.bool, device=device),
142 config.gamma, config.gae_lambda,
143 )
144 returns = advantages + values
145 if count > 1:
146 advantages = (advantages - advantages.mean()) / (advantages.std(unbiased=False) + 1e-8)
147
148 for _ in range(config.epochs):
149 order = torch.randperm(count, generator=self.rng, device=device)
150 for batch in order.split(config.batch_size):
151 pred = self.value(obs[batch]).flatten()
152 logps, entropy = self.actor._ppo_statistics(obs[batch], actions[batch], self.rng)
153 policy_loss = _surrogate_loss(logps, old_logps[batch], advantages[batch], config.clip_ratio)
154 value_loss = 0.5 * (pred - returns[batch]).square().mean()
155 loss = policy_loss + config.value_coef * value_loss - config.entropy_coef * entropy.mean()
156 if not torch.isfinite(loss):
157 raise ValueError("PPO produced a nonfinite loss.")
158 self.optimizer.zero_grad(set_to_none=True)
159 loss.backward()
160 torch.nn.utils.clip_grad_norm_(self.parameters, config.max_grad_norm, error_if_nonfinite=True)
161 self.optimizer.step()
162 budget.counts["optimizer_steps"] += 1
163
164
165
166class PPO:
167 """Train an actor with fresh rollouts, GAE, and the clipped PPO objective.
168
169 :param env_factory: Callable returning a fresh Gymnasium environment.
170 :param policy: Actor architecture as a :class:`PolicyConfig`.
171 :param config: Sampling and optimizer settings as a :class:`PPOConfig`.
172 :param max_episode_steps: External safety horizon, treated as truncation.
173 :param seed: Seed for initialization, actions, minibatches, and resets.
174 :param device: CPU or CUDA device for the actor and value network.
175 """
176
177 def __init__(self, env_factory, *, policy=None, config=None, max_episode_steps=300, seed=0, device="cpu"):
178 if not callable(env_factory):
179 raise TypeError("env_factory must be callable.")
180 self._factory = env_factory
181 self._horizon = _integer(max_episode_steps, "max_episode_steps")
182 self.config = PPOConfig() if config is None else config
183 if not isinstance(self.config, PPOConfig):
184 raise TypeError("config must be a PPOConfig.")
185 seeds = np.random.SeedSequence(_integer(seed, "seed", 0)).spawn(3)
186 self._reset_rng, actor_rng, learner_rng = map(np.random.default_rng, seeds)
187 with _open_environment(env_factory) as env:
188 self.policy = _make_policy(env, policy, _seed(actor_rng), device, stochastic=True)
189 self._learner = _Learner(self.policy, self.config, _seed(learner_rng))
190 self._counts = Counter()
191
192 @property
193 def stats(self):
194 """Return a snapshot of cumulative running costs."""
195 return TrainingStats(**self._counts)
196
197
198 def train(self, max_env_steps):
199 """Continue the actor and optimizer in a fresh environment instance."""
200 budget = _StepBudget(max_env_steps, self._counts)
201 with _open_environment(self._factory) as env:
202 _check_spaces(env, self.policy)
203 cursor = _Cursor(env, self.policy, self._horizon, self._reset_rng)
204 while budget.remaining:
205 self._learner.update(cursor, budget, budget.remaining)
206 return self.stats
Sampling and minibatch settings for the clipped PPO update.
Definition ppo.py:21
Train PPO in a categorical or bounded continuous action space.
Definition ppo.py:166
train(self, max_env_steps)
Spend an additional environment-step budget and return cumulative statistics.
Definition ppo.py:198
stats(self)
Definition ppo.py:193
Cumulative search costs and evaluated-candidate counts.
Definition rollout.py:51