169 lines
6.6 KiB
Python
Raw Normal View History

2020-03-18 21:45:41 +08:00
import torch
2020-03-21 15:31:31 +08:00
import numpy as np
2020-03-18 21:45:41 +08:00
from copy import deepcopy
import torch.nn.functional as F
2020-05-12 11:31:47 +08:00
from typing import Dict, Tuple, Union, Optional
2020-03-18 21:45:41 +08:00
from tianshou.policy import BasePolicy
from tianshou.exploration import BaseNoise, GaussianNoise
2020-06-03 13:59:47 +08:00
from tianshou.data import Batch, ReplayBuffer, to_torch_as
2020-03-18 21:45:41 +08:00
class DDPGPolicy(BasePolicy):
2020-04-06 19:36:59 +08:00
"""Implementation of Deep Deterministic Policy Gradient. arXiv:1509.02971
:param torch.nn.Module actor: the actor network following the rules in
:class:`~tianshou.policy.BasePolicy`. (s -> logits)
:param torch.optim.Optimizer actor_optim: the optimizer for actor network.
:param torch.nn.Module critic: the critic network. (s, a -> Q(s, a))
:param torch.optim.Optimizer critic_optim: the optimizer for critic
network.
:param float tau: param for soft update of the target network, defaults to
0.005.
:param float gamma: discount factor, in [0, 1], defaults to 0.99.
:param BaseNoise exploration_noise: the exploration noise,
add to the action, defaults to ``GaussianNoise(sigma=0.1)``.
2020-04-06 19:36:59 +08:00
:param action_range: the action range (minimum, maximum).
2020-05-12 11:31:47 +08:00
:type action_range: (float, float)
2020-04-06 19:36:59 +08:00
:param bool reward_normalization: normalize the reward to Normal(0, 1),
defaults to ``False``.
:param bool ignore_done: ignore the done flag while training the policy,
defaults to ``False``.
2020-06-03 13:59:47 +08:00
:param int estimation_step: greater than 1, the number of steps to look
ahead.
.. seealso::
Please refer to :class:`~tianshou.policy.BasePolicy` for more detailed
explanation.
2020-04-06 19:36:59 +08:00
"""
2020-03-18 21:45:41 +08:00
2020-05-12 11:31:47 +08:00
def __init__(self,
actor: torch.nn.Module,
actor_optim: torch.optim.Optimizer,
critic: torch.nn.Module,
critic_optim: torch.optim.Optimizer,
2020-05-16 20:08:32 +08:00
tau: float = 0.005,
gamma: float = 0.99,
exploration_noise: Optional[BaseNoise]
= GaussianNoise(sigma=0.1),
2020-05-12 11:31:47 +08:00
action_range: Optional[Tuple[float, float]] = None,
2020-05-16 20:08:32 +08:00
reward_normalization: bool = False,
ignore_done: bool = False,
2020-06-03 13:59:47 +08:00
estimation_step: int = 1,
2020-05-12 11:31:47 +08:00
**kwargs) -> None:
2020-04-08 21:13:15 +08:00
super().__init__(**kwargs)
2020-03-23 17:17:41 +08:00
if actor is not None:
self.actor, self.actor_old = actor, deepcopy(actor)
self.actor_old.eval()
self.actor_optim = actor_optim
2020-03-23 11:34:52 +08:00
if critic is not None:
self.critic, self.critic_old = critic, deepcopy(critic)
self.critic_old.eval()
self.critic_optim = critic_optim
2020-04-06 19:36:59 +08:00
assert 0 <= tau <= 1, 'tau should in [0, 1]'
2020-03-18 21:45:41 +08:00
self._tau = tau
2020-04-06 19:36:59 +08:00
assert 0 <= gamma <= 1, 'gamma should in [0, 1]'
2020-03-18 21:45:41 +08:00
self._gamma = gamma
self._noise = exploration_noise
2020-03-23 17:17:41 +08:00
assert action_range is not None
2020-03-18 21:45:41 +08:00
self._range = action_range
2020-03-23 17:17:41 +08:00
self._action_bias = (action_range[0] + action_range[1]) / 2
self._action_scale = (action_range[1] - action_range[0]) / 2
# it is only a little difference to use rand_normal
2020-03-18 21:45:41 +08:00
# self.noise = OUNoise()
2020-03-25 14:08:28 +08:00
self._rm_done = ignore_done
2020-03-21 15:31:31 +08:00
self._rew_norm = reward_normalization
2020-06-03 13:59:47 +08:00
assert estimation_step > 0, 'estimation_step should greater than 0'
self._n_step = estimation_step
2020-03-18 21:45:41 +08:00
def set_exp_noise(self, noise: Optional[BaseNoise]) -> None:
"""Set the exploration noise."""
self._noise = noise
2020-03-18 21:45:41 +08:00
2020-05-12 11:31:47 +08:00
def train(self) -> None:
2020-04-06 19:36:59 +08:00
"""Set the module in training mode, except for the target network."""
2020-03-18 21:45:41 +08:00
self.training = True
self.actor.train()
self.critic.train()
2020-05-12 11:31:47 +08:00
def eval(self) -> None:
2020-04-06 19:36:59 +08:00
"""Set the module in evaluation mode, except for the target network."""
2020-03-18 21:45:41 +08:00
self.training = False
self.actor.eval()
self.critic.eval()
2020-05-12 11:31:47 +08:00
def sync_weight(self) -> None:
2020-04-06 19:36:59 +08:00
"""Soft-update the weight for the target network."""
2020-03-18 21:45:41 +08:00
for o, n in zip(self.actor_old.parameters(), self.actor.parameters()):
o.data.copy_(o.data * (1 - self._tau) + n.data * self._tau)
for o, n in zip(
self.critic_old.parameters(), self.critic.parameters()):
o.data.copy_(o.data * (1 - self._tau) + n.data * self._tau)
2020-06-03 13:59:47 +08:00
def _target_q(self, buffer: ReplayBuffer,
indice: np.ndarray) -> torch.Tensor:
batch = buffer[indice] # batch.obs_next: s_{t+n}
with torch.no_grad():
target_q = self.critic_old(batch.obs_next, self(
batch, model='actor_old', input='obs_next',
explorating=False).act)
2020-06-03 13:59:47 +08:00
return target_q
2020-05-12 11:31:47 +08:00
def process_fn(self, batch: Batch, buffer: ReplayBuffer,
indice: np.ndarray) -> Batch:
2020-03-25 14:08:28 +08:00
if self._rm_done:
batch.done = batch.done * 0.
2020-06-03 13:59:47 +08:00
batch = self.compute_nstep_return(
batch, buffer, indice, self._target_q,
self._gamma, self._n_step, self._rew_norm)
2020-03-23 17:17:41 +08:00
return batch
2020-05-12 11:31:47 +08:00
def forward(self, batch: Batch,
state: Optional[Union[dict, Batch, np.ndarray]] = None,
2020-05-16 20:08:32 +08:00
model: str = 'actor',
input: str = 'obs',
explorating: bool = True,
2020-05-12 11:31:47 +08:00
**kwargs) -> Batch:
2020-04-06 19:36:59 +08:00
"""Compute action over the given batch data.
:param float eps: in [0, 1], for exploration use.
:return: A :class:`~tianshou.data.Batch` which has 2 keys:
* ``act`` the action.
* ``state`` the hidden state.
.. seealso::
2020-04-10 10:47:16 +08:00
Please refer to :meth:`~tianshou.policy.BasePolicy.forward` for
more detailed explanation.
2020-04-06 19:36:59 +08:00
"""
2020-03-18 21:45:41 +08:00
model = getattr(self, model)
obs = getattr(batch, input)
logits, h = model(obs, state=state, info=batch.info)
2020-03-23 17:17:41 +08:00
logits += self._action_bias
if self.training and explorating:
logits += to_torch_as(self._noise(logits.shape), logits)
2020-03-23 17:17:41 +08:00
logits = logits.clamp(self._range[0], self._range[1])
2020-03-18 21:45:41 +08:00
return Batch(act=logits, state=h)
2020-05-12 11:31:47 +08:00
def learn(self, batch: Batch, **kwargs) -> Dict[str, float]:
2020-03-18 21:45:41 +08:00
current_q = self.critic(batch.obs, batch.act)
2020-06-03 13:59:47 +08:00
target_q = to_torch_as(batch.returns, current_q)
target_q = target_q[:, None]
2020-03-18 21:45:41 +08:00
critic_loss = F.mse_loss(current_q, target_q)
self.critic_optim.zero_grad()
critic_loss.backward()
self.critic_optim.step()
action = self(batch, explorating=False).act
actor_loss = -self.critic(batch.obs, action).mean()
2020-03-18 21:45:41 +08:00
self.actor_optim.zero_grad()
actor_loss.backward()
self.actor_optim.step()
2020-03-19 17:23:46 +08:00
self.sync_weight()
return {
2020-04-03 21:28:12 +08:00
'loss/actor': actor_loss.item(),
'loss/critic': critic_loss.item(),
2020-03-19 17:23:46 +08:00
}