-
Notifications
You must be signed in to change notification settings - Fork 1
/
Agent.py
348 lines (275 loc) · 12 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import torch
from utils import *
import copy
from torch.distributions import Categorical
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
#Xavier weight initialization
def init_weights(m):
if isinstance(m,nn.Linear):
torch.nn.init.xavier_uniform_(m.weight,gain=torch.nn.init.calculate_gain('tanh'))
torch.nn.init.zeros_(m.bias)
class Agent(object):
def __init__(self, env, opt):
self.opt=opt
self.env=env
if opt.fromFile is not None:
self.load(opt.fromFile)
self.action_space = env.action_space
self.test=False
self.nbEvents=0
self.device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Define actor network
self.actor=nn.Sequential(
nn.Linear(env.observation_space.shape[0],128),
nn.Tanh(),
nn.Linear(128,64),
nn.Tanh(),
nn.Linear(64,self.action_space.n),
nn.Softmax(dim=-1)
)
# Define critic network
self.critic=nn.Sequential(
nn.Linear(env.observation_space.shape[0],128),
nn.Tanh(),
nn.Linear(128,64),
nn.Tanh(),
nn.Linear(64,1)
)
self.actor.apply(init_weights)
self.critic.apply(init_weights)
self.actor.to(self.device)
self.critic.to(self.device)
#Define learning rates and optimizers
self.lr_a=opt.lr_a
self.lr_c=opt.lr_c
self.optimizer_actor = torch.optim.Adam(self.actor.parameters(),self.lr_a)
self.optimizer_critic= torch.optim.Adam(self.critic.parameters(),self.lr_c)
# Define algorithm variables
self.clip=opt.clip
self.ppo=opt.PPO
self.kl=opt.KL
#Define hyperparameters
self.K=opt.K_epochs
self.discount=opt.discount # Discount factor
self.gae_lambda=opt.gae_lambda # Lambda of TD(lambda) advantage estimation
#Hyperparameters of clipped PPO
self.eps_clip=0.2
# Hyperparameters of KL-Div Algo
self.beta=1.
self.delta=0.01
#Initialize memory
self.states=[]
self.actions=[]
self.log_probs=[]
self.rewards=[]
self.dones=[]
self.new_states=[]
self.values=[]
#counters
self.actor_count=0
self.critic_count=0
def act(self, obs):
#Calculate distribution of policy
prob=self.actor(torch.FloatTensor(obs).to(self.device))
dist=Categorical(prob)
#sample action w.r.t policy
action=dist.sample()
#store values
if not self.test:
self.log_probs.append(dist.log_prob(action))
self.actions.append(action.detach())
self.states.append(torch.FloatTensor(obs).to(self.device))
self.values.append(self.critic(torch.FloatTensor(obs).to(self.device)).detach())
return action.item()
#learning algorithm of PPO with Adaptive Kullback-Leibler divergence
def learn_kl(self):
#Compute the TD(lambda) advantage estimation
last_val=self.critic(torch.FloatTensor(self.new_states[-1]).to(self.device)).item()
rewards = np.zeros_like(self.rewards)
advantage = np.zeros_like(self.rewards)
adv=0.
for t in reversed(range(len(self.rewards))):
if t==len(self.rewards)-1:
rewards[t]=self.rewards[t]+self.discount*(1-self.dones[t])*last_val
delta = self.rewards[t]+self.discount*(1-self.dones[t])*last_val - self.values[t].item()
else:
rewards[t]=self.rewards[t]+self.discount*(1-self.dones[t])*rewards[t+1]
delta=self.rewards[t]+self.discount*(1-self.dones[t])*self.values[t+1].item()-self.values[t].item()
adv=adv*self.discount*self.gae_lambda*(1-self.dones[t])+delta
advantage[t]=adv
rewards = torch.FloatTensor(rewards).to(self.device)
advantage = torch.FloatTensor(advantage).to(self.device)
#Normalize the advantage
advantage = (advantage - advantage.mean()) / (advantage.std() + 1e-10)
old_states = torch.squeeze(torch.stack(self.states, dim=0)).detach().to(self.device)
old_actions = torch.squeeze(torch.stack(self.actions, dim=0)).detach().to(self.device)
old_logprobs = torch.squeeze(torch.stack(self.log_probs, dim=0)).detach().to(self.device)
pi_old=self.actor(old_states).view((-1,self.action_space.n))
state_value=self.critic(old_states).view(-1)
for _ in range(self.K):
probs = self.actor(old_states)
dist=Categorical(probs)
log_probs=dist.log_prob(old_actions)
ratios=torch.exp(log_probs-old_logprobs.detach())
#PPO Loss
loss1=torch.mean(ratios*advantage.detach())
#KL-Divergence Loss
loss2=F.kl_div(input=probs,target=pi_old.detach(),reduction='batchmean')
#Actor update
actor_loss=- (loss1-self.beta*loss2)
self.actor_count+=1
self.actor_loss=actor_loss
self.optimizer_actor.zero_grad()
actor_loss.backward()
self.optimizer_actor.step()
#KL-Divergence update
DL=F.kl_div(input=probs.view((-1,self.action_space.n)),target=pi_old.view((-1,self.action_space.n)),reduction='batchmean')
if DL>=1.5*self.delta:
self.beta*=2
if DL<=self.delta/1.5:
self.beta*=0.5
#Critic update
loss=F.smooth_l1_loss(rewards,state_value.view(-1))
self.critic_loss=loss
self.critic_count+=1
self.optimizer_critic.zero_grad()
loss.backward()
self.optimizer_critic.step()
#Clear memory
self.states=[]
self.actions=[]
self.log_probs=[]
self.rewards=[]
self.dones=[]
self.new_states=[]
self.values=[]
#learning algorithm of PPO
def learn_ppo(self):
#Compute the TD(lambda) advantage estimation
last_val=self.critic(torch.FloatTensor(self.new_states[-1]).to(self.device)).item()
rewards = np.zeros_like(self.rewards)
advantage = np.zeros_like(self.rewards)
for t in reversed(range(len(self.rewards))):
if t==len(self.rewards)-1:
rewards[t]=self.rewards[t]+self.discount*(1-self.dones[t])*last_val
#td_error = self.rewards[t]+self.discount*(1-self.dones[t])*last_val - self.values[t].item()
else:
rewards[t]=self.rewards[t]+self.discount*(1-self.dones[t])*rewards[t+1]
#td_error=self.rewards[t]+self.discount*(1-self.dones[t])*self.values[t+1]-self.values[t]
advantage[t]=rewards[t]-self.values[t]
rewards = torch.FloatTensor(rewards).to(self.device)
advantage = torch.FloatTensor(advantage).to(self.device)
#Normalize the advantage
advantage = (advantage - advantage.mean()) / (advantage.std() + 1e-10)
old_states = torch.squeeze(torch.stack(self.states, dim=0)).detach().to(self.device)
old_actions = torch.squeeze(torch.stack(self.actions, dim=0)).detach().to(self.device)
old_logprobs = torch.squeeze(torch.stack(self.log_probs, dim=0)).detach().to(self.device)
pi_old=self.actor(old_states).view((-1,self.action_space.n))
state_value=self.critic(old_states).view(-1)
for _ in range(self.K):
probs = self.actor(old_states)
dist=Categorical(probs)
log_probs=dist.log_prob(old_actions)
ratios=torch.exp(log_probs-old_logprobs.detach())
#Use only the PPO Loss here
loss1=torch.mean(ratios*advantage.detach())
actor_loss=-loss1
#Actor update
self.actor_count+=1
self.actor_loss=actor_loss
self.optimizer_actor.zero_grad()
actor_loss.backward()
self.optimizer_actor.step()
#Critic update
loss=F.smooth_l1_loss(rewards,state_value.view(-1))
self.critic_loss=loss
self.critic_count+=1
self.optimizer_critic.zero_grad()
loss.backward()
self.optimizer_critic.step()
#Clear memory
self.states=[]
self.actions=[]
self.log_probs=[]
self.rewards=[]
self.dones=[]
self.new_states=[]
self.values=[]
#learning algorithm of PPO with clipped objective
def learn_clip(self):
#Compute TD(lambda) advantage estimation
last_val=self.critic(torch.FloatTensor(self.new_states[-1]).to(self.device)).item()
rewards = np.zeros_like(self.rewards)
advantage = np.zeros_like(self.rewards)
adv=0.
for t in reversed(range(len(self.rewards))):
if t==len(self.rewards)-1:
rewards[t]=self.rewards[t]+self.discount*(1-self.dones[t])*last_val
delta = self.rewards[t]+self.discount*(1-self.dones[t])*last_val - self.values[t].item()
else:
rewards[t]=self.rewards[t]+self.discount*(1-self.dones[t])*rewards[t+1]
delta=self.rewards[t]+self.discount*(1-self.dones[t])*self.values[t+1].item()-self.values[t].item()
adv=adv*self.discount*self.gae_lambda*(1-self.dones[t])+delta
advantage[t]=adv
rewards = torch.FloatTensor(rewards).to(self.device)
advantage = torch.FloatTensor(advantage).to(self.device)
#Normalize the advantage
advantage = (advantage - advantage.mean()) / (advantage.std() + 1e-10)
old_states = torch.squeeze(torch.stack(self.states, dim=0)).detach().to(self.device)
old_actions = torch.squeeze(torch.stack(self.actions, dim=0)).detach().to(self.device)
old_logprobs = torch.squeeze(torch.stack(self.log_probs, dim=0)).detach().to(self.device)
state_values=self.critic(old_states).view(-1)
for _ in range(self.K):
probs = self.actor(old_states)
dist=Categorical(probs)
log_probs=dist.log_prob(old_actions)
ratios=torch.exp(log_probs-old_logprobs.detach())
#PPO-Loss
loss1=ratios*advantage.detach()
#Clipped Loss
loss2=torch.clamp(ratios,min=1-self.eps_clip,max=1+self.eps_clip)*advantage.detach()
#Actor update
actor_loss= -torch.mean(torch.min(loss1,loss2))
self.actor_count+=1
self.actor_loss=actor_loss
self.optimizer_actor.zero_grad()
actor_loss.backward()
self.optimizer_actor.step()
#Critic update
loss=F.smooth_l1_loss(rewards,state_values)
self.critic_loss=loss
self.critic_count+=1
self.optimizer_critic.zero_grad()
loss.backward()
self.optimizer_critic.step()
#Clear memory
self.states=[]
self.actions=[]
self.log_probs=[]
self.rewards=[]
self.dones=[]
self.new_states=[]
self.values=[]
def learn(self):
if self.clip:
self.learn_clip()
elif self.kl:
self.learn_kl()
elif self.ppo:
self.learn_ppo()
def store(self,ob, action, new_obs, reward, done, it):
if not self.test:
if it == self.opt.maxLengthTrain:
print("undone")
done=False
self.rewards.append(reward)
self.dones.append(float(done))
self.new_states.append(new_obs)
#defines the timesteps when the agent learns
def timeToLearn(self,done):
if self.test:
return False
self.nbEvents+=1
return self.nbEvents%self.opt.freqOptim == 0