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

标签 python tensorflow

我有一个在 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/

相关文章:

python - 组合任意形状的张量

python - 我们如何使用回调和提供数据框的函数动态地在 Dash Table 中创建数据列

python - sys.maxint 返回一个与 32 位系统相对应的值,即使我使用的是 64 位系统

python - 使用具有 LSTM 和动态 RNN 的可训练词嵌入层 : AdamOptimizer expected float_ref instead of float

python - Tensorflow 模型到 Numpy

tensorflow - 用 GPU 代替 TPU 训练莎士比亚模型

python - 需要使用 Keras 的 model.predict 的帮助

python - STATICFILES_DIRS 设置不是元组或列表。尽管它不包含逗号

Python 多处理 - 类型错误 : Pickling an AuthenticationString object is disallowed for security reasons

python - 拆分 pandas 数据框中的字符串数据