2021-09-03 05:05:04 +08:00
|
|
|
from typing import Any, Dict, List, Optional, Type
|
|
|
|
|
2020-03-20 19:52:29 +08:00
|
|
|
import numpy as np
|
2021-09-03 05:05:04 +08:00
|
|
|
import torch
|
2020-03-19 17:23:46 +08:00
|
|
|
from torch import nn
|
|
|
|
|
2021-03-28 18:28:36 +08:00
|
|
|
from tianshou.data import Batch, ReplayBuffer, to_torch_as
|
2021-09-03 05:05:04 +08:00
|
|
|
from tianshou.policy import A2CPolicy
|
2021-10-13 09:25:24 -04:00
|
|
|
from tianshou.utils.net.common import ActorCritic
|
2020-03-19 17:23:46 +08:00
|
|
|
|
|
|
|
|
2021-03-23 22:05:48 +08:00
|
|
|
class PPOPolicy(A2CPolicy):
|
2020-09-11 07:55:37 +08:00
|
|
|
r"""Implementation of Proximal Policy Optimization. arXiv:1707.06347.
|
2020-04-06 19:36:59 +08:00
|
|
|
|
|
|
|
:param torch.nn.Module actor: the actor network following the rules in
|
|
|
|
:class:`~tianshou.policy.BasePolicy`. (s -> logits)
|
|
|
|
:param torch.nn.Module critic: the critic network. (s -> V(s))
|
2021-02-27 11:20:43 +08:00
|
|
|
:param torch.optim.Optimizer optim: the optimizer for actor and critic network.
|
2020-09-11 07:55:37 +08:00
|
|
|
:param dist_fn: distribution class for computing the action.
|
2021-02-27 11:20:43 +08:00
|
|
|
:type dist_fn: Type[torch.distributions.Distribution]
|
|
|
|
:param float discount_factor: in [0, 1]. Default to 0.99.
|
2020-04-06 19:36:59 +08:00
|
|
|
:param float eps_clip: :math:`\epsilon` in :math:`L_{CLIP}` in the original
|
2021-02-27 11:20:43 +08:00
|
|
|
paper. Default to 0.2.
|
2020-04-19 14:30:42 +08:00
|
|
|
:param float dual_clip: a parameter c mentioned in arXiv:1912.09729 Equ. 5,
|
2021-02-27 11:20:43 +08:00
|
|
|
where c > 1 is a constant indicating the lower bound.
|
|
|
|
Default to 5.0 (set None if you do not want to use it).
|
2021-08-30 10:35:02 -04:00
|
|
|
:param bool value_clip: a parameter mentioned in arXiv:1811.02553v3 Sec. 4.1.
|
2021-02-27 11:20:43 +08:00
|
|
|
Default to True.
|
2021-03-28 18:28:36 +08:00
|
|
|
:param bool advantage_normalization: whether to do per mini-batch advantage
|
|
|
|
normalization. Default to True.
|
|
|
|
:param bool recompute_advantage: whether to recompute advantage every update
|
|
|
|
repeat according to https://arxiv.org/pdf/2006.05990.pdf Sec. 3.5.
|
|
|
|
Default to False.
|
2021-03-25 10:12:39 +08:00
|
|
|
:param float vf_coef: weight for value loss. Default to 0.5.
|
|
|
|
:param float ent_coef: weight for entropy loss. Default to 0.01.
|
|
|
|
:param float max_grad_norm: clipping gradients in back propagation. Default to
|
|
|
|
None.
|
|
|
|
:param float gae_lambda: in [0, 1], param for Generalized Advantage Estimation.
|
|
|
|
Default to 0.95.
|
|
|
|
:param bool reward_normalization: normalize estimated values to have std close
|
|
|
|
to 1, also normalize the advantage to Normal(0, 1). Default to False.
|
2020-08-27 12:15:18 +08:00
|
|
|
:param int max_batchsize: the maximum size of the batch when computing GAE,
|
2021-03-25 10:12:39 +08:00
|
|
|
depends on the size of available memory and the memory cost of the model;
|
|
|
|
should be as large as possible within the memory constraint. Default to 256.
|
2021-03-21 16:45:50 +08:00
|
|
|
:param bool action_scaling: whether to map actions from range [-1, 1] to range
|
|
|
|
[action_spaces.low, action_spaces.high]. Default to True.
|
|
|
|
:param str action_bound_method: method to bound action to range [-1, 1], can be
|
|
|
|
either "clip" (for simply clipping the action), "tanh" (for applying tanh
|
|
|
|
squashing) for now, or empty string for no bounding. Default to "clip".
|
|
|
|
:param Optional[gym.Space] action_space: env's action space, mandatory if you want
|
|
|
|
to use option "action_scaling" or "action_bound_method". Default to None.
|
2021-03-22 16:57:24 +08:00
|
|
|
:param lr_scheduler: a learning rate scheduler that adjusts the learning rate in
|
|
|
|
optimizer in each policy.update(). Default to None (no lr_scheduler).
|
2021-04-27 21:22:39 +08:00
|
|
|
:param bool deterministic_eval: whether to use deterministic action instead of
|
|
|
|
stochastic action sampled by the policy. Default to False.
|
2020-04-09 21:36:53 +08:00
|
|
|
|
|
|
|
.. seealso::
|
|
|
|
|
|
|
|
Please refer to :class:`~tianshou.policy.BasePolicy` for more detailed
|
|
|
|
explanation.
|
2020-04-06 19:36:59 +08:00
|
|
|
"""
|
2020-03-19 17:23:46 +08:00
|
|
|
|
2020-09-12 15:39:01 +08:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
actor: torch.nn.Module,
|
|
|
|
critic: torch.nn.Module,
|
|
|
|
optim: torch.optim.Optimizer,
|
2021-02-27 11:20:43 +08:00
|
|
|
dist_fn: Type[torch.distributions.Distribution],
|
2020-09-12 15:39:01 +08:00
|
|
|
eps_clip: float = 0.2,
|
|
|
|
dual_clip: Optional[float] = None,
|
2021-03-28 18:28:36 +08:00
|
|
|
value_clip: bool = False,
|
|
|
|
advantage_normalization: bool = True,
|
|
|
|
recompute_advantage: bool = False,
|
2020-09-12 15:39:01 +08:00
|
|
|
**kwargs: Any,
|
|
|
|
) -> None:
|
2021-03-25 10:12:39 +08:00
|
|
|
super().__init__(actor, critic, optim, dist_fn, **kwargs)
|
2020-03-19 17:23:46 +08:00
|
|
|
self._eps_clip = eps_clip
|
2021-02-27 11:20:43 +08:00
|
|
|
assert dual_clip is None or dual_clip > 1.0, \
|
|
|
|
"Dual-clip PPO parameter should greater than 1.0."
|
2020-04-19 14:30:42 +08:00
|
|
|
self._dual_clip = dual_clip
|
|
|
|
self._value_clip = value_clip
|
2021-03-28 18:28:36 +08:00
|
|
|
self._norm_adv = advantage_normalization
|
|
|
|
self._recompute_adv = recompute_advantage
|
2021-10-13 09:25:24 -04:00
|
|
|
self._actor_critic: ActorCritic
|
2020-03-20 19:52:29 +08:00
|
|
|
|
2020-09-12 15:39:01 +08:00
|
|
|
def process_fn(
|
2021-08-20 09:58:44 -04:00
|
|
|
self, batch: Batch, buffer: ReplayBuffer, indices: np.ndarray
|
2020-09-12 15:39:01 +08:00
|
|
|
) -> Batch:
|
2021-03-28 18:28:36 +08:00
|
|
|
if self._recompute_adv:
|
2021-08-20 09:58:44 -04:00
|
|
|
# buffer input `buffer` and `indices` to be used in `learn()`.
|
|
|
|
self._buffer, self._indices = buffer, indices
|
|
|
|
batch = self._compute_returns(batch, buffer, indices)
|
2021-03-28 18:28:36 +08:00
|
|
|
batch.act = to_torch_as(batch.act, batch.v_s)
|
2020-04-14 21:11:06 +08:00
|
|
|
with torch.no_grad():
|
2022-12-04 12:23:18 -08:00
|
|
|
batch.logp_old = self(batch).dist.log_prob(batch.act)
|
2021-03-23 22:05:48 +08:00
|
|
|
return batch
|
2020-03-20 19:52:29 +08:00
|
|
|
|
2020-09-13 19:31:50 +08:00
|
|
|
def learn( # type: ignore
|
2020-09-12 15:39:01 +08:00
|
|
|
self, batch: Batch, batch_size: int, repeat: int, **kwargs: Any
|
|
|
|
) -> Dict[str, List[float]]:
|
2020-03-20 19:52:29 +08:00
|
|
|
losses, clip_losses, vf_losses, ent_losses = [], [], [], []
|
2021-03-28 18:28:36 +08:00
|
|
|
for step in range(repeat):
|
|
|
|
if self._recompute_adv and step > 0:
|
2021-08-20 09:58:44 -04:00
|
|
|
batch = self._compute_returns(batch, self._buffer, self._indices)
|
2022-01-30 00:53:56 +08:00
|
|
|
for minibatch in batch.split(batch_size, merge_last=True):
|
2021-03-25 10:12:39 +08:00
|
|
|
# calculate loss for actor
|
2022-01-30 00:53:56 +08:00
|
|
|
dist = self(minibatch).dist
|
2021-03-28 18:28:36 +08:00
|
|
|
if self._norm_adv:
|
2022-01-30 00:53:56 +08:00
|
|
|
mean, std = minibatch.adv.mean(), minibatch.adv.std()
|
2022-12-04 12:23:18 -08:00
|
|
|
minibatch.adv = (minibatch.adv -
|
|
|
|
mean) / (std + self._eps) # per-batch norm
|
2022-01-30 00:53:56 +08:00
|
|
|
ratio = (dist.log_prob(minibatch.act) -
|
|
|
|
minibatch.logp_old).exp().float()
|
2020-07-24 17:38:12 +08:00
|
|
|
ratio = ratio.reshape(ratio.size(0), -1).transpose(0, 1)
|
2022-01-30 00:53:56 +08:00
|
|
|
surr1 = ratio * minibatch.adv
|
|
|
|
surr2 = ratio.clamp(
|
|
|
|
1.0 - self._eps_clip, 1.0 + self._eps_clip
|
|
|
|
) * minibatch.adv
|
2020-04-19 14:30:42 +08:00
|
|
|
if self._dual_clip:
|
2021-09-02 21:43:14 +08:00
|
|
|
clip1 = torch.min(surr1, surr2)
|
2022-01-30 00:53:56 +08:00
|
|
|
clip2 = torch.max(clip1, self._dual_clip * minibatch.adv)
|
|
|
|
clip_loss = -torch.where(minibatch.adv < 0, clip2, clip1).mean()
|
2020-04-19 14:30:42 +08:00
|
|
|
else:
|
|
|
|
clip_loss = -torch.min(surr1, surr2).mean()
|
2021-03-25 10:12:39 +08:00
|
|
|
# calculate loss for critic
|
2022-01-30 00:53:56 +08:00
|
|
|
value = self.critic(minibatch.obs).flatten()
|
2020-04-19 14:30:42 +08:00
|
|
|
if self._value_clip:
|
2022-01-30 00:53:56 +08:00
|
|
|
v_clip = minibatch.v_s + \
|
|
|
|
(value - minibatch.v_s).clamp(-self._eps_clip, self._eps_clip)
|
|
|
|
vf1 = (minibatch.returns - value).pow(2)
|
|
|
|
vf2 = (minibatch.returns - v_clip).pow(2)
|
2021-03-28 18:28:36 +08:00
|
|
|
vf_loss = torch.max(vf1, vf2).mean()
|
2020-04-19 14:30:42 +08:00
|
|
|
else:
|
2022-01-30 00:53:56 +08:00
|
|
|
vf_loss = (minibatch.returns - value).pow(2).mean()
|
2021-03-25 10:12:39 +08:00
|
|
|
# calculate regularization and overall loss
|
|
|
|
ent_loss = dist.entropy().mean()
|
2021-02-27 11:20:43 +08:00
|
|
|
loss = clip_loss + self._weight_vf * vf_loss \
|
2021-03-25 10:12:39 +08:00
|
|
|
- self._weight_ent * ent_loss
|
2020-03-20 19:52:29 +08:00
|
|
|
self.optim.zero_grad()
|
|
|
|
loss.backward()
|
2021-03-28 13:12:43 +08:00
|
|
|
if self._grad_norm: # clip large gradient
|
2020-10-31 16:38:54 +08:00
|
|
|
nn.utils.clip_grad_norm_(
|
2021-10-04 11:19:07 -04:00
|
|
|
self._actor_critic.parameters(), max_norm=self._grad_norm
|
2021-09-03 05:05:04 +08:00
|
|
|
)
|
2020-03-20 19:52:29 +08:00
|
|
|
self.optim.step()
|
2021-03-25 10:12:39 +08:00
|
|
|
clip_losses.append(clip_loss.item())
|
|
|
|
vf_losses.append(vf_loss.item())
|
|
|
|
ent_losses.append(ent_loss.item())
|
|
|
|
losses.append(loss.item())
|
2021-03-22 16:57:24 +08:00
|
|
|
|
2020-03-20 19:52:29 +08:00
|
|
|
return {
|
2020-09-12 15:39:01 +08:00
|
|
|
"loss": losses,
|
|
|
|
"loss/clip": clip_losses,
|
|
|
|
"loss/vf": vf_losses,
|
|
|
|
"loss/ent": ent_losses,
|
2020-03-20 19:52:29 +08:00
|
|
|
}
|