gpt4 book ai didi

tensorflow - 并行性并没有减少数据集映射中的时间

转载 作者:行者123 更新时间:2023-12-04 02:49:19 24 4
gpt4 key购买 nike

TF Map function supports parallel calls .我没有看到通过 num_parallel_calls 的任何改进映射。与 num_parallel_calls=1num_parallel_calls=10 , 性能运行时间没有改善。这是一个简单的代码

import time
def test_two_custom_function_parallelism(num_parallel_calls=1, batch=False,
batch_size=1, repeat=1, num_iterations=10):
tf.reset_default_graph()
start = time.time()
dataset_x = tf.data.Dataset.range(1000).map(lambda x: tf.py_func(
squarer, [x], [tf.int64]),
num_parallel_calls=num_parallel_calls).repeat(repeat)
if batch:
dataset_x = dataset_x.batch(batch_size)
dataset_y = tf.data.Dataset.range(1000).map(lambda x: tf.py_func(
squarer, [x], [tf.int64]), num_parallel_calls=num_parallel_calls).repeat(repeat)
if batch:
dataset_y = dataset_x.batch(batch_size)
X = dataset_x.make_one_shot_iterator().get_next()
Y = dataset_x.make_one_shot_iterator().get_next()

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
i = 0
while True:
try:
res = sess.run([X, Y])
i += 1
if i == num_iterations:
break
except tf.errors.OutOfRangeError as e:
pass

这里是时间
%timeit test_two_custom_function_parallelism(num_iterations=1000, 
num_parallel_calls=2, batch_size=2, batch=True)
370ms

%timeit test_two_custom_function_parallelism(num_iterations=1000,
num_parallel_calls=5, batch_size=2, batch=True)
372ms

%timeit test_two_custom_function_parallelism(num_iterations=1000,
num_parallel_calls=10, batch_size=2, batch=True)
384ms

我用了 %timeit在 Juypter 笔记本中。我做错了什么?

最佳答案

这里的问题是 Dataset.map() 中的唯一操作函数是 tf.py_func() 同上。此操作回调到本地 Python 解释器以在同一进程中运行一个函数。增加num_parallel_calls将增加尝试同时回调 Python 的 TensorFlow 线程的数量。然而,Python 有一个叫做 "Global Interpreter Lock" 的东西。这可以防止多个线程同时执行代码。结果,除了其中一个之外的所有多个并行调用都将被阻塞,等待获取全局解释器锁,并且几乎不会有并行加速(甚至可能会稍微减速)。

您的代码示例不包含 squarer() 的定义功能,但可以替换 tf.py_func()使用纯 TensorFlow 操作,它们是用 C++ 实现的,并且可以并行执行。例如——只是通过名字来猜测——你可以用调用 tf.square(x) 来替换它。 ,然后您可能会享受一些并行加速。

但是请注意,如果函数中的工作量很小,例如对单个整数进行平方,则加速可能不会很大。并行Dataset.map()对于繁重的操作更有用,例如使用 tf.parse_single_example() 解析 TFRecord或执行一些图像失真作为数据增强管道的一部分。

关于tensorflow - 并行性并没有减少数据集映射中的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48484689/

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