2017-11-12 00:20:33 -08:00
|
|
|
""" Code adapted from https://github.com/ikostrikov/pytorch-a3c"""
|
|
|
|
import numpy as np
|
2020-11-12 03:16:12 -08:00
|
|
|
from typing import Union, Tuple, Any, List
|
2019-12-30 15:27:32 -05:00
|
|
|
|
2020-12-30 22:30:52 -05:00
|
|
|
from ray.rllib.models.utils import get_activation_fn
|
|
|
|
from ray.rllib.utils.framework import try_import_torch
|
2020-11-12 03:16:12 -08:00
|
|
|
from ray.rllib.utils.typing import TensorType
|
2019-12-30 15:27:32 -05:00
|
|
|
|
|
|
|
torch, nn = try_import_torch()
|
2017-11-12 00:20:33 -08:00
|
|
|
|
|
|
|
|
2020-11-12 03:16:12 -08:00
|
|
|
def normc_initializer(std: float = 1.0) -> Any:
|
2017-11-12 00:20:33 -08:00
|
|
|
def initializer(tensor):
|
|
|
|
tensor.data.normal_(0, 1)
|
|
|
|
tensor.data *= std / torch.sqrt(
|
|
|
|
tensor.data.pow(2).sum(1, keepdim=True))
|
2018-05-30 10:48:11 -07:00
|
|
|
|
2017-11-12 00:20:33 -08:00
|
|
|
return initializer
|
|
|
|
|
|
|
|
|
2020-11-12 03:16:12 -08:00
|
|
|
def same_padding(in_size: Tuple[int, int], filter_size: Tuple[int, int],
|
|
|
|
stride_size: Union[int, Tuple[int, int]]
|
|
|
|
) -> (Union[int, Tuple[int, int]], Tuple[int, int]):
|
2017-11-12 00:20:33 -08:00
|
|
|
"""Note: Padding is added to match TF conv2d `same` padding. See
|
|
|
|
www.tensorflow.org/versions/r0.12/api_docs/python/nn/convolution
|
|
|
|
|
2020-07-25 09:29:24 +02:00
|
|
|
Args:
|
2017-11-12 00:20:33 -08:00
|
|
|
in_size (tuple): Rows (Height), Column (Width) for input
|
2020-07-25 09:29:24 +02:00
|
|
|
stride_size (Union[int,Tuple[int, int]]): Rows (Height), column (Width)
|
|
|
|
for stride. If int, height == width.
|
|
|
|
filter_size (tuple): Rows (Height), column (Width) for filter
|
2017-11-12 00:20:33 -08:00
|
|
|
|
2020-07-25 09:29:24 +02:00
|
|
|
Returns:
|
2020-06-20 00:05:19 +02:00
|
|
|
padding (tuple): For input into torch.nn.ZeroPad2d.
|
|
|
|
output (tuple): Output shape after padding and convolution.
|
2017-11-12 00:20:33 -08:00
|
|
|
"""
|
|
|
|
in_height, in_width = in_size
|
2020-07-25 09:29:24 +02:00
|
|
|
if isinstance(filter_size, int):
|
|
|
|
filter_height, filter_width = filter_size, filter_size
|
|
|
|
else:
|
|
|
|
filter_height, filter_width = filter_size
|
2017-11-12 00:20:33 -08:00
|
|
|
stride_height, stride_width = stride_size
|
|
|
|
|
|
|
|
out_height = np.ceil(float(in_height) / float(stride_height))
|
|
|
|
out_width = np.ceil(float(in_width) / float(stride_width))
|
|
|
|
|
|
|
|
pad_along_height = int(
|
|
|
|
((out_height - 1) * stride_height + filter_height - in_height))
|
|
|
|
pad_along_width = int(
|
|
|
|
((out_width - 1) * stride_width + filter_width - in_width))
|
|
|
|
pad_top = pad_along_height // 2
|
|
|
|
pad_bottom = pad_along_height - pad_top
|
|
|
|
pad_left = pad_along_width // 2
|
|
|
|
pad_right = pad_along_width - pad_left
|
|
|
|
padding = (pad_left, pad_right, pad_top, pad_bottom)
|
|
|
|
output = (out_height, out_width)
|
|
|
|
return padding, output
|
2019-01-03 13:48:33 +08:00
|
|
|
|
|
|
|
|
|
|
|
class SlimConv2d(nn.Module):
|
|
|
|
"""Simple mock of tf.slim Conv2d"""
|
|
|
|
|
2020-04-15 13:25:16 +02:00
|
|
|
def __init__(
|
|
|
|
self,
|
2020-11-12 03:16:12 -08:00
|
|
|
in_channels: int,
|
|
|
|
out_channels: int,
|
|
|
|
kernel: Union[int, Tuple[int, int]],
|
|
|
|
stride: Union[int, Tuple[int, int]],
|
|
|
|
padding: Union[int, Tuple[int, int]],
|
2020-04-15 13:25:16 +02:00
|
|
|
# Defaulting these to nn.[..] will break soft torch import.
|
2020-11-12 03:16:12 -08:00
|
|
|
initializer: Any = "default",
|
|
|
|
activation_fn: Any = "default",
|
|
|
|
bias_init: float = 0):
|
|
|
|
"""Creates a standard Conv2d layer, similar to torch.nn.Conv2d
|
|
|
|
|
|
|
|
Args:
|
|
|
|
in_channels(int): Number of input channels
|
|
|
|
out_channels (int): Number of output channels
|
|
|
|
kernel (Union[int, Tuple[int, int]]): If int, the kernel is
|
|
|
|
a tuple(x,x). Elsewise, the tuple can be specified
|
|
|
|
stride (Union[int, Tuple[int, int]]): Controls the stride
|
|
|
|
for the cross-correlation. If int, the stride is a
|
|
|
|
tuple(x,x). Elsewise, the tuple can be specified
|
|
|
|
padding (Union[int, Tuple[int, int]]): Controls the amount
|
|
|
|
of implicit zero-paddings during the conv operation
|
|
|
|
initializer (Any): Initializer function for kernel weights
|
|
|
|
activation_fn (Any): Activation function at the end of layer
|
|
|
|
bias_init (float): Initalize bias weights to bias_init const
|
|
|
|
"""
|
2019-01-03 13:48:33 +08:00
|
|
|
super(SlimConv2d, self).__init__()
|
|
|
|
layers = []
|
2020-08-19 17:49:50 +02:00
|
|
|
# Padding layer.
|
2019-01-03 13:48:33 +08:00
|
|
|
if padding:
|
|
|
|
layers.append(nn.ZeroPad2d(padding))
|
2020-08-19 17:49:50 +02:00
|
|
|
# Actual Conv2D layer (including correct initialization logic).
|
2019-01-03 13:48:33 +08:00
|
|
|
conv = nn.Conv2d(in_channels, out_channels, kernel, stride)
|
|
|
|
if initializer:
|
2020-04-15 13:25:16 +02:00
|
|
|
if initializer == "default":
|
|
|
|
initializer = nn.init.xavier_uniform_
|
2019-01-03 13:48:33 +08:00
|
|
|
initializer(conv.weight)
|
|
|
|
nn.init.constant_(conv.bias, bias_init)
|
|
|
|
layers.append(conv)
|
2020-08-19 17:49:50 +02:00
|
|
|
# Activation function (if any; default=ReLu).
|
|
|
|
if isinstance(activation_fn, str):
|
2020-04-15 13:25:16 +02:00
|
|
|
if activation_fn == "default":
|
|
|
|
activation_fn = nn.ReLU
|
2020-08-19 17:49:50 +02:00
|
|
|
else:
|
|
|
|
activation_fn = get_activation_fn(activation_fn, "torch")
|
|
|
|
if activation_fn is not None:
|
2019-01-03 13:48:33 +08:00
|
|
|
layers.append(activation_fn())
|
2020-08-19 17:49:50 +02:00
|
|
|
# Put everything in sequence.
|
2019-01-03 13:48:33 +08:00
|
|
|
self._model = nn.Sequential(*layers)
|
|
|
|
|
2020-11-12 03:16:12 -08:00
|
|
|
def forward(self, x: TensorType) -> TensorType:
|
2019-01-03 13:48:33 +08:00
|
|
|
return self._model(x)
|
|
|
|
|
|
|
|
|
|
|
|
class SlimFC(nn.Module):
|
|
|
|
"""Simple PyTorch version of `linear` function"""
|
|
|
|
|
|
|
|
def __init__(self,
|
2020-11-12 03:16:12 -08:00
|
|
|
in_size: int,
|
|
|
|
out_size: int,
|
|
|
|
initializer: Any = None,
|
|
|
|
activation_fn: Any = None,
|
|
|
|
use_bias: bool = True,
|
|
|
|
bias_init: float = 0.0):
|
|
|
|
"""Creates a standard FC layer, similar to torch.nn.Linear
|
|
|
|
|
|
|
|
Args:
|
|
|
|
in_size(int): Input size for FC Layer
|
|
|
|
out_size (int): Output size for FC Layer
|
|
|
|
initializer (Any): Initializer function for FC layer weights
|
|
|
|
activation_fn (Any): Activation function at the end of layer
|
|
|
|
use_bias (bool): Whether to add bias weights or not
|
|
|
|
bias_init (float): Initalize bias weights to bias_init const
|
|
|
|
"""
|
2019-01-03 13:48:33 +08:00
|
|
|
super(SlimFC, self).__init__()
|
|
|
|
layers = []
|
2020-12-03 15:51:30 +01:00
|
|
|
# Actual nn.Linear layer (including correct initialization logic).
|
2020-06-23 14:42:30 -04:00
|
|
|
linear = nn.Linear(in_size, out_size, bias=use_bias)
|
2019-01-03 13:48:33 +08:00
|
|
|
if initializer:
|
|
|
|
initializer(linear.weight)
|
2020-06-23 14:42:30 -04:00
|
|
|
if use_bias is True:
|
|
|
|
nn.init.constant_(linear.bias, bias_init)
|
2019-01-03 13:48:33 +08:00
|
|
|
layers.append(linear)
|
2020-08-19 17:49:50 +02:00
|
|
|
# Activation function (if any; default=None (linear)).
|
2020-07-25 09:29:24 +02:00
|
|
|
if isinstance(activation_fn, str):
|
|
|
|
activation_fn = get_activation_fn(activation_fn, "torch")
|
|
|
|
if activation_fn is not None:
|
2019-01-03 13:48:33 +08:00
|
|
|
layers.append(activation_fn())
|
2020-08-19 17:49:50 +02:00
|
|
|
# Put everything in sequence.
|
2019-01-03 13:48:33 +08:00
|
|
|
self._model = nn.Sequential(*layers)
|
|
|
|
|
2020-11-12 03:16:12 -08:00
|
|
|
def forward(self, x: TensorType) -> TensorType:
|
2019-01-03 13:48:33 +08:00
|
|
|
return self._model(x)
|
2020-05-12 10:14:05 -07:00
|
|
|
|
|
|
|
|
|
|
|
class AppendBiasLayer(nn.Module):
|
|
|
|
"""Simple bias appending layer for free_log_std."""
|
|
|
|
|
2020-11-12 03:16:12 -08:00
|
|
|
def __init__(self, num_bias_vars: int):
|
2020-05-12 10:14:05 -07:00
|
|
|
super().__init__()
|
|
|
|
self.log_std = torch.nn.Parameter(
|
|
|
|
torch.as_tensor([0.0] * num_bias_vars))
|
|
|
|
self.register_parameter("log_std", self.log_std)
|
|
|
|
|
2020-11-12 03:16:12 -08:00
|
|
|
def forward(self, x: TensorType) -> TensorType:
|
2020-05-12 10:14:05 -07:00
|
|
|
out = torch.cat(
|
|
|
|
[x, self.log_std.unsqueeze(0).repeat([len(x), 1])], axis=1)
|
|
|
|
return out
|
2020-10-12 15:00:42 +02:00
|
|
|
|
|
|
|
|
|
|
|
class Reshape(nn.Module):
|
|
|
|
"""Standard module that reshapes/views a tensor
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, shape: List):
|
|
|
|
super().__init__()
|
|
|
|
self.shape = shape
|
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
return x.view(*self.shape)
|