-
Notifications
You must be signed in to change notification settings - Fork 10
/
run.py
180 lines (155 loc) · 8.02 KB
/
run.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
import torch
from agent import FQF_Agent
import numpy as np
import torch.optim as optim
import random
import math
from torch.utils.tensorboard import SummaryWriter
from collections import deque, namedtuple
import time
import gym
import argparse
import wrapper
import MultiPro
def evaluate(eps, frame, eval_runs):
"""
Makes an evaluation run with the current epsilon
"""
reward_batch = []
for i in range(eval_runs):
state = eval_env.reset()
rewards = 0
while True:
action = agent.act(np.expand_dims(state, axis=0), eps, eval=True)
state, reward, done, _ = eval_env.step(action[0].item())
rewards += reward
if done:
break
reward_batch.append(rewards)
writer.add_scalar("Reward", np.mean(reward_batch), frame)
def run(frames=1000, eps_fixed=False, eps_frames=1e6, min_eps=0.01, eval_every=1000, eval_runs=5, worker=1):
"""
Params
======
"""
scores = [] # list containing scores from each episode
scores_window = deque(maxlen=100//worker) # last 100 scores
frame = 0
if eps_fixed:
eps = 0
else:
eps = 1
eps_start = 1
i_episode = 1
state = envs.reset()
score = 0
for frame in range(1, frames+1):
action = agent.act(state, eps)
next_state, reward, done, _ = envs.step(action)
for s, a, r, ns, d in zip(state, action, reward, next_state, done):
agent.step(s, a, r, ns, d, writer)
state = next_state
score += np.mean(reward)
# linear annealing to the min epsilon value until eps_frames and from there slowly decease epsilon to 0 until the end of training
if eps_fixed == False:
if frame < eps_frames:
eps = max(eps_start - (frame*(1/eps_frames)), min_eps)
else:
eps = max(min_eps - min_eps*((frame-eps_frames)/(frames-eps_frames)), 0.001)
# evaluation runs
if frame % eval_every == 0 or frame == 1:
evaluate(eps, frame*worker, eval_runs)
if done.any():
scores_window.append(score) # save most recent score
scores.append(score) # save most recent score
writer.add_scalar("Average100", np.mean(scores_window), frame)
print('\rEpisode {}\tFrame {} \tAverage100 Score: {:.2f}'.format(i_episode*worker, frame*worker, np.mean(scores_window)), end="")
if i_episode % 100 == 0:
print('\rEpisode {}\tFrame {}\tAverage100 Score: {:.2f} '.format(i_episode*worker, frame*worker, np.mean(scores_window)))
i_episode +=1
state = envs.reset()
score = 0
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-agent", type=str, choices=["fqf",
"fqf+per",
"noisy_fqf",
"noisy_fqf+per",
"dueling",
"dueling+per",
"noisy_dueling",
"noisy_dueling+per"
], default="fqf", help="Specify which type of FQF agent you want to train, default is fqf - baseline!")
parser.add_argument("-env", type=str, default="CartPole-v0", help="Name of the Environment, default = CartPole-v0")
parser.add_argument("-frames", type=int, default=30000, help="Number of frames to train, default = 30000")
parser.add_argument("-eval_every", type=int, default=1000, help="Evaluate every x frames, default = 1000")
parser.add_argument("-eval_runs", type=int, default=5, help="Number of evaluation runs, default = 5")
parser.add_argument("-seed", type=int, default=1, help="Random seed to replicate training runs, default = 1")
parser.add_argument("-munchausen", type=int, default=0, choices=[0,1], help="Use Munchausen RL loss for training if set to 1 (True), default = 0")
parser.add_argument("-bs", "--batch_size", type=int, default=32, help="Batch size for updating the DQN, default = 32")
parser.add_argument("-layer_size", type=int, default=512, help="Size of the hidden layer, default=512")
parser.add_argument("-n_step", type=int, default=1, help="Multistep IQN, default = 1")
parser.add_argument("-N", type=int, default=32, help="Number of quantiles, default = 32")
parser.add_argument("-m", "--memory_size", type=int, default=int(1e5), help="Replay memory size, default = 1e5")
parser.add_argument("-ec", "--entropy_coeff", type=float, default=0.001, help="Entropy coefficient, default = 0.001")
parser.add_argument("-lr", type=float, default=5e-4, help="Learning rate, default = 5e-4")
parser.add_argument("-g", "--gamma", type=float, default=0.99, help="Discount factor gamma, default = 0.99")
parser.add_argument("-t", "--tau", type=float, default=1e-3, help="Soft update parameter tat, default = 1e-3")
parser.add_argument("-eps_frames", type=int, default=5000, help="Linear annealed frames for Epsilon, default = 5000")
parser.add_argument("-min_eps", type=float, default = 0.025, help="Final epsilon greedy value, default = 0.025")
parser.add_argument("-w", "--worker", type=int, default=1, help="Number of parallel environments, dont choose too many since batch size increased proportional, default = 1")
parser.add_argument("-info", type=str, help="Name of the training run")
parser.add_argument("-save_model", type=int, choices=[0,1], default=0, help="Specify if the trained network shall be saved or not, default is 0 - not saved!")
args = parser.parse_args()
writer = SummaryWriter("runs/"+args.info)
torch.autograd.set_detect_anomaly(True)
env_name = args.env
seed = args.seed
BUFFER_SIZE = args.memory_size
BATCH_SIZE = args.batch_size
GAMMA = args.gamma
TAU = args.tau
LR = args.lr
n_step = args.n_step
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print("Using ", device)
np.random.seed(seed)
random.seed(seed)
torch.manual_seed(seed)
if "-ram" in args.env or args.env == "CartPole-v0" or args.env == "LunarLander-v2":
envs = MultiPro.SubprocVecEnv([lambda: gym.make(args.env) for i in range(args.worker)])
eval_env = gym.make(args.env)
else:
envs = MultiPro.SubprocVecEnv([lambda: wrapper.make_env(args.env) for i in range(args.worker)])
eval_env = wrapper.make_env(args.env)
envs.seed(seed)
eval_env.seed(seed+1)
action_size = eval_env.action_space.n
state_size = eval_env.observation_space.shape
agent = FQF_Agent(state_size=state_size,
action_size=action_size,
network=args.agent,
layer_size=args.layer_size,
n_step=n_step,
BATCH_SIZE=BATCH_SIZE,
BUFFER_SIZE=BUFFER_SIZE,
LR=LR,
TAU=TAU,
GAMMA=GAMMA,
Munchausen=args.munchausen,
N=args.N,
entropy_coeff=args.entropy_coeff,
worker=args.worker,
device=device,
seed=seed)
# set epsilon frames to 0 so no epsilon exploration
if "noisy" in args.agent:
eps_fixed = True
else:
eps_fixed = False
t0 = time.time()
run(frames = args.frames//args.worker, eps_fixed=eps_fixed, eps_frames=args.eps_frames//args.worker, min_eps=args.min_eps, eval_every=args.eval_every//args.worker, eval_runs=args.eval_runs, worker=args.worker)
t1 = time.time()
print("Training time: {}min".format(round((t1-t0)/60,2)))
if args.save_model:
torch.save(agent.qnetwork_local.state_dict(), args.info+".pth")