-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTD3.py
More file actions
168 lines (118 loc) · 7.03 KB
/
TD3.py
File metadata and controls
168 lines (118 loc) · 7.03 KB
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
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class Actor(nn.Module):
def __init__(self, state_dim, action_dim, max_action):
super(Actor, self).__init__()
self.fc1 = nn.Linear(state_dim, 256)
self.fc2 = nn.Linear(256, 256)
self.fc3 = nn.Linear(256, action_dim)
self.max_action = max_action
def forward(self, state):
a = F.relu(self.fc1(state))
a = F.relu(self.fc2(a))
a = torch.tanh(self.fc3(a)) * self.max_action
return a
class Critic(nn.Module):
def __init__(self, state_dim, action_dim):
super(Critic, self).__init__()
self.fc1 = nn.Linear(state_dim + action_dim, 256)
self.fc2 = nn.Linear(256, 256)
self.fc3 = nn.Linear(256, 1)
def forward(self, state, action):
state_action = torch.cat([state, action], 1)
q = F.relu(self.fc1(state_action))
q = F.relu(self.fc2(q))
q = self.fc3(q)
return q
class TD3:
def __init__(self, lr, state_dim, action_dim, max_action):
self.actor = Actor(state_dim, action_dim, max_action).to(device)
self.actor_target = Actor(state_dim, action_dim, max_action).to(device)
self.actor_target.load_state_dict(self.actor.state_dict())
self.actor_optimizer = optim.Adam(self.actor.parameters(), lr=lr)
self.critic_1 = Critic(state_dim, action_dim).to(device)
self.critic_1_target = Critic(state_dim, action_dim).to(device)
self.critic_1_target.load_state_dict(self.critic_1.state_dict())
self.critic_1_optimizer = optim.Adam(self.critic_1.parameters(), lr=lr)
self.critic_2 = Critic(state_dim, action_dim).to(device)
self.critic_2_target = Critic(state_dim, action_dim).to(device)
self.critic_2_target.load_state_dict(self.critic_2.state_dict())
self.critic_2_optimizer = optim.Adam(self.critic_2.parameters(), lr=lr)
self.max_action = max_action
def select_action(self, state):
state = torch.FloatTensor(state.reshape(1, -1)).to(device)
return self.actor(state).cpu().data.numpy().flatten()
def update(self, replay_buffer, n_iter, batch_size, gamma, polyak, policy_noise, noise_clip, policy_delay):
for i in range(n_iter):
# Sample a batch of transitions from replay buffer:
state, action_, reward, next_state, done = replay_buffer.sample(batch_size)
state = torch.FloatTensor(state).to(device)
action = torch.FloatTensor(action_).to(device)
reward = torch.FloatTensor(reward).reshape((batch_size, 1)).to(device)
next_state = torch.FloatTensor(next_state).to(device)
done = torch.FloatTensor(done).reshape((batch_size, 1)).to(device)
# Select next action according to target policy:
noise = torch.FloatTensor(action_).data.normal_(0, policy_noise).to(device)
noise = noise.clamp(-noise_clip, noise_clip)
next_action = (self.actor_target(next_state) + noise)
next_action = next_action.clamp(-self.max_action, self.max_action)
# Compute target Q-value:
target_Q1 = self.critic_1_target(next_state, next_action)
target_Q2 = self.critic_2_target(next_state, next_action)
target_Q = torch.min(target_Q1, target_Q2)
target_Q = reward + ((1 - done) * gamma * target_Q).detach()
# Optimize Critic 1:
current_Q1 = self.critic_1(state, action)
loss_Q1 = F.mse_loss(current_Q1, target_Q)
self.critic_1_optimizer.zero_grad()
loss_Q1.backward()
self.critic_1_optimizer.step()
# Optimize Critic 2:
current_Q2 = self.critic_2(state, action)
loss_Q2 = F.mse_loss(current_Q2, target_Q)
self.critic_2_optimizer.zero_grad()
loss_Q2.backward()
self.critic_2_optimizer.step()
# Delayed policy updates:
if i % policy_delay == 0:
# Compute actor loss:
actor_loss = -self.critic_1(state, self.actor(state)).mean()
# Optimize the actor
self.actor_optimizer.zero_grad()
actor_loss.backward()
self.actor_optimizer.step()
# Polyak averaging update:
for param, target_param in zip(self.actor.parameters(), self.actor_target.parameters()):
target_param.data.copy_((polyak * target_param.data) + ((1 - polyak) * param.data))
for param, target_param in zip(self.critic_1.parameters(), self.critic_1_target.parameters()):
target_param.data.copy_((polyak * target_param.data) + ((1 - polyak) * param.data))
for param, target_param in zip(self.critic_2.parameters(), self.critic_2_target.parameters()):
target_param.data.copy_((polyak * target_param.data) + ((1 - polyak) * param.data))
def save(self, directory, name):
torch.save(self.actor.state_dict(), '%s/%s_actor.pth' % (directory, name))
torch.save(self.actor_target.state_dict(), '%s/%s_actor_target.pth' % (directory, name))
torch.save(self.critic_1.state_dict(), '%s/%s_crtic_1.pth' % (directory, name))
torch.save(self.critic_1_target.state_dict(), '%s/%s_critic_1_target.pth' % (directory, name))
torch.save(self.critic_2.state_dict(), '%s/%s_crtic_2.pth' % (directory, name))
torch.save(self.critic_2_target.state_dict(), '%s/%s_critic_2_target.pth' % (directory, name))
def load(self, directory, name):
self.actor.load_state_dict(
torch.load('%s/%s_actor.pth' % (directory, name), map_location=lambda storage, loc: storage))
self.actor_target.load_state_dict(
torch.load('%s/%s_actor_target.pth' % (directory, name), map_location=lambda storage, loc: storage))
self.critic_1.load_state_dict(
torch.load('%s/%s_crtic_1.pth' % (directory, name), map_location=lambda storage, loc: storage))
self.critic_1_target.load_state_dict(
torch.load('%s/%s_critic_1_target.pth' % (directory, name), map_location=lambda storage, loc: storage))
self.critic_2.load_state_dict(
torch.load('%s/%s_crtic_2.pth' % (directory, name), map_location=lambda storage, loc: storage))
self.critic_2_target.load_state_dict(
torch.load('%s/%s_critic_2_target.pth' % (directory, name), map_location=lambda storage, loc: storage))
def load_actor(self, directory, name):
self.actor.load_state_dict(
torch.load('%s/%s_actor.pth' % (directory, name), map_location=lambda storage, loc: storage))
self.actor_target.load_state_dict(
torch.load('%s/%s_actor_target.pth' % (directory, name), map_location=lambda storage, loc: storage))