【发布时间】:2021-12-11 02:32:12
【问题描述】:
我正在研究神经网络的 CUDA 实现,我想知道如何进一步优化全连接层中的计算。
我当前用于神经网络中全连接层的 CUDA 内核包括以下步骤:
- 将输出神经元累加器 (
input) 设置为 0 - 将上一层 (
in) 的输出数据与当前层的weights相乘,并将结果相加到累加器中 - 通过对累积的数据应用激活函数来计算当前层 (
out) 的输出
这些是单层神经网络中的一般步骤,但目前(见下文)实现为单独的内核。对于较小的输出大小(例如outSizeX 等于 10),第一步和第三步相对较慢,尤其是结合启动三个内核。
因此,我的问题是:如何将这三个内核组合成一个内核来执行上述所有三个步骤?
// Step 1
__global__ void set_to_zero_cuda(float *__restrict__ input, int outSizeX)
{
int i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= outSizeX)
return;
input[i] = 0;
}
// Step 2
__global__ void activate_cuda_fc(const float *__restrict__ in, float *__restrict__ input, const float *__restrict__ weights,
int totalInSize, int outSizeX, int weightSizeX)
{
int x = blockIdx.x * blockDim.x + threadIdx.x;
int y = blockIdx.y * blockDim.y + threadIdx.y;
int nx = blockDim.x * gridDim.x;
int ny = blockDim.y * gridDim.y;
for (int n = x; n < outSizeX; n += nx)
{
for (int i = y; i < totalInSize; i += ny)
{
atomicAdd(&input[n], in[i] * weights[i + n * weightSizeX]);
}
}
}
// Step 3
__global__ void perform_activation_function_cuda_fc(float *__restrict__ out, float *input,
int outSizeX)
{
int i = threadIdx.x + blockIdx.x * blockDim.x;
if (i >= outSizeX)
return;
out[i] = activator_function_cuda(input[i]);
}
作为参考,当前配置文件如下所示:
【问题讨论】:
标签: c++ machine-learning deep-learning neural-network cuda