跳转到正文
Retep's
返回

[TIL] 学习笔记:卷积

编辑文章

本文由英文原文翻译。代码、公式与技术名称保留原文。

Triton 中的二维卷积

今天阅读了一个用于单通道二维卷积的小型 Triton kernel:

@triton.jit
def conv_2d(
    input,
    kernel,
    output,
    input_rows,
    input_cols,
    kernel_rows,
    kernel_cols,
    input_row_stride,
    input_col_stride,
    kernel_row_stride,
    kernel_col_stride,
    output_row_stride,
    output_col_stride,
    ROW_BLOCK: tl.constexpr,
    COL_BLOCK: tl.constexpr,
):
    row_pid = tl.program_id(0)
    col_pid = tl.program_id(1)
    row_start = ROW_BLOCK * row_pid
    col_start = COL_BLOCK * col_pid
    # compute output offsets for block (ROW_BLOCK, COL_BLOCK)
    output_row_offsets = row_start + tl.arange(0, ROW_BLOCK)
    output_col_offsets = col_start + tl.arange(0, COL_BLOCK)
    output_mask = (output_row_offsets < input_rows - kernel_rows + 1)[:, None] & (
        output_col_offsets < input_cols - kernel_cols + 1
    )
    acc = tl.zeros((ROW_BLOCK, COL_BLOCK), dtype=tl.float32)
    for i in range(kernel_rows):
        for j in range(kernel_cols):
            # notice that we loop through each kernel value and compute the increment to each output element
            # that it can interact with
            k_val = tl.load(kernel + i * kernel_row_stride + j * kernel_col_stride)
            input_row_offsets = output_row_offsets + i
            input_col_offsets = output_col_offsets + j
            input_mask = (input_row_offsets < input_rows)[:, None] & (
                input_col_offsets < input_cols
            )[None, :]
            input_val = tl.load(
                input
                + input_row_offsets[:, None] * input_row_stride
                + input_col_offsets[None, :] * input_col_stride,
                mask=input_mask,
            )
            acc += k_val * input_val

    tl.store(
        output
        + output_row_offsets[:, None] * output_row_stride
        + output_col_offsets[None, :] * output_col_stride,
        acc,
        mask=output_mask,
    )

一个 program 负责一个输出 tile

启动 grid 是二维的:

grid = (
    cdiv(output_rows, ROW_BLOCK),
    cdiv(output_cols, COL_BLOCK),
)

每个 Triton program 计算一个 ROW_BLOCK x COL_BLOCK 输出 tile。当前常量下,一个 program 最多计算 32 x 32 = 1024 个输出元素。

output

              col_pid=0        col_pid=1        col_pid=2
          +--------------+--------------+--------------+
row_pid=0 |  32 x 32     |  32 x 32     |  32 x 32     |
          +--------------+--------------+--------------+
row_pid=1 |  32 x 32     |  32 x 32     |  32 x 32     |
          +--------------+--------------+--------------+
row_pid=2 |  32 x 32     |  32 x 32     |  32 x 32     |
          +--------------+--------------+--------------+

在一个 program 中:

output_row_offsets = row_start + tl.arange(0, ROW_BLOCK)
output_col_offsets = col_start + tl.arange(0, COL_BLOCK)
acc = tl.zeros((ROW_BLOCK, COL_BLOCK), dtype=tl.float32)

output_row_offsets 是 32 个行索引组成的向量,output_col_offsets 是 32 个列索引组成的向量。通过 [:, None] 和 [None, :] 广播后,形成 32 x 32 的地址块。

这是典型 Triton 写法:创建偏移向量,广播为块,按块加载、运算和存储。

卷积循环

对于卷积核的每个元素 (i, j),program 加载一个卷积核标量:

k_val = tl.load(kernel + i * kernel_row_stride + j * kernel_col_stride)

然后加载一个平移了 (i, j) 的 32 x 32 输入 tile:

input_row_offsets = output_row_offsets + i
input_col_offsets = output_col_offsets + j

input_val = tl.load(
    input
    + input_row_offsets[:, None] * input_row_stride
    + input_col_offsets[None, :] * input_col_stride,
    mask=input_mask,
)

再累加:

acc += k_val * input_val

可以这样理解:

for every kernel position:
    load one scalar kernel value
    load the input patch covered by the output tile at that kernel offset
    multiply the whole input tile by the scalar
    add it into the output accumulator

对于 3 x 3 卷积核,一个 program 执行 9 次输入块加载和 9 次卷积核标量加载;对于 5 x 5,则分别为 25 次。

内存访问模式

假设输入是连续的行主序布局:

input_row_stride = input_cols
input_col_stride = 1

固定卷积核偏移 (i, j) 后,输入地址为:

input
+ (output_row_offsets[:, None] + i) * input_cols
+ (output_col_offsets[None, :] + j)

因此,32 x 32 块中的每一行在内存中连续:

input rows loaded by one program for one kernel element

row r+0:  x x x x x x x x ... 32 contiguous elements
row r+1:  x x x x x x x x ... 32 contiguous elements
row r+2:  x x x x x x x x ... 32 contiguous elements
...
row r+31: x x x x x x x x ... 32 contiguous elements

跨行步长为 input_cols。访存沿列连续、沿行有步长,这适合行主序图像。

输出存储具有相同形状:

output
+ output_row_offsets[:, None] * output_row_stride
+ output_col_offsets[None, :] * output_col_stride

结合:

output_row_stride = output_cols
output_col_stride = 1

每个输出行也都是连续的。

因此,这个 kernel 的访存模式很清楚:

重要的是输出不会被反复写入。所有卷积核位置处理完之前,部分和一直保存在 acc 中。

复用了什么?

这里有两类复用。

首先是卷积核标量的复用:

k_val = tl.load(...)
acc += k_val * input_val

同一个 k_val 应用于当前块的全部 32 x 32 输入元素。卷积核很小,相比输入 tile 加载,标量加载成本很低。

其次是相邻输出的输入窗口重叠。例如,水平方向相邻的两个 3 x 3 输出,其 9 个输入中有 6 个相同。

这个 kernel 没有显式把共享输入区域暂存到共享内存,而是为每个卷积核偏移从全局内存加载一个平移的 32 x 32 tile:

kernel offset (0, 0): load input rows r..r+31, cols c..c+31
kernel offset (0, 1): load input rows r..r+31, cols c+1..c+32
kernel offset (0, 2): load input rows r..r+31, cols c+2..c+33

这些加载高度重叠。硬件缓存可能捕获一部分复用,但程序并没有主动按下面的方式组织输入 tile:

(ROW_BLOCK + kernel_rows - 1) x (COL_BLOCK + kernel_cols - 1)

对于 32 x 32 输出 tile 和 3 x 3 卷积核,不重复的输入区域只有 34 x 34 = 1156 个元素。但当前代码在 Triton 块层面加载 9 x 32 x 32 = 9216 个输入元素,大量地址互相重叠。这也是 TileLang 显式控制内存放置的意义。

更接近生产实现的隐式 GEMM 卷积

为了得到更快的 kernel,可以将卷积表达为隐式矩阵乘法。

概念上的矩阵乘法为:

output[M, OC] = input_im2col[M, K] @ weight[K, OC]

其中:

M = batch * output_rows * output_cols
K = input_channels * kernel_rows * kernel_cols

实际不会物化 input_im2col。kernel 实时计算当前 M x K tile 的输入地址,加载对应值,再交给 tl.dot。

此版本假设输入为连续 NHWC,卷积核为 HWIO,输出为 NHWC。输入通道维度连续,使 K 维更适合向量加载和矩阵乘法。

import torch
import triton
import triton.language as tl


@triton.jit
def conv2d_implicit_gemm_nhwc_hwio(
    input,
    kernel,
    output,
    batch,
    input_rows,
    input_cols,
    input_channels: tl.constexpr,
    output_channels,
    kernel_rows: tl.constexpr,
    kernel_cols: tl.constexpr,
    output_rows,
    output_cols,
    BLOCK_M: tl.constexpr,
    BLOCK_N: tl.constexpr,
    BLOCK_K: tl.constexpr,
):
    pid_m = tl.program_id(0)
    pid_n = tl.program_id(1)

    m_offsets = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
    n_offsets = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
    k_offsets = tl.arange(0, BLOCK_K)

    output_spatial = output_rows * output_cols
    total_m = batch * output_spatial
    total_k: tl.constexpr = input_channels * kernel_rows * kernel_cols

    batch_offsets = m_offsets // output_spatial
    spatial_offsets = m_offsets % output_spatial
    out_rows = spatial_offsets // output_cols
    out_cols = spatial_offsets % output_cols

    acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)

    for k_start in range(0, total_k, BLOCK_K):
        k = k_start + k_offsets

        # translate k into indexes to read
        ic = k % input_channels
        kw = (k // input_channels) % kernel_cols
        kh = k // (input_channels * kernel_cols)

        input_rows_for_k = out_rows[:, None] + kh[None, :]
        input_cols_for_k = out_cols[:, None] + kw[None, :]
        input_channels_for_k = ic[None, :]

        # translate indexes to offsets
        input_ptrs = (
            input
            + batch_offsets[:, None] * input_rows * input_cols * input_channels
            + input_rows_for_k * input_cols * input_channels
            + input_cols_for_k * input_channels
            + input_channels_for_k
        )

        input_mask = (
            (m_offsets[:, None] < total_m)
            & (k[None, :] < total_k)
            & (input_rows_for_k < input_rows)
            & (input_cols_for_k < input_cols)
        )

        input_tile = tl.load(input_ptrs, mask=input_mask, other=0.0)

        weight_ptrs = (
            kernel
            + kh[:, None] * kernel_cols * input_channels * output_channels
            + kw[:, None] * input_channels * output_channels
            + ic[:, None] * output_channels
            + n_offsets[None, :]
        )

        weight_mask = (k[:, None] < total_k) & (n_offsets[None, :] < output_channels)
        weight_tile = tl.load(weight_ptrs, mask=weight_mask, other=0.0)

        acc += tl.dot(input_tile, weight_tile, input_precision="tf32")

    output_ptrs = (
        output
        + batch_offsets[:, None] * output_rows * output_cols * output_channels
        + out_rows[:, None] * output_cols * output_channels
        + out_cols[:, None] * output_channels
        + n_offsets[None, :]
    )
    output_mask = (m_offsets[:, None] < total_m) & (
        n_offsets[None, :] < output_channels
    )

    tl.store(output_ptrs, acc, mask=output_mask)

这将卷积转换为 GPU 最擅长的形式:

acc += tl.dot(input_tile, weight_tile)

对应 tile 为:

input_tile:  [BLOCK_M, BLOCK_K]
weight_tile: [BLOCK_K, BLOCK_N]
acc:         [BLOCK_M, BLOCK_N]

与标量版本相比,复用明显改善:

仍需针对 GPU 和形状调优。BLOCK_M = 64、BLOCK_N = 64、BLOCK_K = 32 只是起点。通道较少时,更小的 BLOCK_K 或 BLOCK_N 可能更快;输出通道很多时,BLOCK_N = 128 可能更好。大量使用 fp32 时,寄存器压力和 occupancy 更重要。

此 kernel 还假设 stride 为 1、无 padding、dilation 为 1。可以在地址计算中加入 padding 和 stride:

input_rows_for_k = out_rows[:, None] * stride_h + kh[None, :] - pad_h
input_cols_for_k = out_cols[:, None] * stride_w + kw[None, :] - pad_w

此时输入 mask 必须检查计算得到的坐标是否位于 [0, input_rows) 和 [0, input_cols) 内。


编辑文章
分享文章:

上一篇
[Book Club] TileLang:连接现代神经网络 Kernel 的可编程性与性能
下一篇
[TIL] TileLang EP-01:初探