gpt4 book ai didi

tensorflow - 为什么TensorFlow在调用1D卷积时要计算2D卷积?

转载 作者:行者123 更新时间:2023-12-01 04:24:16 25 4
gpt4 key购买 nike

在 tf.nn.conv1d 的文档中,指出

Internally, this op reshapes the input tensors and invokes tf.nn.conv2d. For example, if data_format does not start with "NC", a tensor of shape [batch, in_width, in_channels] is reshaped to [batch, 1, in_width, in_channels], and the filter is reshaped to [1, filter_width, in_channels, out_channels]. The result is then reshaped back to [batch, out_width, out_channels] (where out_width is a function of the stride and padding as in conv2d) and returned to the caller.



我知道这些操作是等效的,但我对这个实现细节的含义有点困惑。

reshape 是否会产生一些计算开销?
3D 卷积有它自己的实现,那么为什么不是 1D 卷积呢?

感谢任何解释,帮助我和其他人理解 TensorFlow 的这个实现细节!

最佳答案

通过挖掘源代码,我得出结论,它可能是为了方便和实现的极简主义而完成的——细节如下。

首先,没有“ reshape ”,只有扩展、挤压和重新排序 dims,这会产生很小的开销;实际上没有数组元素在内存中移动 - 只有张量对象的索引说明符被更改。

二、全部conv最终路由到 tf.nn_ops.convolution_internal , 然后路由到 gen_nn_ops.conv2dgen_nn_ops.conv3d ;一个 conv1dgen_nn_ops.py 中不存在.请注意,由于某种原因,您不会在 Git 存储库中找到该文件 - 但它应该在您的本地安装中,/python/ops/gen_nn_ops.py .

最后,要真正回答为什么没有专门的 conv1d实现,您需要询问 gen_nn_ops.py 中的卷积算法背后的 cuDNN 开发人员;他们可能没有发现性能改进,conv2d工作一样快。从低层次的角度来看,这是有道理的,因为在将内核与 N x 1 滑动时的矩阵乘法数沿 M x 1 的元素输入与 N 的输入相同沿 M - 同样,唯一的区别在于索引。

不幸的是,开发人员决定封装最终调用,即 _pywrap_tensorflow_internal.TFE_Py_FastPathExecute ;该模块由 .lib 组成和 .pyd文件 - 基本上,编译的 C (Cython) 代码需要反汇编以进行自省(introspection)。

TL;DR(1)“ reshape ”的开销很小; (2) 缺少专用conv1d实现可能是每个备用冗余为conv2d一样快; (3) 我不是 cuDNN 专家,所以如果你需要确定,最好在 cuDNN 询问。 ,或阅读他们的SDK Documentation .或者,TF Github 的开发人员可能会有所帮助。多年来,我还没有看到 cuDNN 开发人员对 SO 的回答,所以在这里发帖可能不是最好的选择。

Dim 重新排序性能演示 :

import numpy as np
from time import time

x = np.random.randn(700, 800, 900) # 504,000,000 elements

t0 = time()
for i in range(1000):
if i % 2 == 0:
x = x.reshape(700, 900, 800)
else:
x = x.reshape(700, 800, 900)
print(time() - t0)
0.0009968280792236328

关于tensorflow - 为什么TensorFlow在调用1D卷积时要计算2D卷积?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59531864/

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