tf.function结合TensorArray实现远慢于原生Python的原因与优化
性能异常实测现象
- 为提升项目运行性能,开发者使用带
@tf.function装饰器的TensorFlow实现替代原有未使用TensorFlow的原生Python实现,实测结果与优化预期完全相反:- 开启GPU运行时,原生Python代码的运行速度比tf.function实现快100倍
- 纯CPU环境下,TensorFlow实现的速度差距缩小,但仍比原生Python实现慢10倍
- 当入参
cond取值较大(如5000及以上)时,两类实现的速度差距会尤其明显。
对照测试代码
带@tf.function装饰的TensorFlow实现
@tf.function def test1(cond): xp = tf.constant(0) yp = tf.constant(0) stride = tf.constant(10) patches = tf.TensorArray( tf.int32, size=tf.cast((cond / stride + 1) * (cond / stride + 1), dtype=tf.int32), dynamic_size=False, clear_after_read=False) i = tf.constant(0) while tf.less_equal(yp, cond): while tf.less_equal(xp, cond): xp = tf.add(xp, stride) patches = patches.write(i, xp) i += 1 xp = tf.constant(0) yp = tf.add(yp, stride) return patches.stack()
原生Python对照实现
def test2(cond): xp = 0 yp = 0 stride = 10 i = 0 patches = [] while yp <= cond: while xp <= cond: xp += stride patches.append(xp) xp = 0 yp += stride return patches
问题定位与优化结果
- 开发者检索TensorFlow官方仓库的相关issue后确认,问题根源与排查方向一致:
tf.TensorArray的性能表现不佳,搭配逐次循环逐次写入数组的实现逻辑,抵消了@tf.function的图编译优化、以及GPU硬件加速的收益,最终导致运行效率远低于原生Python实现。 - 对应场景的优化方案:替换原有
tf.TensorArray与逐次循环结构,改用张量计算体系下的向量化算子实现同等逻辑,例如可使用tf.image.extract_patches这类内置向量化算子完成计算。 - 按上述方案完成优化后,TensorFlow实现的运行性能比原生Python代码快3倍,达成最初的性能优化目标。
内容的提问来源于stack exchange,提问作者pdimh
相关产品推荐
相关产品推荐

