【发布时间】:2018-04-24 17:10:20
【问题描述】:
在 TF 1.8 即将发布的版本中,tf.contrib.learn.* 将被弃用。
tf.contrib.learn.Experiment 类建议改用 tf.estimator.train_and_evaluate,因此我正在尝试将我的代码移植到该框架。
我想做的是在两台机器的 GPU 上设置分布式训练,再加上第三个仅 CPU 的进程,该进程对小型验证集进行连续评估。
按照the documentation of train_and_evaluate 和Distributed Tensorflow 指南中的示例,我设法设置了所需架构的训练部分,但我找不到设置估算器的方法。
到目前为止,我看到的内容如下:
def input_fn(mode, num_classes, batch_size):
# [...] build input pipeline
return {'input': images}, labels
def model_fn(features, labels, num_classes, mode):
# [...] build model
return tf.estimator.EstimatorSpec(
mode=mode,
predictions=predictions,
loss=total_loss,
train_op=train_op,
eval_metric_ops=metrics,
export_outputs=export_outputs)
def distributed_main_v2(unused_argv):
"""Expects `unused_argv` to be a list ['<task_type>', '<task_id>']"""
import json
# Set up environment variables according to the parameters passed to the process
TF_CONFIG = {
'cluster': {
"ps": [
"host1:2222",
],
"chief": [
"host1:2223",
],
"worker": [
"host2:2224"
]
},
'environment': 'cluster',
'task': {
'type': unused_argv[1].strip(),
'index': unused_argv[2].strip() if len(unused_argv) > 2 else 0
}
}
os.environ['TF_CONFIG'] = json.dumps(TF_CONFIG)
if unused_argv[1].strip() not in ['worker', 'chief']:
os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # leave the GPU to the worker process
# create the estimator
# define warm start configuration
regex = '^(?!.*final_layer*|.*aux_logits*)'
ws_settings = tf.estimator.WarmStartSettings('checkpoint_path', regex)
gpu_opts = tf.GPUOptions(per_process_gpu_memory_fraction=0.95) # fix for cuDNN fatal memory error with tf.contrib.learn.Experiment (TODO: still necessary?)
sess_conf = tf.ConfigProto(gpu_options=gpu_opts)
run_conf = tf.estimator.RunConfig(session_config=sess_conf)
# Create the Estimator
estimator = tf.estimator.Estimator(
model_fn=lambda features, labels, mode: model_fn(features, labels, NUM_CLASSES, mode),
model_dir=model_dir,
config=run_conf,
warm_start_from=ws_settings)
# Set up input functions for training and evaluation
train_input_fn = lambda : input_fn(tf.estimator.ModeKeys.TRAIN, NUM_CLASSES, batch_size)
eval_input_fn = lambda : input_fn(tf.estimator.ModeKeys.EVAL, NUM_CLASSES, batch_size)
train_spec = tf.estimator.TrainSpec(input_fn=train_input_fn, max_steps=steps)
eval_spec = tf.estimator.EvalSpec(input_fn=eval_input_fn)
# start distributed training
tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
if __name__ == '__main__':
# set up globals and parse known arguments
distributed_main_v2(unused_argv)
此代码有效,尽管我对它的理解仍然非常有限。我得到了 PS 和工作人员所做的事情,但从 chief 的规范中,我知道这应该是“主”工作人员,它也记录摘要并保存检查点。我现在缺少的是定期评估……我很茫然。从train_and_evaluate 代码库我看到有一些“评估器”支持,但我不明白如何正确设置它。
【问题讨论】:
标签: python tensorflow