首页 > 解决方案 > 使用 TensorFlow2 的分布式学习不起作用

问题描述

我试图让分布式 TF 在 VS-Code 中使用 Tensorflow 版本 2.0.0a(CPU 版本)。

我正在使用 Windows 和 Linux 系统(两台不同的计算机),两者都单独运行良好。

对于分布式 TF,我遵循了 https://www.tensorflow.org/alpha/guide/distribute_strategy上的教程。

我已经尝试了不同的端口并关闭了防火墙。我还尝试将主系统从 Windows 切换到 Linux,但现在我认为这可能是代码问题,或者可能是标记为实验性的 TF 版本。

from __future__ import absolute_import, division, print_function, unicode_literals

import tensorflow_datasets as tfds    
import tensorflow as tf    
import json    
import os

BUFFER_SIZE = 10000    
BATCH_SIZE = 64

def scale(image, label):

   image = tf.cast(image, tf.float32)
   image /= 255
   return image, label


datasets, info = tfds.load(name='mnist', with_info=True, as_supervised=True)

train_datasets_unbatched = datasets['train'].map(scale).shuffle(BUFFER_SIZE)

train_datasets = train_datasets_unbatched.batch(BATCH_SIZE)

def build_and_compile_cnn_model():

  model = tf.keras.Sequential([    
      tf.keras.layers.Conv2D(32, 3, activation='relu', input_shape=(28, 28, 1)),    
      tf.keras.layers.MaxPooling2D(),    
      tf.keras.layers.Flatten(),    
      tf.keras.layers.Dense(64, activation='relu'),    
      tf.keras.layers.Dense(10, activation='softmax')    
  ])

  model.compile(    
      loss=tf.keras.losses.sparse_categorical_crossentropy,    
      optimizer=tf.keras.optimizers.SGD(learning_rate=0.001),    
      metrics=['accuracy'])

  return model


#multiworker conf:

os.environ['TF_CONFIG'] = json.dumps({    
    'cluster': {    
        'worker': ["192.168.0.12:2468", "192.168.0.13:1357"]    
    },    
    'task': {'type': 'worker', 'index': 0}    
})

strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
NUM_WORKERS = 2

GLOBAL_BATCH_SIZE = 64 * NUM_WORKERS

#--------------------------------------------------------------------

#In the following line the error occurs

train_datasets = train_datasets_unbatched.batch(GLOBAL_BATCH_SIZE)

#--------------------------------------------------------------------


with strategy.scope():    
    multi_worker_model = build_and_compile_cnn_model()  
    multi_worker_model.fit(x=train_datasets, epochs=3)

我希望工人开始学习过程,但我得到了错误:

“F tensorflow/core/framework/device_base.cc:33] 设备未实现 name()”

标签: tensorflowpython-3.6distributed-tensorflow

解决方案


据我所知,每个工人都应该有一个唯一的任务索引,例如:

在第一台机器上你应该有:

os.environ['TF_CONFIG'] = json.dumps({    
    'cluster': {    
        'worker': ["192.168.0.12:2468", "192.168.0.13:1357"]    
    },    
    'task': {'type': 'worker', 'index': 0}    
})

第二个:

os.environ['TF_CONFIG'] = json.dumps({    
    'cluster': {    
        'worker': ["192.168.0.12:2468", "192.168.0.13:1357"]    
    },    
    'task': {'type': 'worker', 'index': 1}    
})

推荐阅读