-
Notifications
You must be signed in to change notification settings - Fork 82
/
run_a3c.py
183 lines (148 loc) · 6 KB
/
run_a3c.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
import argparse
import copy
import multiprocessing as mp
import os
import sys
import statistics
import time
import chainer
from chainer import links as L
from chainer import functions as F
import cv2
import numpy as np
import a3c
import random_seed
import async
from prepare_output_dir import prepare_output_dir
def eval_performance(process_idx, make_env, model, phi, n_runs):
assert n_runs > 1, 'Computing stdev requires at least two runs'
scores = []
for i in range(n_runs):
model.reset_state()
env = make_env(process_idx, test=True)
obs = env.reset()
done = False
test_r = 0
while not done:
s = chainer.Variable(np.expand_dims(phi(obs), 0))
pout, _ = model.pi_and_v(s)
a = pout.action_indices[0]
obs, r, done, info = env.step(a)
test_r += r
scores.append(test_r)
print('test_{}:'.format(i), test_r)
mean = statistics.mean(scores)
median = statistics.median(scores)
stdev = statistics.stdev(scores)
return mean, median, stdev
def train_loop(process_idx, counter, make_env, max_score, args, agent, env,
start_time, outdir):
try:
total_r = 0
episode_r = 0
global_t = 0
local_t = 0
obs = env.reset()
r = 0
done = False
while True:
# Get and increment the global counter
with counter.get_lock():
counter.value += 1
global_t = counter.value
local_t += 1
if global_t > args.steps:
break
agent.optimizer.lr = (
args.steps - global_t - 1) / args.steps * args.lr
total_r += r
episode_r += r
a = agent.act(obs, r, done)
if done:
if process_idx == 0:
print('{} global_t:{} local_t:{} lr:{} r:{}'.format(
outdir, global_t, local_t, agent.optimizer.lr,
episode_r))
episode_r = 0
obs = env.reset()
r = 0
done = False
else:
obs, r, done, info = env.step(a)
if global_t % args.eval_frequency == 0:
# Evaluation
# We must use a copy of the model because test runs can change
# the hidden states of the model
test_model = copy.deepcopy(agent.model)
test_model.reset_state()
mean, median, stdev = eval_performance(
process_idx, make_env, test_model, agent.phi,
args.eval_n_runs)
with open(os.path.join(outdir, 'scores.txt'), 'a+') as f:
elapsed = time.time() - start_time
record = (global_t, elapsed, mean, median, stdev)
print('\t'.join(str(x) for x in record), file=f)
with max_score.get_lock():
if mean > max_score.value:
# Save the best model so far
print('The best score is updated {} -> {}'.format(
max_score.value, mean))
filename = os.path.join(
outdir, '{}.h5'.format(global_t))
agent.save_model(filename)
print('Saved the current best model to {}'.format(
filename))
max_score.value = mean
except KeyboardInterrupt:
if process_idx == 0:
# Save the current model before being killed
agent.save_model(os.path.join(
outdir, '{}_keyboardinterrupt.h5'.format(global_t)))
print('Saved the current model to {}'.format(
outdir), file=sys.stderr)
raise
if global_t == args.steps + 1:
# Save the final model
agent.save_model(
os.path.join(args.outdir, '{}_finish.h5'.format(args.steps)))
print('Saved the final model to {}'.format(args.outdir))
def train_loop_with_profile(process_idx, counter, make_env, max_score, args,
agent, env, start_time, outdir):
import cProfile
cmd = 'train_loop(process_idx, counter, make_env, max_score, args, ' \
'agent, env, start_time)'
cProfile.runctx(cmd, globals(), locals(),
'profile-{}.out'.format(os.getpid()))
def run_a3c(processes, make_env, model_opt, phi, t_max=1, beta=1e-2,
profile=False, steps=8 * 10 ** 7, eval_frequency=10 ** 6,
eval_n_runs=10, args={}):
# Prevent numpy from using multiple threads
os.environ['OMP_NUM_THREADS'] = '1'
outdir = prepare_output_dir(args, None)
print('Output files are saved in {}'.format(outdir))
n_actions = 20 * 20
model, opt = model_opt()
shared_params = async.share_params_as_shared_arrays(model)
shared_states = async.share_states_as_shared_arrays(opt)
max_score = mp.Value('f', np.finfo(np.float32).min)
counter = mp.Value('l', 0)
start_time = time.time()
# Write a header line first
with open(os.path.join(outdir, 'scores.txt'), 'a+') as f:
column_names = ('steps', 'elapsed', 'mean', 'median', 'stdev')
print('\t'.join(column_names), file=f)
def run_func(process_idx):
env = make_env(process_idx, test=False)
model, opt = model_opt()
async.set_shared_params(model, shared_params)
async.set_shared_states(opt, shared_states)
agent = a3c.A3C(model, opt, t_max, 0.99, beta=beta,
process_idx=process_idx, phi=phi)
if profile:
train_loop_with_profile(process_idx, counter, make_env, max_score,
args, agent, env, start_time,
outdir=outdir)
else:
train_loop(process_idx, counter, make_env, max_score,
args, agent, env, start_time, outdir=outdir)
async.run_async(processes, run_func)