|
| 1 | +from typing import TypeVar |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +import torch as th |
| 5 | +from gymnasium import spaces |
| 6 | + |
| 7 | +from stable_baselines3 import PPO |
| 8 | +from stable_baselines3.common.utils import explained_variance |
| 9 | + |
| 10 | +SelfAVECPPO = TypeVar("SelfAVECPPO", bound="AVECPPO") |
| 11 | + |
| 12 | +class AVECPPO(PPO): |
| 13 | + """ |
| 14 | + PPO version of LEARNING VALUE FUNCTIONS IN DEEP POLICY GRADIENTS USING RESIDUAL VARIANCE. |
| 15 | + Paper: https://arxiv.org/abs/2010.04440 |
| 16 | +
|
| 17 | + Introduction to PPO: https://spinningup.openai.com/en/latest/algorithms/ppo.html |
| 18 | + Full PPO documentation: https://stable-baselines3.readthedocs.io/en/master/modules/ppo.html |
| 19 | + """ |
| 20 | + |
| 21 | + def train(self) -> None: |
| 22 | + """ |
| 23 | + Update policy using the currently gathered rollout buffer. |
| 24 | + """ |
| 25 | + # Switch to train mode (this affects batch norm / dropout) |
| 26 | + self.policy.set_training_mode(True) |
| 27 | + # Update optimizer learning rate |
| 28 | + self._update_learning_rate(self.policy.optimizer) |
| 29 | + # Compute current clip range |
| 30 | + clip_range = self.clip_range(self._current_progress_remaining) # type: ignore[operator] |
| 31 | + # Optional: clip range for the value function |
| 32 | + if self.clip_range_vf is not None: |
| 33 | + clip_range_vf = self.clip_range_vf(self._current_progress_remaining) # type: ignore[operator] |
| 34 | + |
| 35 | + entropy_losses = [] |
| 36 | + pg_losses, value_losses = [], [] |
| 37 | + clip_fractions = [] |
| 38 | + |
| 39 | + continue_training = True |
| 40 | + # train for n_epochs epochs |
| 41 | + for epoch in range(self.n_epochs): |
| 42 | + approx_kl_divs = [] |
| 43 | + # Do a complete pass on the rollout buffer |
| 44 | + for rollout_data in self.rollout_buffer.get(self.batch_size): |
| 45 | + actions = rollout_data.actions |
| 46 | + if isinstance(self.action_space, spaces.Discrete): |
| 47 | + # Convert discrete action from float to long |
| 48 | + actions = rollout_data.actions.long().flatten() |
| 49 | + |
| 50 | + values, log_prob, entropy = self.policy.evaluate_actions(rollout_data.observations, actions) |
| 51 | + values = values.flatten() |
| 52 | + # Normalize advantage |
| 53 | + advantages = rollout_data.advantages |
| 54 | + # Normalization does not make sense if mini batchsize == 1, see GH issue #325 |
| 55 | + if self.normalize_advantage and len(advantages) > 1: |
| 56 | + advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8) |
| 57 | + |
| 58 | + # ratio between old and new policy, should be one at the first iteration |
| 59 | + ratio = th.exp(log_prob - rollout_data.old_log_prob) |
| 60 | + |
| 61 | + # clipped surrogate loss |
| 62 | + policy_loss_1 = advantages * ratio |
| 63 | + policy_loss_2 = advantages * th.clamp(ratio, 1 - clip_range, 1 + clip_range) |
| 64 | + policy_loss = -th.min(policy_loss_1, policy_loss_2).mean() |
| 65 | + |
| 66 | + # Logging |
| 67 | + pg_losses.append(policy_loss.item()) |
| 68 | + clip_fraction = th.mean((th.abs(ratio - 1) > clip_range).float()).item() |
| 69 | + clip_fractions.append(clip_fraction) |
| 70 | + |
| 71 | + if self.clip_range_vf is None: |
| 72 | + # No clipping |
| 73 | + values_pred = values |
| 74 | + else: |
| 75 | + # Clip the difference between old and new value |
| 76 | + # NOTE: this depends on the reward scaling |
| 77 | + values_pred = rollout_data.old_values + th.clamp( |
| 78 | + values - rollout_data.old_values, -clip_range_vf, clip_range_vf |
| 79 | + ) |
| 80 | + # Value loss using the TD(gae_lambda) target |
| 81 | + # value_loss = F.mse_loss(rollout_data.returns, values_pred) |
| 82 | + |
| 83 | + # NOTE here is the variance loss: |
| 84 | + value_loss = th.var(rollout_data.returns - values_pred) |
| 85 | + value_losses.append(value_loss.item()) |
| 86 | + |
| 87 | + # Entropy loss favor exploration |
| 88 | + if entropy is None: |
| 89 | + # Approximate entropy when no analytical form |
| 90 | + entropy_loss = -th.mean(-log_prob) |
| 91 | + else: |
| 92 | + entropy_loss = -th.mean(entropy) |
| 93 | + |
| 94 | + entropy_losses.append(entropy_loss.item()) |
| 95 | + |
| 96 | + loss = policy_loss + self.ent_coef * entropy_loss + self.vf_coef * value_loss |
| 97 | + |
| 98 | + # Calculate approximate form of reverse KL Divergence for early stopping |
| 99 | + # see issue #417: https://github.com/DLR-RM/stable-baselines3/issues/417 |
| 100 | + # and discussion in PR #419: https://github.com/DLR-RM/stable-baselines3/pull/419 |
| 101 | + # and Schulman blog: http://joschu.net/blog/kl-approx.html |
| 102 | + with th.no_grad(): |
| 103 | + log_ratio = log_prob - rollout_data.old_log_prob |
| 104 | + approx_kl_div = th.mean((th.exp(log_ratio) - 1) - log_ratio).cpu().numpy() |
| 105 | + approx_kl_divs.append(approx_kl_div) |
| 106 | + |
| 107 | + if self.target_kl is not None and approx_kl_div > 1.5 * self.target_kl: |
| 108 | + continue_training = False |
| 109 | + if self.verbose >= 1: |
| 110 | + print(f"Early stopping at step {epoch} due to reaching max kl: {approx_kl_div:.2f}") |
| 111 | + break |
| 112 | + |
| 113 | + # Optimization step |
| 114 | + self.policy.optimizer.zero_grad() |
| 115 | + loss.backward() |
| 116 | + # Clip grad norm |
| 117 | + th.nn.utils.clip_grad_norm_(self.policy.parameters(), self.max_grad_norm) |
| 118 | + self.policy.optimizer.step() |
| 119 | + |
| 120 | + self._n_updates += 1 |
| 121 | + if not continue_training: |
| 122 | + break |
| 123 | + |
| 124 | + explained_var = explained_variance(self.rollout_buffer.values.flatten(), self.rollout_buffer.returns.flatten()) |
| 125 | + |
| 126 | + # Logs |
| 127 | + self.logger.record("train/entropy_loss", np.mean(entropy_losses)) |
| 128 | + self.logger.record("train/policy_gradient_loss", np.mean(pg_losses)) |
| 129 | + self.logger.record("train/value_loss", np.mean(value_losses)) |
| 130 | + self.logger.record("train/approx_kl", np.mean(approx_kl_divs)) |
| 131 | + self.logger.record("train/clip_fraction", np.mean(clip_fractions)) |
| 132 | + self.logger.record("train/loss", loss.item()) |
| 133 | + self.logger.record("train/explained_variance", explained_var) |
| 134 | + if hasattr(self.policy, "log_std"): |
| 135 | + self.logger.record("train/std", th.exp(self.policy.log_std).mean().item()) |
| 136 | + |
| 137 | + self.logger.record("train/n_updates", self._n_updates, exclude="tensorboard") |
| 138 | + self.logger.record("train/clip_range", clip_range) |
| 139 | + if self.clip_range_vf is not None: |
| 140 | + self.logger.record("train/clip_range_vf", clip_range_vf) |
| 141 | + |
| 142 | + |
| 143 | + |
0 commit comments