我目前正在试验分布式TensorFlow。我使用了tf.estimator.Estimator
类(自定义模型函数)和tf.contrib.learn.Experiment
,并成功实现了数据并行执行。
然而,我现在想尝试模型并行执行。我找不到任何相关的示例,除了TensorFlow中模型并行性的实现。但我不确定如何使用tf.estimators
来实现这一点(例如,如何处理输入函数?)。
有谁有这方面的经验,或者能提供一个可用的示例吗?
回答:
首先,您应该停止使用tf.contrib.learn.Estimator
,转而使用tf.estimator.Estimator
,因为contrib
是一个实验性模块,那些已经升级到核心API的类(例如Estimator
)会自动被弃用。
现在,回到您的主题问题,您可以创建一个分布式模型,并通过tf.estimator.Estimator.__init__
的model_fn
参数传递它。
def my_model(features, labels, mode): net = features[X_FEATURE] with tf.device('/device:GPU:1'): for units in [10, 20, 10]: net = tf.layers.dense(net, units=units, activation=tf.nn.relu) net = tf.layers.dropout(net, rate=0.1) with tf.device('/device:GPU:2'): logits = tf.layers.dense(net, 3, activation=None) onehot_labels = tf.one_hot(labels, 3, 1, 0) loss = tf.losses.softmax_cross_entropy(onehot_labels=onehot_labels, logits=logits) optimizer = tf.train.AdagradOptimizer(learning_rate=0.1) train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step()) return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)[...]classifier = tf.estimator.Estimator(model_fn=my_model)
上面的模型定义了6层位于/device:GPU:1
,以及另外3层位于/device:GPU:2
。my_model
函数的返回值应该是一个EstimatorSpec
实例。完整的可工作示例可以在TensorFlow示例中找到。