-
Notifications
You must be signed in to change notification settings - Fork 0
/
modules.py
139 lines (110 loc) · 4.65 KB
/
modules.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
from math import sqrt
import torch
from torch import nn
from torch.distributions import Distribution, Normal
import numpy as np
from typing import Tuple, Optional
class Actor(nn.Module):
def __init__(self,
state_dim: int,
action_dim: int,
hidden_dim: int,
min_log_std: float = -20.0,
max_log_std: float = 2.0,
min_action: float = -1.0,
max_action: float = 1.0) -> None:
super().__init__()
self.net = nn.Sequential(
nn.Linear(state_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, action_dim)
)
self.log_std = nn.Parameter(torch.zeros(action_dim, dtype=torch.float32))
self.min_log_std = min_log_std
self.max_log_std = max_log_std
self.min_action = min_action
self.max_action = max_action
def get_policy(self, state: torch.Tensor) -> Distribution:
mean = self.net(state)
log_std = self.log_std.clamp(self.min_log_std, self.max_log_std)
policy = Normal(mean, log_std.exp())
return policy
def log_prob(self, state: torch.Tensor, action: torch.Tensor) -> torch.Tensor:
policy = self.get_policy(state)
log_prob = policy.log_prob(action).sum(-1, keepdim=True)
return log_prob
def act(self, state: np.ndarray, device: str) -> np.ndarray:
state = torch.tensor(state[None], dtype=torch.float32, device=device)
policy = self.get_policy(state)
#action = policy.mean
if self.net.training:
action = policy.sample()
else:
action = policy.mean
return action[0].cpu().numpy()
def forward(self, state: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
policy = self.get_policy(state)
action = policy.rsample().clamp(self.min_action, self.max_action)
log_prob = policy.log_prob(action).sum(-1, keepdim=True)
return action, log_prob
class EnsembleLinear(nn.Module):
def __init__(self,
in_features: int,
out_features: int,
ensemble_size: int) -> None:
super().__init__()
self.in_features = in_features
self.out_features = out_features
self.ensemble_size = ensemble_size
self.weight = nn.Parameter(torch.empty(ensemble_size, in_features, out_features))
self.bias = nn.Parameter(torch.empty(ensemble_size, 1, out_features))
self.reset_parameters()
def reset_parameters(self) -> None:
scale_factor = sqrt(5)
# default pytorch init
for layer in range(self.ensemble_size):
nn.init.kaiming_normal_(self.weight[layer], a=scale_factor)
fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight[0])
bound = 1 / sqrt(fan_in) if fan_in > 0 else 0
nn.init.uniform_(self.bias, -bound, bound)
def forward(self, x: torch.Tensor) -> torch.Tensor:
'''
x: [ensemble_size, batch_size, input_size]
weight: [ensemble_size, input_size, out_size]
bias: [ensemble_size, batch_size, out_size]
'''
return x @ self.weight + self.bias
class EnsembledCritic(nn.Module):
def __init__(self,
state_dim: int,
action_dim: int,
hiddem_dim: int = 256,
num_critics: int = 2) -> None:
super().__init__()
self.critic = nn.Sequential(
EnsembleLinear(state_dim + action_dim, hiddem_dim, num_critics),
nn.ReLU(),
EnsembleLinear(hiddem_dim, hiddem_dim, num_critics),
nn.ReLU(),
EnsembleLinear(hiddem_dim, hiddem_dim, num_critics),
nn.ReLU(),
EnsembleLinear(hiddem_dim, 1, num_critics)
)
self.reset_parameters()
self.num_critics = num_critics
def reset_parameters(self):
for layer in self.critic[::2]:
nn.init.constant_(layer.bias, 0.1)
nn.init.uniform_(self.critic[-1].weight, -3e-3, 3e-3)
nn.init.uniform_(self.critic[-1].bias, -3e-3, 3e-3)
def forward(self, state: torch.Tensor, action: torch.Tensor) -> torch.Tensor:
# [batch_size, state_dim + action_dim]
concat = torch.cat([state, action], dim=-1)
concat = concat.unsqueeze(0).repeat_interleave(self.num_critics, dim=0)
# [num_critics, batch_size]
q_values = self.critic(concat).squeeze(-1)
return q_values