forked from kharyal/pybullet-driving-env
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathagent.py
202 lines (161 loc) · 5.8 KB
/
agent.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
from typing import *
import torch
from dataclasses import dataclass
from torch.distributions.normal import Normal
from config import Config
import numpy as np
class PolicyNetwork(torch.nn.Module):
"""Gaussian policy network"""
def __init__(
self, num_input: int, num_output: int, num_hidden: int
) -> None:
super().__init__()
self.input = torch.nn.Linear(num_input, num_hidden)
self.fully_connected = torch.nn.Linear(num_hidden, num_hidden)
self.mean = torch.nn.Linear(num_hidden, num_output)
self.log_std = torch.nn.Parameter(torch.zeros(1, num_output))
def forward(
self, x: torch.Tensor
) -> Tuple[torch.distributions.normal.Normal, torch.Tensor]:
# Input layer
x = self.input(x)
x = torch.tanh(x)
# Hidden layer
x = self.fully_connected(x)
x = torch.tanh(x)
# Output layer
mean = self.mean(x)
std = self.log_std.exp()
dist = torch.distributions.normal.Normal(mean, std)
return dist, mean
class ValueNetwork(torch.nn.Module):
"""Value network that quantifies the quality of an action given a state."""
def __init__(self, num_input: int, num_hidden: int):
super().__init__()
self.input = torch.nn.Linear(num_input, num_hidden)
self.fully_connected = torch.nn.Linear(num_hidden, num_hidden)
self.output = torch.nn.Linear(num_hidden, 1)
def forward(self, x: torch.Tensor):
# Input layer
x = self.input(x)
x = torch.tanh(x)
# Hidden layer
x = self.fully_connected(x)
x = torch.tanh(x)
# Output layer
value = self.output(x)
return value
@dataclass
class NormalizationParams:
"""Normalization paramters for state and rewards"""
mean_state: torch.Tensor
var_state: torch.Tensor
mean_reward: torch.Tensor
var_reward: torch.Tensor
def initialize_weight(param) -> None:
"""Initialization of the weight's value of a network"""
if isinstance(param, torch.nn.Linear):
torch.nn.init.orthogonal_(param.weight.data)
torch.nn.init.constant_(param.bias.data, 0)
class Normalization:
"""Normalize the states and rewards on the fly"""
def __init__(
self,
dtype: torch.FloatTensor = torch.float,
epsilon: float = 1e-4,
nums: int = 1,
):
self.mean = torch.zeros(1, nums, dtype=dtype)
self.var = torch.ones(1, nums, dtype=dtype)
self.count = epsilon
def update(self, x: torch.Tensor):
batch_mean = torch.mean(x, axis=0)
batch_var = torch.var(x, axis=0)
batch_count = x.size(dim=0)
self.update_mean_var(batch_mean, batch_var, batch_count)
def update_mean_var(
self,
batch_mean: torch.Tensor,
batch_var: torch.Tensor,
batch_count: int,
):
self.mean, self.var, self.count = self.update_mean_var_count(
self.mean, self.var, self.count, batch_mean, batch_var, batch_count
)
@staticmethod
def update_mean_var_count(
mean: torch.Tensor,
var: torch.Tensor,
count: int,
batch_mean: torch.Tensor,
batch_var: torch.Tensor,
batch_count: int,
) -> Tuple[torch.Tensor, int]:
delta = batch_mean - mean
tot_count = count + batch_count
new_mean = mean + delta * batch_count / tot_count
ma = var * count
mb = batch_var * batch_count
m2 = ma + mb + (delta**0.5) * count * batch_count / tot_count
new_var = m2 / tot_count
new_count = tot_count
return new_mean, new_var, new_count
class Agent:
"""PPO agent"""
def __init__(
self,
num_states: int,
num_actions: int,
config: Config,
) -> None:
self.num_states = num_states
self.num_actions = num_actions
self.config = config
self.policy_network = PolicyNetwork(
num_input=self.num_states,
num_hidden=self.config.num_hiddens,
num_output=self.num_actions,
)
self.value_network = ValueNetwork(
num_input=num_states,
num_hidden=self.config.num_hiddens,
)
# # Intialize networks's parameters
self.policy_network.apply(initialize_weight)
self.value_network.apply(initialize_weight)
# Get optimizer for two models
self.policy_optimizer = torch.optim.Adam(
self.policy_network.parameters(),
lr=self.config.learning_rate,
)
self.value_optimizer = torch.optim.Adam(
self.value_network.parameters(),
lr=self.config.learning_rate,
)
self.policy_scheduler = torch.optim.lr_scheduler.ExponentialLR(
self.policy_optimizer, gamma=self.config.decay_coef
)
self.value_scheduler = torch.optim.lr_scheduler.ExponentialLR(
self.value_optimizer, gamma=self.config.decay_coef
)
def select_action(self, state: torch.Tensor) -> tuple[Normal, torch.Tensor]:
with torch.no_grad():
dist, mu = self.policy_network(state)
return dist, mu
def compute_value(self, state: torch.Tensor) -> np.ndarray:
with torch.no_grad():
value = self.value_network(state)
return value.detach().cpu().numpy()
def optimize(
self, policy_loss: torch.Tensor, value_loss: torch.Tensor
) -> None:
# Policy net
self.policy_optimizer.zero_grad()
policy_loss.backward()
torch.nn.utils.clip_grad_norm_(self.policy_network.parameters(), 0.5)
self.policy_optimizer.step()
# Value net
self.value_optimizer.zero_grad()
value_loss.backward()
torch.nn.utils.clip_grad_norm_(self.value_network.parameters(), 0.5)
self.value_optimizer.step()