Repository navigation
Expand file tree
/
Copy pathtrain_loop.py
More file actions
257 lines (202 loc) · 8.93 KB
/
Copy pathtrain_loop.py
File metadata and controls
257 lines (202 loc) · 8.93 KB
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
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Runs a reinforcement learning loop to train a Go playing model."""
import sys
sys.path.insert(0, '.') # nopep8
import asyncio
import itertools
import logging
import os
import re
import tensorflow as tf
import time
from ml_perf.utils import *
from absl import app, flags
flags.DEFINE_integer('iterations', 100, 'Number of iterations of the RL loop.')
flags.DEFINE_string('flags_dir', None,
'Directory in which to find the flag files for each stage '
'of the RL loop. The directory must contain the following '
'files: bootstrap.flags, selfplay.flags, eval.flags, '
'train.flags.')
flags.DEFINE_integer('window_size', 5,
'Maximum number of recent selfplay rounds to train on.')
flags.DEFINE_float('train_filter', 0.3,
'Fraction of selfplay games to pass to training.')
flags.DEFINE_boolean('validate', False, 'Run validation on holdout games')
flags.DEFINE_integer('min_games_per_iteration', 4096,
'Minimum number of games to play for each training '
'iteration.')
flags.DEFINE_integer('num_read_threads', 8,
'Number of threads to read examples on. Using more '
'read threads may speed up reading the examples as '
'more can be decompressed in parallel. This flag has '
'no effect on the output data.')
flags.DEFINE_integer('num_write_threads', 8,
'Number of threads to write examples on. Each thread '
'will write a separate .tfrecord.zz file to train on. '
'Using more threads may reduce the time take to generate '
'the training chunks as more threads are used to '
'compress the data. Using too many threads however could '
'slow down training time if each shard gets much smaller '
'than around 100MB.')
flags.DEFINE_string('golden_chunk_dir', None, 'Training example directory.')
flags.DEFINE_string('holdout_dir', None, 'Holdout example directory.')
flags.DEFINE_string('model_dir', None, 'Model directory.')
flags.DEFINE_string('selfplay_dir', None, 'Selfplay example directory.')
flags.DEFINE_string('work_dir', None, 'Training checkpoint directory.')
flags.DEFINE_string('tpu_name', None, 'Name of the TPU to train on.')
FLAGS = flags.FLAGS
# Training loop state.
# TODO(tommadams): make the trainer a proper class and get rid of this.
class State:
def __init__(self):
self.start_time = time.time()
self.iter_num = 0
def _model_name(self, it):
return '%06d' % it
@property
def selfplay_model_name(self):
return self._model_name(self.iter_num - 1)
@property
def selfplay_model_path(self):
return '{}.pb'.format(
os.path.join(FLAGS.model_dir, self.selfplay_model_name))
@property
def train_model_name(self):
return self._model_name(self.iter_num)
@property
def train_model_path(self):
return '{}.pb'.format(
os.path.join(FLAGS.model_dir, self.train_model_name))
def wait_for_training_examples(state, num_games):
"""Wait for training examples to be generated by the latest model.
Args:
state: the RL loop State instance.
num_games: number of games to wait for.
"""
model_dir = os.path.join(FLAGS.selfplay_dir, state.selfplay_model_name)
pattern = os.path.join(model_dir, '*', '*', '*.tfrecord.zz')
for i in itertools.count():
try:
paths = sorted(tf.gfile.Glob(pattern))
except tf.errors.OpError:
paths = []
if len(paths) >= num_games:
break
if i % 30 == 0:
logging.info('Waiting for %d games in %s (found %d)',
num_games, model_dir, len(paths))
time.sleep(1)
async def sample_training_examples(state):
"""Sample training examples from recent selfplay games.
Args:
state: the RL loop State instance.
Returns:
A (num_examples, record_paths) tuple:
- num_examples : number of examples sampled.
- record_paths : list of golden chunks up to window_size in length,
sorted by path.
"""
# Training examples are written out to the following directory hierarchy:
# selfplay_dir/device_id/model_name/timestamp/
# Read examples from the most recent `window_size` models.
model_dirs = [os.path.join(FLAGS.selfplay_dir, x)
for x in tf.gfile.ListDirectory(FLAGS.selfplay_dir)]
model_dirs = sorted(model_dirs, reverse=True)[:FLAGS.window_size]
src_patterns = [os.path.join(x, '*', '*', '*.tfrecord.zz')
for x in model_dirs]
dst_path = os.path.join(FLAGS.golden_chunk_dir,
'{}.tfrecord.zz'.format(state.train_model_name))
logging.info('Writing training chunks to %s', dst_path)
output = await checked_run(
'bazel-bin/cc/sample_records',
'--num_read_threads={}'.format(FLAGS.num_read_threads),
'--num_write_threads={}'.format(FLAGS.num_write_threads),
'--sample_frac={}'.format(FLAGS.train_filter),
'--compression=1',
'--shuffle=true',
'--dst={}'.format(dst_path),
*src_patterns)
m = re.search(r"sampled ([\d]+) records", output)
assert m
num_records = int(m.group(1))
chunk_pattern = os.path.join(
FLAGS.golden_chunk_dir,
'{}-*-of-*.tfrecord.zz'.format(state.train_model_name))
chunk_paths = sorted(tf.gfile.Glob(chunk_pattern))
assert len(chunk_paths) == 8
return (num_records, chunk_paths)
def append_timestamp(elapsed, model_name):
# Append the time elapsed from when the RL was started to when this model
# was trained. GCS files are immutable, so we have to do the append manually.
timestamps_path = os.path.join(FLAGS.model_dir, 'train_times.txt')
try:
with tf.gfile.Open(timestamps_path, 'r') as f:
timestamps = f.read()
except tf.errors.NotFoundError:
timestamps = ''
timestamps += '{:.3f} {}\n'.format(elapsed, model_name)
with tf.gfile.Open(timestamps_path, 'w') as f:
f.write(timestamps)
async def train(state):
"""Run training and write a new model to the model_dir.
Args:
state: the RL loop State instance.
"""
wait_for_training_examples(state, FLAGS.min_games_per_iteration)
num_records, record_paths = await sample_training_examples(state)
model_path = os.path.join(FLAGS.model_dir, state.train_model_name)
await checked_run(
'python3', 'train.py',
'--flagfile={}'.format(os.path.join(FLAGS.flags_dir, 'train.flags')),
'--work_dir={}'.format(FLAGS.work_dir),
'--export_path={}'.format(model_path),
'--use_tpu={}'.format('true' if FLAGS.tpu_name else 'false'),
'--tpu_name={}'.format(FLAGS.tpu_name),
'--num_examples={}'.format(num_records),
'--freeze=true',
*record_paths)
# Append the time elapsed from when the RL was started to when this model
# was trained.
elapsed = time.time() - state.start_time
append_timestamp(elapsed, state.train_model_name)
async def validate(state):
dirs = [x.path for x in os.scandir(FLAGS.holdout_dir) if x.is_dir()]
src_dirs = sorted(dirs, reverse=True)[:FLAGS.window_size]
await checked_run('python3', 'validate.py',
'--flagfile={}'.format(os.path.join(FLAGS.flags_dir,
'validate.flags')),
'--work_dir={}'.format(FLAGS.work_dir),
'--use_tpu={}'.format('true' if FLAGS.tpu_name else 'false'),
'--tpu_name={}'.format(FLAGS.tpu_name),
'--expand_validation_dirs',
*src_dirs)
def main(unused_argv):
"""Run the reinforcement learning loop."""
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('[%(asctime)s] %(message)s',
'%Y-%m-%d %H:%M:%S')
for handler in logger.handlers:
handler.setFormatter(formatter)
with logged_timer('Total time'):
try:
state = State()
while state.iter_num <= FLAGS.iterations:
state.iter_num += 1
wait(train(state))
finally:
asyncio.get_event_loop().close()
if __name__ == '__main__':
app.run(main)