Caffe 的卷积究竟是如何工作的?

How does Caffe's convolution really work?

所以我在玩弄作为基本卷积层的一部分实现的 pycaffe 的卷积函数。这是我的 convolution.prototxt 文件:

name: "convolution"
input: "data"
input_dim: 1
input_dim: 1
input_dim: 227
input_dim: 227

layer {
  name: "conv"
  type: "Convolution"
  bottom: "data"
  top: "conv"
  convolution_param {
    num_output: 96
    kernel_size: 11
    stride: 1
  }
}

这些参数与AlexNet的第一个CONV层的参数相同(除了stride,实际上是4)。

我有一台配备 NVIDIA GeForce GT 650M 1024 MB GPU 的 Macbook Pro。我不确定这有什么意义,但我的笔记本电脑也有一个 Intel HD 4000 作为内置 GPU。

我在笔记本电脑上做了一些测试,同时改变了步幅超参数,首先是在 GPU 模式下,然后是 CPU。

1) 调用 caffe.set_device(0); caffe.set_mode_gpu():

后的不同步幅
Stride 1: 27.26 ms
Stride 2: 14.27 ms
Stride 3: 10.57 ms
Stride 4: 7.45 ms

2) 调用 caffe.set_mode_cpu() 后的不同步幅:

Stride 1: 49.77 ms # expected
Stride 2: 9.92 ms # this and the results after this don't make sense
Stride 3: 4.50 ms
Stride 4: 1.96 ms

(3 的平均值。)

我只是想根据这些测试了解 Caffe 的卷积是如何工作的。谁能帮我阐明这一点?为什么 CPU 模式比 GPU 模式执行得更快?


我用的测试代码,有兴趣的可以自己看看:

import numpy as np
import caffe
import time

caffe.set_device(0)
caffe.set_mode_gpu() # caffe.set_mode_cpu()

net = caffe.Net('convolution.prototxt', caffe.TEST)
total = 0.0
for _ in range(3):
    net.blobs['data'].data[...] = np.random.randn(1, 1, 227, 227) # there really is an ellipsis there
    net.params['conv'][0].data[...] = np.random.randn(96, 1, 11, 11)
    s = time.time()
    r = net.forward()
    e = time.time()
    total += (e - s)

print total / 3 * 1000

于是,翻找了一下,发现Caffe基本上是用extra memory把局部区域拉平,然后用level3 BLAS routines(特别是cblas_sgemm)进行矩阵乘法得到结果.这导致以额外内存为代价的快速计算。

可以找到参考资料 here and here

GPU 的内存操作通常比 CPU 的成本高得多。所有额外的内存使用可能是在 GPU 模式下 运行 时遇到的减速的可能解释。这也取决于 GPU 的规格本身。