-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.py
144 lines (125 loc) · 6.01 KB
/
main.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
from configparser import ConfigParser
from argparse import ArgumentParser
import torch
import gym
import numpy as np
import os
from agents.ppo import PPO
from agents.sac import SAC
from agents.ddpg import DDPG
from utils.utils import make_transition, Dict, RunningMeanStd
os.makedirs('./model_weights', exist_ok=True)
parser = ArgumentParser('parameters')
parser.add_argument("--env_name", type=str, default = 'Hopper-v2', help = "'Ant-v2','HalfCheetah-v2','Hopper-v2','Humanoid-v2','HumanoidStandup-v2',\
'InvertedDoublePendulum-v2', 'InvertedPendulum-v2' (default : Hopper-v2)")
parser.add_argument("--algo", type=str, default = 'ppo', help = 'algorithm to adjust (default : ppo)')
parser.add_argument('--train', type=bool, default=True, help="(default: True)")
parser.add_argument('--render', type=bool, default=False, help="(default: False)")
parser.add_argument('--epochs', type=int, default=1000, help='number of epochs, (default: 1000)')
parser.add_argument('--tensorboard', type=bool, default=False, help='use_tensorboard, (default: False)')
parser.add_argument("--load", type=str, default = 'no', help = 'load network name in ./model_weights')
parser.add_argument("--save_interval", type=int, default = 100, help = 'save interval(default: 100)')
parser.add_argument("--print_interval", type=int, default = 1, help = 'print interval(default : 20)')
parser.add_argument("--use_cuda", type=bool, default = True, help = 'cuda usage(default : True)')
parser.add_argument("--reward_scaling", type=float, default = 0.1, help = 'reward scaling(default : 0.1)')
args = parser.parse_args()
parser = ConfigParser()
parser.read('config.ini')
agent_args = Dict(parser,args.algo)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
if args.use_cuda == False:
device = 'cpu'
if args.tensorboard:
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter()
else:
writer = None
env = gym.make(args.env_name)
action_dim = env.action_space.shape[0]
state_dim = env.observation_space.shape[0]
state_rms = RunningMeanStd(state_dim)
if args.algo == 'ppo' :
agent = PPO(writer, device, state_dim, action_dim, agent_args)
elif args.algo == 'sac' :
agent = SAC(writer, device, state_dim, action_dim, agent_args)
elif args.algo == 'ddpg' :
from utils.noise import OUNoise
noise = OUNoise(action_dim,0)
agent = DDPG(writer, device, state_dim, action_dim, agent_args, noise)
if (torch.cuda.is_available()) and (args.use_cuda):
agent = agent.cuda()
if args.load != 'no':
agent.load_state_dict(torch.load("./model_weights/"+args.load))
score_lst = []
state_lst = []
if agent_args.on_policy == True:
score = 0.0
state_ = (env.reset())
state = np.clip((state_ - state_rms.mean) / (state_rms.var ** 0.5 + 1e-8), -5, 5)
for n_epi in range(args.epochs):
for t in range(agent_args.traj_length):
if args.render:
env.render()
state_lst.append(state_)
mu,sigma = agent.get_action(torch.from_numpy(state).float().to(device))
dist = torch.distributions.Normal(mu,sigma[0])
action = dist.sample()
log_prob = dist.log_prob(action).sum(-1,keepdim = True)
next_state_, reward, done, info = env.step(action.cpu().numpy())
next_state = np.clip((next_state_ - state_rms.mean) / (state_rms.var ** 0.5 + 1e-8), -5, 5)
transition = make_transition(state,\
action.cpu().numpy(),\
np.array([reward*args.reward_scaling]),\
next_state,\
np.array([done]),\
log_prob.detach().cpu().numpy()\
)
agent.put_data(transition)
score += reward
if done:
state_ = (env.reset())
state = np.clip((state_ - state_rms.mean) / (state_rms.var ** 0.5 + 1e-8), -5, 5)
score_lst.append(score)
if args.tensorboard:
writer.add_scalar("score/score", score, n_epi)
score = 0
else:
state = next_state
state_ = next_state_
agent.train_net(n_epi)
state_rms.update(np.vstack(state_lst))
if n_epi%args.print_interval==0 and n_epi!=0:
print("# of episode :{}, avg score : {:.1f}".format(n_epi, sum(score_lst)/len(score_lst)))
score_lst = []
if n_epi%args.save_interval==0 and n_epi!=0:
torch.save(agent.state_dict(),'./model_weights/agent_'+str(n_epi))
else : # off policy
for n_epi in range(args.epochs):
score = 0.0
state = env.reset()
done = False
while not done:
if args.render:
env.render()
action, _ = agent.get_action(torch.from_numpy(state).float().to(device))
action = action.cpu().detach().numpy()
next_state, reward, done, info = env.step(action)
transition = make_transition(state,\
action,\
np.array([reward*args.reward_scaling]),\
next_state,\
np.array([done])\
)
agent.put_data(transition)
state = next_state
score += reward
if agent.data.data_idx > agent_args.learn_start_size:
agent.train_net(agent_args.batch_size, n_epi)
score_lst.append(score)
if args.tensorboard:
writer.add_scalar("score/score", score, n_epi)
if n_epi%args.print_interval==0 and n_epi!=0:
print("# of episode :{}, avg score : {:.1f}".format(n_epi, sum(score_lst)/len(score_lst)))
score_lst = []
if n_epi%args.save_interval==0 and n_epi!=0:
torch.save(agent.state_dict(),'./model_weights/agent_'+str(n_epi))