# 前言

本篇是学习 MLIR 中的 Transform Dialect 的第六篇,本章主要讲的是演示如何用 MLIR 的 Transform dialect 来复现 Halide DSL 的调度(schedule),并以 2D 通道卷积为例,完整走一遍从高层调度到接近手写性能的优化流程。内容来自 MLIR 官方教程 《Chapter H: Reproducing Halide Schedule》。

相关链接: LLVM Project ,MLIR 官方文档,MLIR 官网教程。

作为初学者,错误在所难免,还望不吝赐教。

# Transform Dialect

Transform Dialect 提供了一个「基底(substrate)」,用来在 MLIR 里实现各种变换指令型 DSL(transformation directive DSL)。

  • 可以基于 Transform dialect 定义一套自己的调度 DSL;
  • 这套 DSL 的调度部分,最终会落到 Transform dialect 的操作上,由编译器去执行;
  • 甚至可以新建一个方言,只要复用 Transform dialect 的接口和基础设施。

# Channeled Convolution

我们想把一个标准的 Halide 风格 2D 带通道卷积算法,等价翻译到 MLIR 的 Linalg 结构化操作方言上。
现在有两种 Halide → MLIR 的对接思路:

1. 新建一个完整的 Halide 方言,再把所有调度原语包装成 Transform 操作。这种思路语法最贴近 Halide,但是重复造轮子,因为 Halide 作为 DSL 的核心能力 —— 结构化张量计算表达 + 循环级调度变换 —— 在 MLIR 生态中已经有通用、可复用的标准实现。再实现一遍 Halide Dialect,是重复造轮子。
2. 把 Halide 的抽象直接映射到 MLIR 已有的 Linalg 结构化操作上。这种思路复用 Linalg 全部现有变换,生态成本最低,也是本教程采用的方案。

Halide 的「数学函数」抽象,和 Linalg 的「结构化张量操作 + 隐式循环」模型在概念上高度同构,可以直接平移。

教程中的例子 :示例取自 Halide 官方的 conv_layer 应用,是一个标准的带偏置 2D 卷积 + ReLU 计算。

// Sizes of the problem.
const int N = 5, CI = 128, CO = 128, W = 100, H = 80;
// Sized inputs. Note that the order of dimensions is
// inverted in Halide with respect to C++, so the last dimension
// in the list (N for input, CI for filter) is the least
// frequently varying. The C++ equivalent is input[N][H+2][W+2][CI].
Buffer<float, 4> input({CI, W+2, H+2, N}, "input");  // 128,102,82,5  CWHN -> NHWC Halide 中 buffer 设置时反着来的
Buffer<float, 4> filter({CO, 3, 3, CI}, "filter");  // 128,3,3,128    CO 3*3 CI -> CI 3*3 CO 
Buffer<float, 1> bias(std::vector<int>{CO}, "bias");  // 128
// ... data initialization happens here ...
// Declarations of "mathematical functions" for convolution and relu.
Func conv("conv"), relu("relu");
// Iterators/subscripts.
Var x("x"), y("y"), c("c"), n("n");
// 3D reduction domain (channels and 2 window dimensions),
// dimensions are later referred to as r.x, r.y, r.z.
RDom r(0, CI, 0, 3, 0, 3);
// Core convolution with the result initialized to the bias value.
// Note that the order of iterators is inverted in Halide DSL,
// i.e. `n` corresponds to the lest frequently-varying (outermost) dimension
// here and below.
conv(c, x, y, n) = bias(c);
conv(c, x, y, n) += filter(c, r.y, r.z, r.x) * input(r.x, x + r.y, y + r.z, n);
// ReLU rectification, an elementwise operation.
relu(c, x, y, n) = max(0, conv(c, x, y, n));

需要注意的是 :Halide Buffer 定义中,维度列表的顺序是从变化最快到变化最慢;而 C/C++ 数组的下标顺序是从变化最慢到变化最快。两者恰好相反。也就是说,Buffer 列表里的第一个维度,对应最内层循环,内存中连续存储;Buffer 列表里的最后一个维度,对应最外层循环,变化频率最低。

Func conv("conv"), relu("relu");
Var x("x"), y("y"), c("c"), n("n");
RDom r(0, CI, 0, 3, 0, 3);
conv(c, x, y, n) = bias(c);
conv(c, x, y, n) += filter(c, r.y, r.z, r.x) * input(r.x, x + r.y, y + r.z, n);
relu(c, x, y, n) = max(0, conv(c, x, y, n));

其中对于卷积得定义非常简洁, RDom r(0, CI, 0, 3, 0, 3); 定义了一个规约域, r.x 是范围 [0,CI), r.y 是范围 [0,3), r.z 是范围 [0,3)。而 conv(c, x, y, n) += filter(c, r.y, r.z, r.x) * input(r.x, x + r.y, y + r.z, n); 则定义了整个卷积的计算过程,conv (c, x, y, n) 表示 “在坐标 (c, x, y, n) 处,卷积结果是多少”。
这里面没有定义循环,但是定义了卷积结果的每个像素和 fliter、input 的对应关系。
而 c,x,y,n 这四个变量并没有限制取值范围,因为这四个变量表示的是四个坐标符号,而取值范围是在函数具体调用的时候指定的,比如 conv.realize({CO, W, H, N}); 。
将上述 Halide 官方的 conv_layer 应用,映射为 Linalg 方言,如下所示:

// Bias. Using a named Linalg operation for brevity.
%bias_init = tensor.empty() : !toutput
%biased = linalg.broadcast ins(%bias : !tbias)  // 对应 Halide conv (c, x, y, n) = bias (c); bias 广播
                          outs(%bias_init : !toutput) dimensions = [0, 1, 2]
// Convolution proper. While Linalg has named operations for 2D convolutions,
// the one in the Halide example has an uncommon order of filter dimensions
// and is not supported. It also takes the filter as first argument. This
// code recreates it faithfully using the generic form.
%convolved = linalg.generic {
  iterator_types = ["parallel", "parallel", "parallel", "parallel",
                    "reduction", "reduction", "reduction"],
  indexing_maps = [
    affine_map<(n, y, x, c, rz, ry, rx) -> (rx, rz, ry, c)>,
    affine_map<(n, y, x, c, rz, ry, rx) -> (n, y+rz, x+ry, rx)>,
    affine_map<(n, y, x, c, rz, ry, rx) -> (n, y, x, c)>
  ]
} ins(%filter, %input: !tfilter, !tinput)
  outs(%biased : !toutput) {
^bb0(%in: f32, %f: f32, %b: f32):
  // Note the fastmath attributes that allow operations to be recombined into
  //   %0 = math.fma %in, %f, %b : f32
  // later on and to reorder reductions.
  %m1 = arith.mulf %in, %f  {fastmath = #arith.fastmath<fast>} : f32
  %0 = arith.addf %b, %m1  {fastmath = #arith.fastmath<fast>} : f32
  linalg.yield %0 : f32
} -> !toutput
// ReLU is just a max(0, x).
%c0 = arith.constant 0.0 : f32
%relued = linalg.generic {
  iterator_types = ["parallel", "parallel", "parallel", "parallel"],
  indexing_maps = [
    affine_map<(d0, d1, d2, d3) -> ()>,
    affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>,
    affine_map<(d0, d1, d2, d3) -> (d0, d1, d2, d3)>
  ]
} ins(%c0, %convolved : f32, !toutput)
  outs(%output : !toutput) {
^bb0(%cst: f32, %in: f32, %out: f32):
  %0 = llvm.intr.maxnum(%cst, %in) : (f32, f32) -> f32
  linalg.yield %0 : f32
} -> !toutput

Halide 与 Linalg 的循环模型不同。

Halide 里 conv 的初始化和更新虽然写成两条语句,但内部是同一个对象;Linalg 没有这种能力,初始化和更新是两个互不相连的 Linalg 操作。

Halide 中 x, y, c, n 这些变量对应隐式循环; 共享这些变量的函数,也共享对应的循环; 所以 Halide 定义的循环等价形式是全融合(fully-fused)的。

for n
  for y
    for x
      for c
        conv[n, y, x, c] = bias[c]
        for rz
          for ry
            for rx
              conv[n, y, x, c] += filter[rx, rz, ry, c] * input[n, y+rz, x+ry, rx]
        relu[n, y, x, c] = max(0, conv[n, y, x, c])

也就是说,尽管有以下三条分开的语句:

conv(c, x, y, n) = bias(c);                                    // (1) 初始化
conv(c, x, y, n) += filter(...) * input(...);                  // (2) 归约更新
relu(c, x, y, n) = max(0, conv(c, x, y, n));                   // (3) ReLU

但 Func 之间的关系和共享的 Var 会让编译器把它们视为同一个循环嵌套里的不同阶段。初始化、归约、ReLU 都在同一组外层循环里。

而 Linalg 每个结构化操作对应自己的循环嵌套;所以是全分布(fully-distributed)的。

for n
  for y
    for x
      for c
        init[n, y, x, c] = bias[c]
for n
  for y
    for x
      for c
        for rz
          for ry
            for rx
              conv[n, y, x, c] += filter[rx, rz, ry, c] * input[n, y+rz, x+ry, rx]
for n
  for y
    for x
      for c
        relu[n, y, x, c] = max(0, conv[n, y, x, c])

# Mapping Halide Scheduling Primitives to Linalg Structured Transforms

将 Halide 调度原语映射为 Linalg 结构化变换。

把 Halide 调度中的 5 个原语,逐一映射到 MLIR Linalg / Transform dialect 上对应的变换操作,并解释每个映射的细节和注意点。

上述 Halide 例子中的完整调度操作如下所示:同时教程声明,本章只考虑不带并行化的版本,避免 Halide 和 MLIR 并行运行时差异干扰对比。所以 parallel (y)、parallel (n)、parallel (co) 这里不展开讨论。

Var co, ci, xo, xi;
relu.split(c, co, ci, vec * tile_w)
  .split(x, xo, xi, tile_h)
  .reorder(ci, xi, xo, y, n, co)
  .vectorize(ci, vec)
  .unroll(ci)
  .unroll(xi)
  .parallel(y)
  .parallel(n)
  .parallel(co);
conv.compute_at(relu, xo)
  .vectorize(c, vec)
  .unroll(c)
  .unroll(x)
  .unroll(y)
  .update()
  .reorder(c, x, y, r.x, r.y, r.z, n)
  .vectorize(c, vec)
  .unroll(c)
  .unroll(x)
  .unroll(y)
  .unroll(r.x, 2);

先了解一下 Halide 和 MLIR 5 个原语的对照:
split → tile_using_forall
Halide 的 split 本质是循环 strip-mining (Strip-mining(条带挖掘)中文名常译作循环剥离,把一个单层循环拆成两层嵌套循环),或者说是「单维 tiling 的退化情况」。
MLIR 中使用 transform.structured.tile_using_forall 。选择 tile_using_forall 而不是 tile,是因为这种循环对 bufferization 支持最好,且后续可以转成并行循环。
两者有些差异性:Halide 的 split 会给原操作增加新的维度;Linalg 的 tiling 不给原操作增加维度,它会在原操作外面包一层循环,并重写原操作本身,让它只处理原始数据的一个子集(通过 tensor.extract_slice/tensor.parallel_insert_slice)。
这个 Linalg 的 tiling 操作有些抽象,举个例子:
对于 Halide 来说,一个 4D tensor,形状 5x80x100x128,对应 (n, y, x, c),它有 4 个隐式循环 n, y, x, c,Halide 的 split 语义是:把 c 拆成 co 和 ci,操作本身增加一个维度,变成 5D: c = co * 64 + ci ,也就是 5x80x100x2x64。
Linalg tiling 现在对 c 做 tiling,tile size = 64,

%co, %relu2 = transform.structured.tile_using_forall %relu
                tile_sizes [0, 0, 0, 64]

结果大致是:

%co = scf.forall (%co) in (2) shared_outs(%arg = %out) -> (tensor<5x80x100x128xf32>) {
  // 1. 从原 tensor 中切出当前 tile 对应的子集
  %slice_in  = tensor.extract_slice %conv[0, 0, 0, %co * 64] [5, 80, 100, 64] [1, 1, 1, 1]
                 : tensor<5x80x100x128xf32> to tensor<5x80x100x64xf32>
  %slice_out = tensor.extract_slice %out[0, 0, 0, %co * 64] [5, 80, 100, 64] [1, 1, 1, 1]
                 : tensor<5x80x100x128xf32> to tensor<5x80x100x64xf32>
  // 2. 原 op 被重写成只处理这个子集,rank 仍然是 4
  %relu_tile = linalg.generic {
    iterator_types = ["parallel", "parallel", "parallel", "parallel"],
    indexing_maps = [
      affine_map<(n, y, x, ci) -> ()>,
      affine_map<(n, y, x, ci) -> (n, y, x, ci)>,
      affine_map<(n, y, x, ci) -> (n, y, x, ci)>
    ]
  } ins(%c0, %slice_in : f32, tensor<5x80x100x64xf32>)
    outs(%slice_out : tensor<5x80x100x64xf32>) {
  ^bb0(%cst: f32, %in: f32, %out: f32):
    %0 = llvm.intr.maxnum(%cst, %in) : (f32, f32) -> f32
    linalg.yield %0 : f32
  } -> tensor<5x80x100x64xf32>
  // 3. 把子集结果写回原 tensor
  %inserted = tensor.parallel_insert_slice %relu_tile into %arg[0, 0, 0, %co * 64]
                [5, 80, 100, 64] [1, 1, 1, 1]
                : tensor<5x80x100x64xf32> into tensor<5x80x100x128xf32>
  scf.forall.in_parallel {
    tensor.parallel_insert_slice ...
  }
}

%co 是一个 scf.forall 循环变量,范围是 2(因为 128 / 64 = 2)。这是 tiling 物化出来的显式循环,包在原 op 外面。原 op 的 rank 没有变,还是 4。
也就是说,原 op 没有因为 tiling 变成 5D。它只是从「处理 c 的 128 个元素」变成了「处理 c 的 64 个元素」。

reorder → interchange
Halide 的 reorder 可以任意重排循环。
MLIR 的情况更复杂,1. 隐式循环:Linalg 的循环是隐式的(还没有物化为显示的 scf.for/scf.forall),并且尽量保持隐式,以便后续匹配微内核。用 transform.structured.interchange 来隐式地改变循环顺序。2. 命名操作:interchange 不能直接作用于命名操作(如 linalg.broadcast),需要先用 transform.structured.generalize 把它泛化成 linalg.generic。3. 已物化的显式循环:tiling 物化出来的显式循环不能再折回原操作,所以 interchange 管不到它们。

vectorize → vectorize_children_and_apply_patterns
Halide 的 vectorize 是针对某个维度、按给定因子向量化;如果循环范围大于因子,循环会被拆成两部分,内层被向量化。
MLIR 的差异较大, transform.structured.vectorize_children_and_apply_patterns 是全局变换,作用于某个作用域(如函数)内所有合适的操作;依赖 MLIR 的多维向量支持,直接把多维 tensor 映射成多维 vector;后续 lowering 时,多维向量再被分解成硬件支持的小向量。
也就是说,MLIR 不是 “选一个维度、选一个因子、局部向量化”,而是 “全局多维向量化,后续再分解”。

*unroll → transform.loop.unroll
这个映射两者很直接:
Halide 的 unroll = 循环展开,完全展开或按因子展开;
MLIR 对应 transform.loop.unroll。

compute_at → fuse_into_containing_op
Halide 的 compute_at 表示:某个函数的值必须在另一个函数产生的指定循环内计算。【Halide】调度优化【2】中该原语操作介绍比较详细。根据两个函数周围循环的关系,这对应两种可能:循环分布(loop distribution);生产者 / 消费者融合(producer/consumer fusion)。
MLIR : Linalg 表示起点是全分布的(每个 op 有自己的循环),所以 compute_at 对应的是融合,用 transform.structured.fuse_into_containing_op ,它作用在之前 tiling 物化出来的 forall 循环上。

# Recreating the Loop Structure

这一节(Recreating the Loop Structure)是整章从「概念映射」进入「实际构造」的第一步。它的核心任务是:用 Transform dialect 的 tiling 和 fusion 操作,把第一小节里 Linalg 的全分布结构,逐步重构成 Halide 调度所期望的融合循环结构。
1.Tile 拆分
Halide 调度中的前三条指令:

relu.split(c, co, ci, vec * tile_w) 
  .split(x, xo, xi, tile_h)
  .reorder(ci, xi, xo, y, n, co)

目标是产生以下的循环:

for co
  for n
    for y
      for xo
        for xi
          for ci
            relu[n, y, xo*tile_h + xi, co*tile_w*vec + ci] = ...

c 的外层部分 co 被提到了所有循环的最外层(注意 Halide 的顺序,最后面的是最外层);relu 的隐式循环顺序是 (n, y, x, c),c 在最内层。所以要让 co 出现在最外层,必须最先物化 co,否则它会被后面的物化压在内部。

所以 Linalg 分两步 tiling 物化目标循环:

//                                                             [n  y  x  c]
%co, %relu2 = transform.structured.tile_using_forall %relu
                                                    tile_sizes [0, 0, 0, 64]
%n_y_xo, %relu3 = transform.structured.tile_using_forall %relu2
                                                    tile_sizes [1, 1, 5, 0]

第一步,物化 co,[5,80,100,128],tile 目标是 [0, 0, 0, 64](0 表示该维度不 tile), tile_using_forall 会自动将外层循环给物化出来,也就是(,,,2),这第一步,将 co 维度提取到了最外面,内部隐式循环为 [5,80,100,64]。
第二步,物化 n, y, xo,[5,80,100,64], tile 目标是 [1,1,5,0],外层循环 (5,80,20) 会被物化出来,内部隐式循环变成 [1,1,5,64]。

scf.forall (%co) in (2) {
  scf.forall (%n, %y, %xo) in (5, 80, 20) {
    tensor.extract_slice
    // Implicit dimensions [ni=0:1, yi=0:1, xi=0:5, ci=0:64]
    %relued = linalg.elementwise <max_signed> // ...
    scf.forall.in_parallel {
      tensor.parallel_insert_slice // ...
    }
  }
}

循环融合
把 conv 和 bias 融合进 ReLU 的循环,MLIR 循环结构进一步拓展为:

for co
  for n
    for y
      for xo
        for xi
          for ci
            conv[...] = ...        // 初始化
        for rz
          for ry
            for rx
              for xi
                for ci
                  conv[...] += ... // 归约更新
        for xi
          for ci
            relu[...] = ...        // ReLU

也就是要让 conv 的初始化和更新、relu 的计算,都发生在同一组 co, n, y, xo 循环里,只是内部的 xi, ci 和 rz, ry, rx 循环位置不同。因为 Linalg 起点是全分布,conv 和 bias 各自有独立的循环,所以需要显式融合。融合分两阶段:
1. 先把卷积更新融合进 ReLU(因为 ReLU 使用 conv 的结果,且 ReLU 的循环已经物化);

2. 再把 bias 初始化融合进 conv + relu 的循环嵌套。
每个阶段又分两步:先融合进外层 % co,再融合进内层 %n_y_xo 。

%conv2, %co2 = transform.structured.fuse_into_containing_op %conv into %co
%conv3, %n_y_xo2 = transform.structured.fuse_into_containing_op %conv2
  into %n_y_xo
%bias2, %co3 = transform.structured.fuse_into_containing_op %bias into %co2
%bias3, %n_y_xo3 = transform.structured.fuse_into_containing_op %bias2
  into %n_y_xo2

fuse_into_containing_op 把 producer 的计算搬进 consumer 已物化的循环里;分两步是因为循环有两层:先融进外层 % co,再融进内层 %n_y_xo ;融合后,conv 的初始化和更新、relu 的计算,都共享 co, n, y, xo 这组循环。

3. 把归约循环 rz, ry, rx 放到 tile 循环外面
目标结构里,rz, ry, rx 在 xo 循环内部、但在 xi, ci 循环外部:

for xo
  for xi
    for ci
      conv[...] = ...        // 初始化
  for rz
    for ry
      for rx
        for xi
          for ci
            conv[...] += ... // 归约更新
  for xi
    for ci
      relu[...] = ...        // ReLU

但此时 rz, ry, rx 还是 linalg.generic 内部的隐式归约维度。需要把它们物化成显式循环。

问题:rz, ry, rx 是 reduction 维度,不能像并行维度那样用 tile_using_forall 物化成 scf.forall(forall 是并行语义,归约不能简单并行)。解决办法:用专门的归约 tiling:

%rz_ry_rx, %red_fill, %conv4, %comb
  = transform.structured.tile_reduction_using_for %conv3
//               n  y  x  c  rz ry rx
  by tile_sizes=[0, 0, 0, 0, 1, 1, 1]

tile_reduction_using_for 把归约维度物化成顺序的 scf.for 循环,而不是 scf.forall;tile size 全是 1,所以归约完全由生成的循环完成;它还会产生一个 combiner 操作 % comb,把归约结果和初始值相加;这会改变浮点运算顺序,但 fastmath 标志允许这种重排。
结果为:

for rz
  for ry
    for rx
      for xi
        for ci
          conv[...] += ...

4. 物化最内层的 xi 和 ci 循环
此时 xi 和 ci 还在 op 内部隐式。下一步要向量化 ci,但 MLIR 的向量化是多维向量化:它不选「某个维度、某个因子」局部向量化;而是直接把 tensor 类型替换成多维 vector 类型;然后后续 lowering 再分解成硬件支持的向量。
所以 tensor 类型不能变成 size-1 的平凡类型,必须在 ci 方向保留 vector_size(比如 16)的维度。
做法:用 vector_size 作为 tile size,对 xi 和 ci 做 tiling:

//                                                                  n  y  xi ci
%1, %c5 = transform.structured.tile_using_forall %conv4 tile_sizes [0, 0, 1, 16]
%2, %b4 = transform.structured.tile_using_forall %bias3 tile_sizes [0, 0, 1, 16]
%3, %r4 = transform.structured.tile_using_forall %relu3 tile_sizes [0, 0, 1, 16]
%4, %c2 = transform.structured.tile_using_forall %comb  tile_sizes [0, 0, 1, 16]

对 xi 用 tile size 1,对 ci 用 tile size 16;物化出 scf.forall 循环包住 op;op 内部保留 tensor<1x1x1x16xf32> 这样的形状,其中 16 是向量宽度;这样后续 vectorize_children_and_apply_patterns 就能把它变成 vector<16xf32> 操作;注意 comb(归约 tiling 产生的 combiner)也要 tiling。

# Explicit Loop Unrolling

进行循环展开。

Halide 调度中有这样的循环展开指令:

conv.unroll(c)
    .unroll(x)
    .unroll(y)
    ...
    .unroll(r.x, 2);

教程里写了,真正需要展开的是构成 4x5 tile 的最内层循环 xi 和 ci:ci 循环展开因子 4(16 元素向量 × 4 = 64,对应 tile_w );xi 循环展开因子 5(对应 tile_h )。
展开后形成 4 × 5 = 20 个 16 元素向量操作,正好对应 20 个 512-bit 向量寄存器作为累加器(zmm 寄存器)。这是为了生成连续的 vfma 指令序列,让寄存器分配和指令调度更高效。
教程中提到,有些循环写了但实际不展开,“Unrolling additional loops, unroll (y) and unroll (r.x, 2), is requested in the schedule but has no practical effect. That is, the code, and all intermediate representations, produced by Halide with these directives removed is strictly identical to the code with the full schedule.”
即 Halide 调度里虽然写了 unroll (y) 和 unroll (r.x, 2);但 Halide 编译器实际生成的代码,去掉这两条指令后完全一样;所以它们没有实际效果,不需要在 MLIR 里复现。原因可能是:y 循环在展开后已经被 xi 的展开覆盖,或者 Halide 认为展开它没有收益;r.x(输入通道归约)的展开因子 2 被其他优化吸收了。
MLIR 可以 “链式” 展开,前面的 tiling(tile_using_forall)已经物化出循环,并返回了循环的 handle;比如 % c5 是 conv 的 xi, ci 循环的 handle;所以 unroll 只需要用这些 handle 直接调用 transform.loop.unroll,不需要重新 match 循环。

transform.loop.unroll %bias_ci {factor = 4}    // 先内层 ci
transform.loop.unroll %bias_xi {factor = 5}    // 再外层 xi
transform.loop.unroll %conv_ci {factor = 4}
transform.loop.unroll %conv_xi {factor = 5}
transform.loop.unroll %relu_ci {factor = 4}
transform.loop.unroll %relu_xi {factor = 5}
transform.loop.unroll %comb_ci {factor = 4}
transform.loop.unroll %comb_xi {factor = 5}

循环展开要按照先内后外的顺序,因为展开外层循环 xi 会重写循环结构,导致内层循环 ci 的 handle 失效;一旦 handle 失效,就无法再对内层循环做 unroll。

# Vectorization

1. 先做简化
前面的 tiling 和 fusion 产生了大量操作:tensor.extract_slice/tensor.parallel_insert_slice 计算子集;scf.forall 的循环范围计算;融合后重复的索引计算、边界计算。
这些操作里有很多是重复的或过于复杂的,如果不清理,向量化后代码会变得臃肿,影响后续 lowering 和优化。

%f00 = transform.structured.match ops{["func.func"]} in %arg0
transform.apply_patterns to %f00 {
  transform.apply_patterns.canonicalization
  transform.apply_patterns.linalg.tiling_canonicalization
}
transform.apply_cse to %f00
%all_loops = transform.structured.match interface{LoopLikeInterface} in %arg0
transform.apply_licm to %all_loops

里面做的内容:

  • canonicalization + tiling_canonicalization:通用规范化:折叠常量、简化 affine.apply、消除冗余 tensor.extract_slice 等;tiling_canonicalization:专门针对 tiling 产生的模式,比如把 extract_slice + insert_slice 合并、简化循环边界。

  • CSE(公共子表达式消除):把重复计算的表达式合并成一个。

  • LICM(循环不变量代码外提):把循环内不变的计算提到循环外;作用于所有 LoopLikeInterface 的循环(scf.for、scf.forall 等)。
    为什么用 Transform dialect 而不是传统 pass,教程指出,传统编译器 pass 通常一组 pattern 一个 pass,要组合多组 pattern 就得写新 pass;Transform dialect 的 transform.apply_patterns 可以在一次扫描中应用任意组合的 pattern 组,不需要为每种组合写新 pass;这样更灵活,也更容易控制 pattern 的应用顺序和范围。
    这是 Transform dialect 的一个优势:pattern 组合是一等公民。

2. 去掉单位维度: fold_unit_extent_dims_via_reshapes
回顾前面的 tiling:用 tile size 1 物化 n, y, xi 循环;用 tile size 16 物化 ci 循环;结果 op 内部 tensor 是 tensor<1x1x1x16xf32>;四个维度里只有 ci 方向是 16,其他三个都是 1。
核心计算没变,但 4D 类型里三个维度是 1,实际只有一个有效维度;后续 lowering 把多维向量分解成硬件支持的向量时,单位维度会让代码变复杂;比如 vector<1x1x1x16xf32> 分解成 vector<16xf32> 时,需要额外的 reshape / 类型转换操作。
解决方法:

transform.apply_patterns to %f00 {
  transform.apply_patterns.linalg.fold_unit_extent_dims_via_reshapes
}

fold_unit_extent_dims_via_reshapes 把 tensor<1x1x1x16xf32> 里的单位维度折叠掉;这样向量化后得到的是 vector<16xf32>,而不是 vector<1x1x1x16xf32>

3. 向量化本身

%fv = transform.structured.vectorize\_children\_and\_apply\_patterns %f00

vectorize_children_and_apply_patterns 作用于 % f00(函数作用域);它把作用域内所有合适的 Linalg op 向量化;向量化方式:把 tensor 类型替换成 vector 类型,op 改成对 vector 操作;同时应用配套的 pattern,处理向量化过程中的类型转换、slice 合并等。
也就是 原本的 linalg.generic 处理 tensor<16xf32>;向量化后变成对 vector<16xf32> 的算术操作。

4. 向量化后的简化
向量化后可能出现新的简化机会:向量化可能把 tensor.extract_slice 和 vector.transfer_read 之类的操作混在一起;可以合并 tensor 子集操作和 vector 切片操作;产生新的冗余表达式。

transform.apply_patterns to %fv {
  transform.apply_patterns.canonicalization
  transform.apply_patterns.tensor.fold_tensor_subset_ops_into_vector_transfers
}
transform.apply_cse to %fv
transform.structured.hoist_redundant_vector_transfers %fv

# Lowering to LLVM and The Bufferization Hurdle

教程本章讲解:如何把重构好的 IR 降到可执行形式(bufferization + lowering)、性能对比发现 MLIR 版本远慢于 Halide、以及根因分析和第一次修正方案。

1.Bufferization:把 tensor 转成 buffer
给 IR 里每个 tensor 关联一块内存 buffer。tensor 是值语义的(不可变、单赋值),buffer 是内存语义的(可读可写、有地址)。lowering 到 LLVM 之前必须完成这一步。
可以通过 Transform 操作直接做:

%arg1 = transform.bufferization.one_shot_bufferize %arg0 {
  bufferize_function_boundaries = true,
  function_boundary_type_conversion = 1 : i32 }

one_shot_bufferize 是 MLIR 的一次性 bufferization,能处理跨函数、跨模块的 bufferization 决策。
bufferization 只分配 buffer,不负责释放。所以要跑 buffer deallocation pipeline:

%f = transform.structured.match ops{["func.func"]} in %arg1
transform.apply_registered_pass "buffer-deallocation-pipeline" to %f

Transform dialect 可以无缝调用命名 pass 和 pass pipeline: transform.apply_registered_pass 直接跑已注册的 pass;
作用域是函数,不是整个模块:因为模块里还包含 Transform IR 本身,对整个模块跑 pass 会误伤 Transform IR。
但在向量化过程中有隐患,“some operations, in particular tensor.empty may not be bufferizable.”,tensor.empty 只定义形状,不分配实际内存,bufferization 时可能无法处理。解决办法:充分融合(本例就是靠融合消除了 tensor.empty);或用 transform.bufferization.eliminate_empty_tensors 删除只用于定义大小的 tensor.empty;或用 transform.bufferization.empty_tensor_to_alloc_tensor 把 tensor.empty 物化成临时 buffer。
本例因为融合充分,可以直接 bufferize。

2.bufferization 后的简化与向量 lowering
bufferization 后,IR 里出现了新的简化机会,也需要把高层的 vector 操作 lower 成更简单的原语。
先来通用简化,canonicalization + CSE,清理 bufferization 引入的冗余。:

%fb = transform.structured.match ops{["func.func"]} in %arg1
transform.apply_patterns to %fb {
  transform.apply_patterns.canonicalization
}
transform.apply_cse to %fb

vector lowering:

transform.apply_patterns to %fb {
  transform.apply_patterns.vector.lower_contraction
    lowering_strategy = parallelarith
  transform.apply_patterns.vector.lower_transfer
    max_transfer_rank = 1
  transform.apply_patterns.vector.lower_transpose
    lowering_strategy = eltwise
  transform.apply_patterns.vector.lower_shape_cast
}

四组 pattern,分别 lowering: lower_contraction :把向量收缩(如 vector.contract)lower 成并行的算术操作; lower_transfer :把 vector.transfer_read/write lower 成更底层的访存, max_transfer_rank = 1 表示最多处理一维 transfer; lower_transpose :把向量转置 lower 成逐元素操作; lower_shape_cast :把向量形状转换 lower 成底层操作。

transfer-to-scf 和 alloc-to-alloca

transform.apply_patterns to %fb {
  transform.apply_patterns.vector.transfer_to_scf
  transform.apply_patterns.memref.alloc_to_alloca
}
transform.bufferization.buffer_loop_hoisting %fb

该过程单独一次 sweep,没有和 vector lowering 放在一起,是因为 transfer_to_scf 和 前面的 lower_transfer 作用于同类操作,如果放在同一个 sweep 里会冲突,所以分开。
另外, transfer_to_scf 可能在循环深处产生临时 buffer 分配,导致灾难性性能。所以: alloc_to_alloca 把堆分配改成栈分配; buffer_loop_hoisting 把这些分配从循环里 hoist 出去。

最终清理:

transform.apply_patterns to %fb {
  transform.apply_patterns.memref.fold_memref_alias_ops
  transform.apply_patterns.canonicalization
}
transform.apply_cse to %fb

fold_memref_alias_ops 简化 buffer aliasing 操作,避免地址计算过于复杂。再加 canonicalization 和 CSE。

3.bufferization 的「不可逆性」和它在流程中的位置
bufferization 是跨过程(inter-procedural)的,处理整个模块;它会让之前所有 handle 失效,包括循环 handle;所以它通常是变换序列的后期步骤,在不需要精确 targeting 的时候做;之后的变换通常是模块级或函数级的 pattern-based lowering,可以看作「用 Transform dialect 写成的 pass pipeline」。

以上得到的 IR,可以完全 lower 到 LLVM dialect,再生成 LLVM IR,交给 LLVM 编译成可执行文件。

4. 性能对比:MLIR 版本远慢于 Halide
MLIR 生成代码:约 420ms,14 GFlops,只有理论峰值的 22%;Halide 生成代码:约 120ms,77% 峰值;Halide 比 MLIR 快 3.5 倍。
计算量:约 5.9 × 10^9 浮点操作;单核理论峰值约 64 GFlops(16 向量宽度 × 2 FMA 单元 × 2 GHz)。
对比汇编代码。
MLIR 版本:vfma 之间夹杂大量访存:

vmovups       -192(%r10), %zmm0
vbroadcastss  -1536(%rdi,%r9), %zmm1
vmovups       112(%rsp), %zmm2
vfmadd231ps   %zmm1, %zmm0, %zmm2
vmovups       %ymm2, 112(%rsp)
vextractf64x4 $1, %zmm2, 144(%rsp)

每次 vfma 前要加载两个操作数,结果还要写回栈,延迟高。

Halide 版本:紧凑的 vfma + vbroadcast 块:

vbroadcastss    -1536(%rsi,%rbx), %zmm25
vmovups         -192(%rdi), %zmm26
vmovups         -128(%rdi), %zmm27
vmovups         -64(%rdi), %zmm28
vmovups         (%rdi), %zmm29
vfmadd231ps     %zmm25, %zmm26, %zmm24
vfmadd231ps     %zmm25, %zmm27, %zmm23
vfmadd231ps     %zmm25, %zmm28, %zmm22
vfmadd231ps     %zmm25, %zmm29, %zmm21

一个 vbroadcast 后面跟 4 个 vfma,两个操作数常驻寄存器,只有一个是内存加载,效率高。
分析原因,是因为过早 unroll。
也就是说:前面「Explicit Loop Unrolling」一节里,我们在调度早期就 unroll 了 xi, ci 循环;unroll 导致循环体被复制多份,每份都有自己的 tensor.extract_slice/vector.transfer_read;这些操作在后续 lowering 中变成向量访存;结果就是 load/FMA 交错。
更深层的原因:tensor 和 vector 是单赋值(single-assignment)的:每次更新都产生新值,形成很长的访问 - 更新链。unroll 把这条链拉得更长,下游编译器和底层变换无法再简化。

5. 修正,把 unroll 推迟到 bufferization 之后
bufferization 让 handle 失效,理想做法是 bufferization 后再 unroll,但 bufferization 会让所有 loop handle 失效,包括我们想 unroll 的循环。
解决方法:bufferization 后重新 match。

  • 把 tiling 产生的循环从 scf.for 改成 scf.forall:用 tile_using_forall 而不是 tile,这样循环种类单一,好 match;
  • bufferization 后重新 match 所有 scf.forall;
  • 用 transform.loop.forall_to_for 把 scf.forall 转成单迭代器的 scf.for;
  • 再对这些 scf.for 做 unroll。
%foralls = transform.structured.match ops{["scf.forall"]} in %arg1
%xi_bias, %ci_bias = transform.loop.forall_to_for %xi_ci_bias
%xi_conv, %ci_conv = transform.loop.forall_to_for %xi_ci_conv
%xi_relu, %ci_relu = transform.loop.forall_to_for %xi_ci_relu
%xi_comb, %ci_comb = transform.loop.forall_to_for %xi_ci_comb

然后可以把 unroll 移到序列后面。
修正后:核心 vfma 计算和 Halide 几乎一样,运行时间约 120ms,与 Halide 持平。这证明,根因确实是过早 unroll,推迟 unroll 就能解决问题。

# Multi-Dimensional Vectors to the Rescue

前面「推迟 unroll 到 bufferization 之后」的方案虽然有效,但违背了 Transform dialect 用 handle 链式变换的初衷;而真正优雅的解法是 —— 根本不手动 tiling、re-match、unroll,直接依赖 MLIR 多维向量的自动展开,性能甚至超过 Halide。

re-make 违背了初衷
前一节通过「bufferization 后重新 match scf.forall,转成 scf.for,再 unroll」达到了和 Halide 相当的性能;但这个做法部分违背了 Transform dialect 的设计目的 —— 用 handle 链式变换;因为 bufferization 让 handle 失效,只能重新 match,这就退回到了「在 IR 里查找目标」的模式,失去了 handle 链的精确性和稳定性。
也就是说:重新 match + unroll 这一步其实不必要,它只是作为「如何构造目标循环结构」的练习。真正的最优方案不需要它。

多维向量会自动展开
MLIR 里的多维向量操作,在 lowering 到目标硬件时,会自动被展开(unroll)和拆分(split)成硬件支持的向量
也就是说,一个 vector<5x64xf32> 的逐元素操作:在 MLIR level 被拆成 5 个 vector<64xf32> 操作;加上一些向量值操作,把结果重新组合成 vector<5x64xf32>。
到了 LLVM level,vector<64xf32> 又被拆成 4 个 vector<16xf32> 操作,正好对应前面手动 unroll 得到的 4 × 5 = 20 个 16 元素向量操作。
也就是说:多维向量的自动展开,效果等价于「先物化 5×4 循环嵌套,再完全 unroll」。但它是自动的、在 lowering 时发生的,不需要在调度里手动做。

最后一阶段可以删掉
最后的 tile_using_forall [0, 0, 1, 16](物化 xi, ci 循环);bufferization 后重新 match scf.forall; forall_to_for 转成 scf.for;transform.loop.unroll 展开;全都不需要了。直接让 op 处理多维向量,lowering 时自动展开。

效果:比 Halide 还快
汇编特点:所有 vbroadcast 被分组到 vfmadd231 之前;其他结构和 Halide 类似。
最终版本:比前一版和 Halide 快约 8%;达到 84% 单核峰值。
原因:中间表示更短、更简洁(没有手动 tiling、unroll 产生的大量重复操作);存在大向量操作(vector<5x64xf32>),让编译器能做更激进的地址计算优化和加载位置优化;最终生成的代码质量更高。

# 后记

请你务必,一而再,再而三,三而不竭,千次万次,毫不犹豫,救自己于这世间水火中。  
                                       —— 罗翔

本博客目前以及可预期的将来都不会支持评论功能。各位大侠如若有指教和问题,可以在我的 github 项目 或随便一个项目下提出 issue,并指明哪一篇博客,看到一定及时回复!

Edited on

Give me a cup of [coffee]~( ̄▽ ̄)~*

XianMu WeChat Pay

WeChat Pay

XianMu Alipay

Alipay