forked from chris-chris/pysc2-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_mineral_shards.py
302 lines (242 loc) · 9.23 KB
/
train_mineral_shards.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
import sys
import os
from absl import flags
from baselines import deepq
from pysc2.env import sc2_env
from pysc2.lib import actions
import os
import deepq_mineral_shards
import datetime
from common.vec_env.subproc_vec_env import SubprocVecEnv
from a2c.policies import CnnPolicy
from a2c import a2c
from baselines.logger import Logger, TensorBoardOutputFormat, HumanOutputFormat
import random
import deepq_mineral_4way
import threading
import time
_MOVE_SCREEN = actions.FUNCTIONS.Move_screen.id
_SELECT_ARMY = actions.FUNCTIONS.select_army.id
_SELECT_ALL = [0]
_NOT_QUEUED = [0]
step_mul = 8
FLAGS = flags.FLAGS
flags.DEFINE_string("map", "CollectMineralShards",
"Name of a map to use to play.")
start_time = datetime.datetime.now().strftime("%Y%m%d%H%M")
flags.DEFINE_string("log", "tensorboard", "logging type(stdout, tensorboard)")
flags.DEFINE_string("algorithm", "a2c", "RL algorithm to use.")
flags.DEFINE_integer("timesteps", 2000000, "Steps to train")
flags.DEFINE_float("exploration_fraction", 0.5, "Exploration Fraction")
flags.DEFINE_boolean("prioritized", True, "prioritized_replay")
flags.DEFINE_boolean("dueling", True, "dueling")
flags.DEFINE_float("lr", 0.0005, "Learning rate")
flags.DEFINE_integer("num_agents", 4, "number of RL agents for A2C")
flags.DEFINE_integer("num_scripts", 0, "number of script agents for A2C")
flags.DEFINE_integer("nsteps", 20, "number of batch steps for A2C")
PROJ_DIR = os.path.dirname(os.path.abspath(__file__))
max_mean_reward = 0
last_filename = ""
start_time = datetime.datetime.now().strftime("%m%d%H%M")
def main():
FLAGS(sys.argv)
print("algorithm : %s" % FLAGS.algorithm)
print("timesteps : %s" % FLAGS.timesteps)
print("exploration_fraction : %s" % FLAGS.exploration_fraction)
print("prioritized : %s" % FLAGS.prioritized)
print("dueling : %s" % FLAGS.dueling)
print("num_agents : %s" % FLAGS.num_agents)
print("lr : %s" % FLAGS.lr)
if (FLAGS.lr == 0):
FLAGS.lr = random.uniform(0.00001, 0.001)
print("random lr : %s" % FLAGS.lr)
lr_round = round(FLAGS.lr, 8)
logdir = "tensorboard"
if (FLAGS.algorithm == "deepq-4way"):
logdir = "tensorboard/mineral/%s/%s_%s_prio%s_duel%s_lr%s/%s" % (
FLAGS.algorithm, FLAGS.timesteps, FLAGS.exploration_fraction,
FLAGS.prioritized, FLAGS.dueling, lr_round, start_time)
elif (FLAGS.algorithm == "deepq"):
logdir = "tensorboard/mineral/%s/%s_%s_prio%s_duel%s_lr%s/%s" % (
FLAGS.algorithm, FLAGS.timesteps, FLAGS.exploration_fraction,
FLAGS.prioritized, FLAGS.dueling, lr_round, start_time)
elif (FLAGS.algorithm == "a2c"):
logdir = "tensorboard/mineral/%s/%s_n%s_s%s_nsteps%s/lr%s/%s" % (
FLAGS.algorithm, FLAGS.timesteps,
FLAGS.num_agents + FLAGS.num_scripts, FLAGS.num_scripts,
FLAGS.nsteps, lr_round, start_time)
if (FLAGS.log == "tensorboard"):
Logger.DEFAULT \
= Logger.CURRENT \
= Logger(dir=None,
output_formats=[TensorBoardOutputFormat(logdir)])
elif (FLAGS.log == "stdout"):
Logger.DEFAULT \
= Logger.CURRENT \
= Logger(dir=None,
output_formats=[HumanOutputFormat(sys.stdout)])
if (FLAGS.algorithm == "deepq"):
with sc2_env.SC2Env(
map_name="CollectMineralShards",
step_mul=step_mul,
visualize=True,
screen_size_px=(16, 16),
minimap_size_px=(16, 16)) as env:
model = deepq.models.cnn_to_mlp(
convs=[(16, 8, 4), (32, 4, 2)], hiddens=[256], dueling=True)
act = deepq_mineral_shards.learn(
env,
q_func=model,
num_actions=16,
lr=FLAGS.lr,
max_timesteps=FLAGS.timesteps,
buffer_size=10000,
exploration_fraction=FLAGS.exploration_fraction,
exploration_final_eps=0.01,
train_freq=4,
learning_starts=10000,
target_network_update_freq=1000,
gamma=0.99,
prioritized_replay=True,
callback=deepq_callback)
act.save("mineral_shards.pkl")
elif (FLAGS.algorithm == "deepq-4way"):
with sc2_env.SC2Env(
map_name="CollectMineralShards",
step_mul=step_mul,
screen_size_px=(32, 32),
minimap_size_px=(32, 32),
visualize=True) as env:
model = deepq.models.cnn_to_mlp(
convs=[(16, 8, 4), (32, 4, 2)], hiddens=[256], dueling=True)
act = deepq_mineral_4way.learn(
env,
q_func=model,
num_actions=4,
lr=FLAGS.lr,
max_timesteps=FLAGS.timesteps,
buffer_size=10000,
exploration_fraction=FLAGS.exploration_fraction,
exploration_final_eps=0.01,
train_freq=4,
learning_starts=10000,
target_network_update_freq=1000,
gamma=0.99,
prioritized_replay=True,
callback=deepq_4way_callback)
act.save("mineral_shards.pkl")
elif (FLAGS.algorithm == "a2c"):
num_timesteps = int(40e6)
num_timesteps //= 4
seed = 0
env = SubprocVecEnv(FLAGS.num_agents + FLAGS.num_scripts, FLAGS.num_scripts, FLAGS.map)
policy_fn = CnnPolicy
a2c.learn(
policy_fn,
env,
seed,
total_timesteps=num_timesteps,
nprocs=FLAGS.num_agents + FLAGS.num_scripts,
nscripts=FLAGS.num_scripts,
ent_coef=0.5,
nsteps=FLAGS.nsteps,
max_grad_norm=0.01,
callback=a2c_callback)
from pysc2.env import environment
import numpy as np
def deepq_callback(locals, globals):
#pprint.pprint(locals)
global max_mean_reward, last_filename
if ('done' in locals and locals['done'] == True):
if ('mean_100ep_reward' in locals and locals['num_episodes'] >= 10
and locals['mean_100ep_reward'] > max_mean_reward):
print("mean_100ep_reward : %s max_mean_reward : %s" %
(locals['mean_100ep_reward'], max_mean_reward))
if (not os.path.exists(os.path.join(PROJ_DIR, 'models/deepq/'))):
try:
os.mkdir(os.path.join(PROJ_DIR, 'models/'))
except Exception as e:
print(str(e))
try:
os.mkdir(os.path.join(PROJ_DIR, 'models/deepq/'))
except Exception as e:
print(str(e))
if (last_filename != ""):
os.remove(last_filename)
print("delete last model file : %s" % last_filename)
max_mean_reward = locals['mean_100ep_reward']
act_x = deepq_mineral_shards.ActWrapper(locals['act_x'])
act_y = deepq_mineral_shards.ActWrapper(locals['act_y'])
filename = os.path.join(
PROJ_DIR,
'models/deepq/mineral_x_%s.pkl' % locals['mean_100ep_reward'])
act_x.save(filename)
filename = os.path.join(
PROJ_DIR,
'models/deepq/mineral_y_%s.pkl' % locals['mean_100ep_reward'])
act_y.save(filename)
print("save best mean_100ep_reward model to %s" % filename)
last_filename = filename
def deepq_4way_callback(locals, globals):
#pprint.pprint(locals)
global max_mean_reward, last_filename
if ('done' in locals and locals['done'] == True):
if ('mean_100ep_reward' in locals and locals['num_episodes'] >= 10
and locals['mean_100ep_reward'] > max_mean_reward):
print("mean_100ep_reward : %s max_mean_reward : %s" %
(locals['mean_100ep_reward'], max_mean_reward))
if (not os.path.exists(
os.path.join(PROJ_DIR, 'models/deepq-4way/'))):
try:
os.mkdir(os.path.join(PROJ_DIR, 'models/'))
except Exception as e:
print(str(e))
try:
os.mkdir(os.path.join(PROJ_DIR, 'models/deepq-4way/'))
except Exception as e:
print(str(e))
if (last_filename != ""):
os.remove(last_filename)
print("delete last model file : %s" % last_filename)
max_mean_reward = locals['mean_100ep_reward']
act = deepq_mineral_4way.ActWrapper(locals['act'])
#act_y = deepq_mineral_shards.ActWrapper(locals['act_y'])
filename = os.path.join(PROJ_DIR,
'models/deepq-4way/mineral_%s.pkl' %
locals['mean_100ep_reward'])
act.save(filename)
# filename = os.path.join(
# PROJ_DIR,
# 'models/deepq/mineral_y_%s.pkl' % locals['mean_100ep_reward'])
# act_y.save(filename)
print("save best mean_100ep_reward model to %s" % filename)
last_filename = filename
def a2c_callback(locals, globals):
global max_mean_reward, last_filename
#pprint.pprint(locals)
if ('mean_100ep_reward' in locals and locals['num_episodes'] >= 10
and locals['mean_100ep_reward'] > max_mean_reward):
print("mean_100ep_reward : %s max_mean_reward : %s" %
(locals['mean_100ep_reward'], max_mean_reward))
if (not os.path.exists(os.path.join(PROJ_DIR, 'models/a2c/'))):
try:
os.mkdir(os.path.join(PROJ_DIR, 'models/'))
except Exception as e:
print(str(e))
try:
os.mkdir(os.path.join(PROJ_DIR, 'models/a2c/'))
except Exception as e:
print(str(e))
if (last_filename != ""):
os.remove(last_filename)
print("delete last model file : %s" % last_filename)
max_mean_reward = locals['mean_100ep_reward']
model = locals['model']
filename = os.path.join(
PROJ_DIR,
'models/a2c/mineral_%s.pkl' % locals['mean_100ep_reward'])
model.save(filename)
print("save best mean_100ep_reward model to %s" % filename)
last_filename = filename
if __name__ == '__main__':
main()