我试图在具有64个CPU的CentOS 7机器上同时运行几个TensorFlow会话。我的同事报告他可以使用以下两个代码块在他的机器上使用4个内核生成并行加速:
mnist.py
import numpy as np
import input_data
from PIL import Image
import tensorflow as tf
import time
def main(randint):
print 'Set new seed:', randint
np.random.seed(randint)
tf.set_random_seed(randint)
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# Setting up the softmax architecture
x = tf.placeholder("float", [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
# Setting up the cost function
y_ = tf.placeholder("float", [None, 10])
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
# Initialization
init = tf.initialize_all_variables()
sess = tf.Session(
config=tf.ConfigProto(
inter_op_parallelism_threads=1,
intra_op_parallelism_threads=1
)
)
sess.run(init)
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})
if __name__ == "__main__":
t1 = time.time()
main(0)
t2 = time.time()
print "time spent: {0:.2f}".format(t2 - t1)
parallel.py
import multiprocessing
import numpy as np
import mnist
import time
t1 = time.time()
p1 = multiprocessing.Process(target=mnist.main,args=(np.random.randint(10000000),))
p2 = multiprocessing.Process(target=mnist.main,args=(np.random.randint(10000000),))
p3 = multiprocessing.Process(target=mnist.main,args=(np.random.randint(10000000),))
p1.start()
p2.start()
p3.start()
p1.join()
p2.join()
p3.join()
t2 = time.time()
print "time spent: {0:.2f}".format(t2 - t1)
特别是,他说他观察了
Running a single process took: 39.54 seconds
Running three processes took: 54.16 seconds
但是,当我运行代码时:
python mnist.py
==> Time spent: 5.14
python parallel.py
==> Time spent: 37.65
正如您所看到的,通过使用多处理,我得到了显着的减速,而我的同事却没有。有没有人知道为什么会发生这种情况以及可以采取哪些措施来解决它?
修改
这是一些示例输出。请注意,加载数据似乎是并行发生的,但是训练单个模型在输出中具有非常顺序的外观(并且可以通过在程序执行时查看top
中的CPU使用情况来验证)
#$ python parallel.py
Set new seed: 9672406
Extracting MNIST_data/train-images-idx3-ubyte.gz
Set new seed: 4790824
Extracting MNIST_data/train-images-idx3-ubyte.gz
Set new seed: 8011659
Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
I tensorflow/core/common_runtime/local_device.cc:25] Local device intra op parallelism threads: 1
I tensorflow/core/common_runtime/local_session.cc:45] Local session inter op parallelism threads: 1
0.9136
I tensorflow/core/common_runtime/local_device.cc:25] Local device intra op parallelism threads: 1
I tensorflow/core/common_runtime/local_session.cc:45] Local session inter op parallelism threads: 1
0.9149
I tensorflow/core/common_runtime/local_device.cc:25] Local device intra op parallelism threads: 1
I tensorflow/core/common_runtime/local_session.cc:45] Local session inter op parallelism threads: 1
0.8931
time spent: 41.36
另一个编辑
假设我们希望确认问题似乎与TensorFlow有关,而不是多处理。我将mnist.py
的内容替换为大循环,如下所示:
def main(randint):
c = 0
for i in xrange(100000000):
c += i
输出:
#$ python mnist.py
==> time spent: 5.16
#$ python parallel.py
==> time spent: 4.86
因此我认为这里的问题不在于多处理本身。
答案 0 :(得分:2)
来自OP的评论(user1936768):
我有个好消息:事实证明,至少在我的系统上,我的试用程序没有执行足够长的时间来启动其他TF实例。当我在main中放置一个运行时间较长的示例程序时,我确实看到了并发计算
答案 1 :(得分:0)
一种可能性是你的会话试图分别使用64个核心并相互踩踏
也许尝试将 NUM_CORES
设置为每个会话的较低值
sess = tf.Session(
tf.ConfigProto(inter_op_parallelism_threads=NUM_CORES,
intra_op_parallelism_threads=NUM_CORES))
答案 2 :(得分:0)
这可以通过Ray优雅地完成,Plasma shared memory object store是用于并行和分布式Python的库,可让您从单个Python脚本并行训练模型。
这具有使您可以将“类”并行化为“演员”的优势,这对于常规的Python多处理而言可能很难做到。这很重要,因为通常会初始化TensorFlow图的昂贵部分。如果创建一个actor,然后多次调用train
方法,则将摊销初始化图形的成本。
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
from PIL import Image
import ray
import tensorflow as tf
import time
@ray.remote
class TrainingActor(object):
def __init__(self, seed):
print('Set new seed:', seed)
np.random.seed(seed)
tf.set_random_seed(seed)
self.mnist = input_data.read_data_sets('MNIST_data/', one_hot=True)
# Setting up the softmax architecture.
self.x = tf.placeholder('float', [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
self.y = tf.nn.softmax(tf.matmul(self.x, W) + b)
# Setting up the cost function.
self.y_ = tf.placeholder('float', [None, 10])
cross_entropy = -tf.reduce_sum(self.y_*tf.log(self.y))
self.train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
# Initialization
self.init = tf.initialize_all_variables()
self.sess = tf.Session(
config=tf.ConfigProto(
inter_op_parallelism_threads=1,
intra_op_parallelism_threads=1
)
)
def train(self):
self.sess.run(self.init)
for i in range(1000):
batch_xs, batch_ys = self.mnist.train.next_batch(100)
self.sess.run(self.train_step, feed_dict={self.x: batch_xs, self.y_: batch_ys})
correct_prediction = tf.equal(tf.argmax(self.y, 1), tf.argmax(self.y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
return self.sess.run(accuracy, feed_dict={self.x: self.mnist.test.images,
self.y_: self.mnist.test.labels})
if __name__ == '__main__':
# Start Ray.
ray.init()
# Create 3 actors.
training_actors = [TrainingActor.remote(seed) for seed in range(3)]
# Make them all train in parallel.
accuracy_ids = [actor.train.remote() for actor in training_actors]
print(ray.get(accuracy_ids))
# Start new training runs in parallel.
accuracy_ids = [actor.train.remote() for actor in training_actors]
print(ray.get(accuracy_ids))
如果只想创建数据集的一个副本,而不是让每个角色都读取数据集,则可以按以下方式重写。在引擎盖下,它使用Apache Arrow data format和Ray documentation。
@ray.remote
class TrainingActor(object):
def __init__(self, mnist, seed):
self.mnist = mnist
...
...
if __name__ == "__main__":
ray.init()
# Read the mnist dataset and put it into shared memory once
# so that workers don't create their own copies.
mnist = input_data.read_data_sets('MNIST_data/', one_hot=True)
mnist_id = ray.put(mnist)
training_actors = [TrainingActor.remote(mnist_id, seed) for seed in range(3)]
您可以在https://www.youtube.com/watch?v=中看到更多内容。请注意,我是Ray开发人员之一。