代码之家  ›  专栏  ›  技术社区  ›  P-Gn

在CPU预处理期间使用多线程时,Tensorflow速度较慢

  •  2
  • P-Gn  · 技术社区  · 8 年前

    make_sample 不能 被翻译成张量流运算。由于样本生成非常耗时,我想从多个线程调用该函数来填充输入队列。

    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

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

    1 回复  |  直到 8 年前
        1
  •  6
  •   Yaroslav Bulatov    8 年前

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

    推荐文章