-
Notifications
You must be signed in to change notification settings - Fork 0
/
ppo_pytorch.py
190 lines (176 loc) · 6.85 KB
/
ppo_pytorch.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
# from https://github.com/alexis-jacq/Pytorch-DPPO
import argparse
import os
import sys
import gym
from gym import wrappers
import random
import numpy as np
import torch
import torch.optim as optim
import torch.multiprocessing as mp
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from model import Model, Shared_obs_stats
class Params():
def __init__(self):
self.batch_size = 64
self.lr = 3e-4
self.gamma = 0.99
self.gae_param = 0.95
self.clip = 0.2
self.ent_coeff = 0.
self.num_epoch = 10
self.num_steps = 2048
self.time_horizon = 1000000
self.max_episode_length = 10000
self.seed = 1
#self.env_name = 'InvertedPendulum-v1'
self.env_name = 'InvertedDoublePendulum-v1'
#self.env_name = 'Reacher-v1'
#self.env_name = 'Pendulum-v0'
#self.env_name = 'Hopper-v1'
#self.env_name = 'Ant-v1'
#self.env_name = 'HalfCheetah-v1'
class ReplayMemory(object):
def __init__(self, capacity):
self.capacity = capacity
self.memory = []
def push(self, events):
for event in zip(*events):
self.memory.append(event)
if len(self.memory)>self.capacity:
del self.memory[0]
def clear(self):
self.memory = []
def sample(self, batch_size):
samples = zip(*random.sample(self.memory, batch_size))
return map(lambda x: torch.cat(x, 0), samples)
def normal(x, mu, sigma_sq):
a = (-1*(x-mu).pow(2)/(2*sigma_sq)).exp()
b = 1/(2*sigma_sq*np.pi).sqrt()
return a*b
def train(env, model, optimizer, shared_obs_stats):
memory = ReplayMemory(params.num_steps)
num_inputs = env.observation_space.shape[0]
num_outputs = env.action_space.shape[0]
state = env.reset()
state = Variable(torch.Tensor(state).unsqueeze(0))
done = True
# horizon loop
episode = -1
for t in range(params.time_horizon):
episode_length = 0
while(len(memory.memory)<params.num_steps):
states = []
actions = []
rewards = []
values = []
returns = []
advantages = []
av_reward = 0
cum_reward = 0
cum_done = 0
# n steps loops
for step in range(params.num_steps):
episode_length += 1
shared_obs_stats.observes(state)
state = shared_obs_stats.normalize(state)
states.append(state)
mu, sigma_sq, v = model(state)
eps = torch.randn(mu.size())
action = (mu + sigma_sq.sqrt()*Variable(eps))
actions.append(action)
values.append(v)
env_action = action.data.squeeze().numpy()
state, reward, done, _ = env.step(env_action)
done = (done or episode_length >= params.max_episode_length)
cum_reward += reward
reward = max(min(reward, 1), -1)
rewards.append(reward)
if done:
episode += 1
cum_done += 1
av_reward += cum_reward
cum_reward = 0
episode_length = 0
state = env.reset()
state = Variable(torch.Tensor(state).unsqueeze(0))
if done:
break
# one last step
R = torch.zeros(1, 1)
if not done:
_,_,v = model(state)
R = v.data
# compute returns and GAE(lambda) advantages:
R = Variable(R)
values.append(R)
A = Variable(torch.zeros(1, 1))
for i in reversed(range(len(rewards))):
td = rewards[i] + params.gamma*values[i+1].data[0,0] - values[i].data[0,0]
A = float(td) + params.gamma*params.gae_param*A
advantages.insert(0, A)
R = A + values[i]
returns.insert(0, R)
# store usefull info:
memory.push([states, actions, returns, advantages])
# epochs
model_old = Model(num_inputs, num_outputs)
model_old.load_state_dict(model.state_dict())
av_loss = 0
for k in range(params.num_epoch):
# cf https://github.com/openai/baselines/blob/master/baselines/pposgd/pposgd_simple.py
batch_states, batch_actions, batch_returns, batch_advantages = memory.sample(params.batch_size)
# old probas
mu_old, sigma_sq_old, v_pred_old = model_old(batch_states.detach())
probs_old = normal(batch_actions, mu_old, sigma_sq_old)
# new probas
mu, sigma_sq, v_pred = model(batch_states)
probs = normal(batch_actions, mu, sigma_sq)
# ratio
ratio = probs/(1e-15+probs_old)
# clip loss
surr1 = ratio * torch.cat([batch_advantages]*num_outputs,1) # surrogate from conservative policy iteration
surr2 = ratio.clamp(1-params.clip, 1+params.clip) * torch.cat([batch_advantages]*num_outputs,1)
loss_clip = -torch.mean(torch.min(surr1, surr2))
# value loss
vfloss1 = (v_pred - batch_returns)**2
v_pred_clipped = v_pred_old + (v_pred - v_pred_old).clamp(-params.clip, params.clip)
vfloss2 = (v_pred_clipped - batch_returns)**2
loss_value = 0.5*torch.mean(torch.max(vfloss1, vfloss2)) # also clip value loss
# entropy
loss_ent = -params.ent_coeff*torch.mean(probs*torch.log(probs+1e-5))
# total
total_loss = (loss_clip + loss_value + loss_ent)
av_loss += total_loss.data[0]/float(params.num_epoch)
# before Adam step, update old_model:
''' not sure about this '''
model_old.load_state_dict(model.state_dict())
# step
optimizer.zero_grad()
#model.zero_grad()
total_loss.backward(retain_variables=True)
optimizer.step()
# finish, print:
print('episode',episode,'av_reward',av_reward/float(cum_done),'av_loss',av_loss)
memory.clear()
def mkdir(base, name):
path = os.path.join(base, name)
if not os.path.exists(path):
os.makedirs(path)
return path
if __name__ == '__main__':
params = Params()
torch.manual_seed(params.seed)
work_dir = mkdir('exp', 'ppo')
monitor_dir = mkdir(work_dir, 'monitor')
env = gym.make(params.env_name)
#env = wrappers.Monitor(env, monitor_dir, force=True)
num_inputs = env.observation_space.shape[0]
num_outputs = env.action_space.shape[0]
model = Model(num_inputs, num_outputs)
shared_obs_stats = Shared_obs_stats(num_inputs)
optimizer = optim.Adam(model.parameters(), lr=params.lr)
train(env, model, optimizer, shared_obs_stats)