gpt4 book ai didi

python - 在 CPU 预处理期间使用多线程时 Tensorflow 变慢

转载 作者:行者123 更新时间:2023-11-28 22:25:35 26 4
gpt4 key购买 nike

我有一个在 CPU 上动态生成的数据集。样本在 Python 中通过函数 make_sample 计算,该函数非常复杂并且无法转换为 tensorflow 操作。因为样本生成很耗时,所以我想从多个线程调用该函数来填充输入队列。

我从 example given in the documentation 开始并得出以下玩具示例:

import numpy as np
import tensorflow as tf
import time

def make_sample():
# something that takes time and needs to be on CPU w/o tf ops
p = 1
for n in range(1000000):
p = (p + np.random.random()) * np.random.random()
return np.float32(p)

read_threads = 1

with tf.device('/cpu:0'):
example_list = [tf.py_func(make_sample, [], [tf.float32]) for _ in range(read_threads)]
for ex in example_list:
ex[0].set_shape(())
batch_size = 3
capacity = 30
batch = tf.train.batch_join(example_list, batch_size=batch_size, capacity=capacity)

with tf.Session().as_default() as sess:
tf.global_variables_initializer().run()
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
try:
# dry run, left out of timing
sess.run(batch)
start_time = time.time()
for it in range(5):
print(sess.run(batch))
finally:
duration = time.time() - start_time
print('duration: {0:4.2f}s'.format(duration))
coord.request_stop()
coord.join(threads)

令我惊讶的是,当增加 read_threads 时,CPU 使用率从未超过 50%。更糟糕的是,计算时间直线下降:在我的电脑上,

  • read_threads=1duration: 12s
  • read_threads=2duration: 46s
  • read_threads=4duration: 68s
  • read_threads=8duration: 112s

是否有一个解释,最重要的是,一个解决方案可以在 tensorflow 上使用自定义 python 函数生成高效的多线程数据?

最佳答案

tf.py_func 重用现有的 Python 解释器。不幸的是,Python 支持并发但不支持并行。换句话说,你可以有多个 Python 线程,但任何时候只有一个线程可以执行 Python 代码。标准解决方案是将生成管道移至 TensorFlow/C++,或使用多个 Python 进程和附加层来聚合其结果(即,使用 ZMQ 聚合来自多个 Python 进程的结果)

关于python - 在 CPU 预处理期间使用多线程时 Tensorflow 变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45446236/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com