8000 minigo/dual_net.py at mlperf.0.6 · Az-mark/minigo · GitHub
[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
671 lines (547 loc) · 25.2 KB

dual_net.py

File metadata and controls

671 lines (547 loc) · 25.2 KB
def _get_tpu_estimator():
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=None, project=None)
tpu_grpc_url = tpu_cluster_resolver.get_master()
run_config = tpu_config.RunConfig(
master=tpu_grpc_url,
evaluation_master=tpu_grpc_url,
model_dir=FLAGS.work_dir,
save_checkpoints_steps=max(1000, FLAGS.iterations_per_loop),
save_summary_steps=FLAGS.summary_steps,
keep_checkpoint_max=FLAGS.keep_checkpoint_max,
session_config=tf.ConfigProto(
allow_soft_placement=True, log_device_placement=True),
tpu_config=tpu_config.TPUConfig(
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=tpu_config.InputPipelineConfig.PER_HOST_V2))
return tpu_estimator.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size * FLAGS.num_tpu_cores,
eval_batch_size=FLAGS.train_batch_size * FLAGS.num_tpu_cores,
params=FLAGS.flag_values_dict())
def bootstrap():
"""Initialize a tf.Estimator run with random initial weights."""
# a bit hacky - forge an initial checkpoint with the name that subsequent
# Estimator runs will expect to find.
#
# Estimator will do this automatically when you call train(), but calling
# train() requires data, and I didn't feel like creating training data in
# order to run the full train pipeline for 1 step.
maybe_set_seed()
initial_checkpoint_name = 'model.ckpt-1'
save_file = os.path.join(FLAGS.work_dir, initial_checkpoint_name)
sess = tf.Session(graph=tf.Graph())
with sess.graph.as_default():
features, labels = get_inference_input()
model_fn(features, labels, tf.estimator.ModeKeys.PREDICT,
params=FLAGS.flag_values_dict())
sess.run(tf.global_variables_initializer())
tf.train.Saver().save(sess, save_file)
def export_model(model_path):
"""Take the latest checkpoint and copy it to model_path.
Assumes that all relevant model files are prefixed by the same name.
(For example, foo.index, foo.meta and foo.data-00000-of-00001).
Args:
model_path: The path (can be a gs:// path) to export model
"""
estimator = tf.estimator.Estimator(model_fn, model_dir=FLAGS.work_dir,
params=FLAGS.flag_values_dict())
latest_checkpoint = estimator.latest_checkpoint()
all_checkpoint_files = tf.gfile.Glob(latest_checkpoint + '*')
for filename in all_checkpoint_files:
suffix = filename.partition(latest_checkpoint)[2]
destination_path = model_path + suffix
print("Copying {} to {}".format(filename, destination_path))
tf.gfile.Copy(filename, destination_path)
def freeze_graph(model_path):
n = DualNetwork(model_path)
out_graph = tf.graph_util.convert_variables_to_constants(
n.sess, n.sess.graph.as_graph_def(), ["policy_output", "value_output"])
with tf.gfile.GFile(model_path + '.pb', 'wb') as f:
f.write(out_graph.SerializeToString())
def freeze_graph_tpu(model_path):
"""Custom freeze_graph implementation for Cloud TPU."""
assert model_path
assert FLAGS.tpu_name
if FLAGS.tpu_name.startswith('grpc://'):
tpu_grpc_url = FLAGS.tpu_name
else:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=None, project=None)
tpu_grpc_url = tpu_cluster_resolver.get_master()
sess = tf.Session(tpu_grpc_url)
output_names = []
with sess.graph.as_default():
# Replicate the inference function for each TPU core.
replicated_features = []
for i in range(FLAGS.num_tpu_cores):
features = tf.placeholder(
tf.float32, [None, go.N, go.N,
features_lib.NEW_FEATURES_PLANES],
name='pos_tensor_%d' % i)
replicated_features.append((features,))
outputs = tf.contrib.tpu.replicate(
tpu_model_inference_fn, replicated_features)
# The replicate op assigns names like output_0_shard_0 to the output
# names. Give them human readable names.
for i, (policy_output, value_output, _) in enumerate(outputs):
policy_name = 'policy_output_%d' % i
value_name = 'value_output_%d' % i
output_names.extend([policy_name, value_name])
tf.identity(policy_output, policy_name)
tf.identity(value_output, value_name)
tf.train.Saver().restore(sess, model_path)
# Freeze the graph.
model_def = tf.graph_util.convert_variables_to_constants(
sess, sess.graph.as_graph_def(), output_names)
with tf.gfile.GFile(model_path + '.pb', 'wb') as f:
f.write(model_def.SerializeToString())
0