stable-baselines3/stable_baselines3/td3/policies.py

282 lines
13 KiB
Python
Raw Normal View History

from typing import Optional, List, Tuple, Callable, Union, Type, Any, Dict
2020-03-16 12:31:06 +00:00
import gym
2019-09-05 15:29:41 +00:00
import torch as th
import torch.nn as nn
2020-05-05 13:02:35 +00:00
from stable_baselines3.common.preprocessing import get_action_dim
from stable_baselines3.common.policies import (BasePolicy, register_policy, create_mlp,
2020-05-08 13:10:46 +00:00
NatureCNN, BaseFeaturesExtractor, FlattenExtractor)
2019-09-06 12:01:10 +00:00
2020-03-23 14:31:14 +00:00
class Actor(BasePolicy):
2019-11-22 16:24:47 +00:00
"""
Actor network (policy) for TD3.
2020-03-23 14:31:14 +00:00
:param observation_space: (gym.spaces.Space) Obervation space
:param action_space: (gym.spaces.Space) Action space
2019-11-22 16:24:47 +00:00
:param net_arch: ([int]) Network architecture
2020-03-23 16:15:30 +00:00
:param features_extractor: (nn.Module) Network to extract features
(a CNN when using images, a nn.Flatten() layer otherwise)
:param features_dim: (int) Number of features
2020-03-24 09:10:37 +00:00
:param activation_fn: (Type[nn.Module]) Activation function
2020-03-23 16:15:30 +00:00
:param normalize_images: (bool) Whether to normalize images or not,
dividing by 255.0 (True by default)
:param device: (Union[th.device, str]) Device on which the code should run.
2019-11-22 16:24:47 +00:00
"""
2020-05-08 13:10:46 +00:00
2020-01-27 13:32:31 +00:00
def __init__(self,
2020-03-23 14:31:14 +00:00
observation_space: gym.spaces.Space,
action_space: gym.spaces.Space,
2020-01-27 13:32:31 +00:00
net_arch: List[int],
2020-03-23 16:15:30 +00:00
features_extractor: nn.Module,
features_dim: int,
2020-03-24 09:10:37 +00:00
activation_fn: Type[nn.Module] = nn.ReLU,
normalize_images: bool = True,
device: Union[th.device, str] = 'auto'):
2020-03-23 16:15:30 +00:00
super(Actor, self).__init__(observation_space, action_space,
features_extractor=features_extractor,
normalize_images=normalize_images,
device=device,
2020-05-08 13:00:34 +00:00
squash_output=True)
2020-03-23 16:15:30 +00:00
self.features_extractor = features_extractor
self.normalize_images = normalize_images
2020-04-20 13:43:23 +00:00
self.net_arch = net_arch
self.features_dim = features_dim
self.activation_fn = activation_fn
2019-11-07 16:31:52 +00:00
2020-03-23 14:31:14 +00:00
action_dim = get_action_dim(self.action_space)
2020-05-08 13:00:34 +00:00
actor_net = create_mlp(features_dim, action_dim, net_arch, activation_fn, squash_output=True)
# Deterministic action
self.mu = nn.Sequential(*actor_net)
2019-11-07 16:31:52 +00:00
2020-04-20 13:43:23 +00:00
def _get_data(self) -> Dict[str, Any]:
data = super()._get_data()
data.update(dict(
2020-05-08 13:10:46 +00:00
net_arch=self.net_arch,
features_dim=self.features_dim,
activation_fn=self.activation_fn,
features_extractor=self.features_extractor
2020-04-20 13:43:23 +00:00
))
return data
2020-03-16 12:31:06 +00:00
def forward(self, obs: th.Tensor, deterministic: bool = True) -> th.Tensor:
2020-05-08 13:00:34 +00:00
# assert deterministic, 'The TD3 actor only outputs deterministic actions'
features = self.extract_features(obs)
return self.mu(features)
2019-09-05 15:29:41 +00:00
def _predict(self, observation: th.Tensor, deterministic: bool = False) -> th.Tensor:
return self.forward(observation, deterministic=deterministic)
2019-09-05 15:29:41 +00:00
2020-03-23 14:31:14 +00:00
class Critic(BasePolicy):
2019-11-22 16:24:47 +00:00
"""
Critic network for TD3,
in fact it represents the action-state value function (Q-value function)
2020-03-23 14:31:14 +00:00
:param observation_space: (gym.spaces.Space) Obervation space
:param action_space: (gym.spaces.Space) Action space
2019-11-22 16:24:47 +00:00
:param net_arch: ([int]) Network architecture
2020-03-23 16:15:30 +00:00
:param features_extractor: (nn.Module) Network to extract features
(a CNN when using images, a nn.Flatten() layer otherwise)
:param features_dim: (int) Number of features
2020-03-24 09:10:37 +00:00
:param activation_fn: (Type[nn.Module]) Activation function
2020-03-23 16:15:30 +00:00
:param normalize_images: (bool) Whether to normalize images or not,
dividing by 255.0 (True by default)
:param device: (Union[th.device, str]) Device on which the code should run.
2019-11-22 16:24:47 +00:00
"""
2020-05-08 13:10:46 +00:00
2020-03-23 14:31:14 +00:00
def __init__(self, observation_space: gym.spaces.Space,
action_space: gym.spaces.Space,
net_arch: List[int],
2020-03-23 16:15:30 +00:00
features_extractor: nn.Module,
features_dim: int,
2020-03-24 09:10:37 +00:00
activation_fn: Type[nn.Module] = nn.ReLU,
normalize_images: bool = True,
device: Union[th.device, str] = 'auto'):
2020-03-23 16:15:30 +00:00
super(Critic, self).__init__(observation_space, action_space,
features_extractor=features_extractor,
normalize_images=normalize_images,
device=device)
2020-03-23 14:31:14 +00:00
action_dim = get_action_dim(self.action_space)
2019-09-05 15:29:41 +00:00
2020-03-23 16:15:30 +00:00
q1_net = create_mlp(features_dim + action_dim, 1, net_arch, activation_fn)
2019-09-12 09:19:06 +00:00
self.q1_net = nn.Sequential(*q1_net)
2020-03-23 16:15:30 +00:00
q2_net = create_mlp(features_dim + action_dim, 1, net_arch, activation_fn)
2019-09-12 09:19:06 +00:00
self.q2_net = nn.Sequential(*q2_net)
def forward(self, obs: th.Tensor, actions: th.Tensor) -> Tuple[th.Tensor, th.Tensor]:
2020-04-22 09:05:46 +00:00
# Learn the features extractor using the policy loss only
with th.no_grad():
features = self.extract_features(obs)
qvalue_input = th.cat([features, actions], dim=1)
2020-01-27 13:32:31 +00:00
return self.q1_net(qvalue_input), self.q2_net(qvalue_input)
2019-09-05 15:29:41 +00:00
def q1_forward(self, obs: th.Tensor, actions: th.Tensor) -> th.Tensor:
2020-04-22 09:05:46 +00:00
with th.no_grad():
features = self.extract_features(obs)
return self.q1_net(th.cat([features, actions], dim=1))
2019-09-05 15:29:41 +00:00
class TD3Policy(BasePolicy):
2019-11-22 16:24:47 +00:00
"""
Policy class (with both actor and critic) for TD3.
:param observation_space: (gym.spaces.Space) Observation space
2019-12-02 13:27:38 +00:00
:param action_space: (gym.spaces.Space) Action space
:param lr_schedule: (Callable) Learning rate schedule (could be constant)
:param net_arch: (Optional[List[int]]) The specification of the policy and value networks.
:param device: (Union[th.device, str]) Device on which the code should run.
2020-03-24 09:10:37 +00:00
:param activation_fn: (Type[nn.Module]) Activation function
2020-04-22 09:05:46 +00:00
:param features_extractor_class: (Type[BaseFeaturesExtractor]) Features extractor to use.
:param features_extractor_kwargs: (Optional[Dict[str, Any]]) Keyword arguments
to pass to the feature extractor.
2020-03-23 16:15:30 +00:00
:param normalize_images: (bool) Whether to normalize images or not,
dividing by 255.0 (True by default)
2020-04-22 11:14:22 +00:00
:param optimizer_class: (Type[th.optim.Optimizer]) The optimizer to use,
``th.optim.Adam`` by default
:param optimizer_kwargs: (Optional[Dict[str, Any]]) Additional keyword arguments,
excluding the learning rate, to pass to the optimizer
2019-11-22 16:24:47 +00:00
"""
2020-05-08 13:10:46 +00:00
2020-03-16 12:31:06 +00:00
def __init__(self, observation_space: gym.spaces.Space,
action_space: gym.spaces.Space,
lr_schedule: Callable,
2020-03-16 12:31:06 +00:00
net_arch: Optional[List[int]] = None,
device: Union[th.device, str] = 'auto',
2020-03-24 09:10:37 +00:00
activation_fn: Type[nn.Module] = nn.ReLU,
2020-04-22 09:05:46 +00:00
features_extractor_class: Type[BaseFeaturesExtractor] = FlattenExtractor,
features_extractor_kwargs: Optional[Dict[str, Any]] = None,
normalize_images: bool = True,
2020-04-22 11:14:22 +00:00
optimizer_class: Type[th.optim.Optimizer] = th.optim.Adam,
optimizer_kwargs: Optional[Dict[str, Any]] = None):
2020-04-22 11:14:22 +00:00
super(TD3Policy, self).__init__(observation_space, action_space,
device,
features_extractor_class,
features_extractor_kwargs,
optimizer_class=optimizer_class,
optimizer_kwargs=optimizer_kwargs,
squash_output=True)
2019-10-10 11:47:13 +00:00
2019-11-22 16:24:47 +00:00
# Default network architecture, from the original paper
2019-10-10 11:47:13 +00:00
if net_arch is None:
2020-04-22 09:05:46 +00:00
if features_extractor_class == FlattenExtractor:
net_arch = [400, 300]
else:
net_arch = []
2019-10-10 11:47:13 +00:00
2020-04-22 11:14:22 +00:00
self.features_extractor = features_extractor_class(self.observation_space,
**self.features_extractor_kwargs)
2020-04-22 09:05:46 +00:00
self.features_dim = self.features_extractor.features_dim
2020-03-23 16:15:30 +00:00
2019-09-05 15:29:41 +00:00
self.net_arch = net_arch
2019-09-09 14:45:55 +00:00
self.activation_fn = activation_fn
2019-09-10 11:07:15 +00:00
self.net_args = {
2020-03-23 14:31:14 +00:00
'observation_space': self.observation_space,
'action_space': self.action_space,
2020-03-23 16:15:30 +00:00
'features_extractor': self.features_extractor,
'features_dim': self.features_dim,
2019-09-10 11:07:15 +00:00
'net_arch': self.net_arch,
2020-03-23 16:15:30 +00:00
'activation_fn': self.activation_fn,
'normalize_images': normalize_images,
'device': device
2019-09-10 11:07:15 +00:00
}
2019-09-09 14:45:55 +00:00
self.actor, self.actor_target = None, None
self.critic, self.critic_target = None, None
2020-05-08 13:00:34 +00:00
self._build(lr_schedule)
2019-09-05 15:29:41 +00:00
def _build(self, lr_schedule: Callable) -> None:
2019-09-05 15:29:41 +00:00
self.actor = self.make_actor()
self.actor_target = self.make_actor()
self.actor_target.load_state_dict(self.actor.state_dict())
self.actor.optimizer = self.optimizer_class(self.actor.parameters(), lr=lr_schedule(1),
**self.optimizer_kwargs)
2019-09-05 15:29:41 +00:00
self.critic = self.make_critic()
self.critic_target = self.make_critic()
self.critic_target.load_state_dict(self.critic.state_dict())
self.critic.optimizer = self.optimizer_class(self.critic.parameters(), lr=lr_schedule(1),
**self.optimizer_kwargs)
2019-12-17 14:01:08 +00:00
2020-04-20 13:43:23 +00:00
def _get_data(self) -> Dict[str, Any]:
data = super()._get_data()
data.update(dict(
2020-05-08 13:10:46 +00:00
net_arch=self.net_args['net_arch'],
activation_fn=self.net_args['activation_fn'],
lr_schedule=self._dummy_schedule, # dummy lr schedule, not needed for loading policy alone
optimizer_class=self.optimizer_class,
optimizer_kwargs=self.optimizer_kwargs,
features_extractor_class=self.features_extractor_class,
features_extractor_kwargs=self.features_extractor_kwargs
2020-04-20 13:43:23 +00:00
))
return data
2020-03-16 12:31:06 +00:00
def make_actor(self) -> Actor:
2020-05-08 13:00:34 +00:00
return Actor(**self.net_args).to(self.device)
2019-09-05 15:29:41 +00:00
2020-03-16 12:31:06 +00:00
def make_critic(self) -> Critic:
2019-09-10 11:07:15 +00:00
return Critic(**self.net_args).to(self.device)
2019-09-06 08:44:55 +00:00
2020-03-16 12:31:06 +00:00
def forward(self, observation: th.Tensor, deterministic: bool = False):
return self._predict(observation, deterministic=deterministic)
2019-09-24 12:53:03 +00:00
def _predict(self, observation: th.Tensor, deterministic: bool = False) -> th.Tensor:
2020-03-16 12:31:06 +00:00
return self.actor(observation, deterministic=deterministic)
2020-02-12 14:25:05 +00:00
2019-09-21 15:17:09 +00:00
2019-09-06 08:44:55 +00:00
MlpPolicy = TD3Policy
2020-04-22 09:05:46 +00:00
class CnnPolicy(TD3Policy):
"""
Policy class (with both actor and critic) for TD3.
:param observation_space: (gym.spaces.Space) Observation space
:param action_space: (gym.spaces.Space) Action space
:param lr_schedule: (Callable) Learning rate schedule (could be constant)
:param net_arch: (Optional[List[int]]) The specification of the policy and value networks.
:param device: (Union[th.device, str]) Device on which the code should run.
:param activation_fn: (Type[nn.Module]) Activation function
:param features_extractor_class: (Type[BaseFeaturesExtractor]) Features extractor to use.
:param features_extractor_kwargs: (Optional[Dict[str, Any]]) Keyword arguments
to pass to the feature extractor.
:param normalize_images: (bool) Whether to normalize images or not,
dividing by 255.0 (True by default)
2020-04-22 11:14:22 +00:00
:param optimizer_class: (Type[th.optim.Optimizer]) The optimizer to use,
2020-04-22 09:05:46 +00:00
``th.optim.Adam`` by default
:param optimizer_kwargs: (Optional[Dict[str, Any]]) Additional keyword arguments,
excluding the learning rate, to pass to the optimizer
"""
2020-05-08 13:10:46 +00:00
2020-04-22 09:05:46 +00:00
def __init__(self, observation_space: gym.spaces.Space,
action_space: gym.spaces.Space,
lr_schedule: Callable,
net_arch: Optional[List[int]] = None,
device: Union[th.device, str] = 'auto',
activation_fn: Type[nn.Module] = nn.ReLU,
features_extractor_class: Type[BaseFeaturesExtractor] = NatureCNN,
features_extractor_kwargs: Optional[Dict[str, Any]] = None,
normalize_images: bool = True,
2020-04-22 11:14:22 +00:00
optimizer_class: Type[th.optim.Optimizer] = th.optim.Adam,
2020-04-22 09:05:46 +00:00
optimizer_kwargs: Optional[Dict[str, Any]] = None):
super(CnnPolicy, self).__init__(observation_space,
action_space,
lr_schedule,
net_arch,
device,
activation_fn,
features_extractor_class,
features_extractor_kwargs,
normalize_images,
2020-04-22 11:14:22 +00:00
optimizer_class,
2020-04-22 09:05:46 +00:00
optimizer_kwargs)
2020-04-23 13:18:21 +00:00
2019-09-06 08:44:55 +00:00
register_policy("MlpPolicy", MlpPolicy)
2020-04-22 09:05:46 +00:00
register_policy("CnnPolicy", CnnPolicy)