TVM TIRx 原生 CUDA 编译与检查实战指南
TVM TIRx 原生 CUDA 编译与检查实战指南
导读
在 TVM 的 TIRx 原生编程体系中,写好的 PrimFunc 只是起点,如何把它编译成可调用的 CUDA Executable、如何检查生成的 CUDA C 源码、如何借助运行时调试手段定位问题,是每个内核开发者都要跨过的关卡。本文以 docs/tirx/native_basics/cuda/compiling.rst 为主线,结合仓库中 TIRx 编译流水线源码,完整讲解 tvm.compile(..., tir_pipeline="tirx") 的编译路径、目标架构自动探测与回退规则、IR 与 CUDA 源码的检查方法,以及从简单到复杂的原生内核进阶路线,读完即可在自己的 CUDA 设备上跑通"写 → 编译 → 检查 → 运行"全流程。
一、编译入口:把 PrimFunc 包装成 IRModule
TIRx 的编译以 IRModule 为最小输入单元。一个用 @Tx.prim_func 写好的设备函数(如 scale 内核)需要先被包装进一个具名模块,"main" 是编译器的入口点符号,也是后续调用时执行的目标:
import numpy as np
import tvm
from tvm.script import tirx as Tx
@Tx.prim_func
def scale(A_ptr: Tx.handle, B_ptr: Tx.handle):
A = Tx.match_buffer(A_ptr, (256,), "float32")
B = Tx.match_buffer(B_ptr, (256,), "float32")
Tx.device_entry() # 其下代码全部在设备端执行
bx = Tx.cta_id([1]) # 1 个 block(blockIdx)
tx = Tx.thread_id([256]) # 每 block 256 线程(threadIdx)
B[tx] = A[tx] * Tx.float32(2.0)
# 通过 TIRx 流水线编译为 CUDA Executable
exe = tvm.compile(tvm.IRModule({"main": scale}),
target=tvm.target.Target("cuda"), tir_pipeline="tirx")
这里的 tvm.IRModule({"main": scale}) 构建一个只含单个函数的模块——在编译期,"main" 既是构建的入口,也是运行时调用的符号名(详见 first_kernel.rst 对周边调用的逐条拆解)。
1.1 关键参数 tir_pipeline="tirx"
tir_pipeline 选择执行哪条后端 lowering 流水线。从源码看,python/tvm/driver/build_module.py 中的 tvm.compile 最终调用 tvm.tirx.build(mod, target, pipeline=tir_pipeline),而流水线由 python/tvm/tirx/compilation_pipeline.py 的 PIPELINE_MAP 注册表提供:
PIPELINE_MAP = {"default": default_tir_pipeline, "tirx": tirx_pipeline}
"tirx":TIRx 专属流水线,包含 tile-primitive dispatch 与清理(LowerTIRx)→ host/device 拆分 → finalize 三阶段,是本文讨论的重点。"default":会按目标平台自动选择——对 OpenCL Adreno 走"adreno",其余走"s_tir"(get_default_tir_pipeline,见 compilation_pipeline.py)。
还可以把 tir_pipeline 直接传一个自定义 tvm.transform.Pass 或可调用对象,实现完全自定义的编译流程;传入未注册的字符串名会抛出 ValueError 并列出候选流水线(compilation_pipeline.py)。
1.2 with target: 上下文同样可用
除了把 target 作为参数传入,tvm.compile 也会遵循 Target.current() 环境上下文(build.py)。因此下面两种写法等价,后者让内核自动拾取当前 target 上下文:
with tvm.target.Target("cuda"):
exe = tvm.compile(tvm.IRModule({"main": scale}), tir_pipeline="tirx")
在 with target: 块内,未显式携带 target 属性的 PrimFunc 会被绑定到该目标(BindTarget pass,build.py),这在多函数、多目标模块的编译场景中非常有用。
二、CUDA 目标架构:自动探测与回退规则
当 CUDA 设备处于激活状态时,target "cuda" 会自动探测当前设备的计算架构,例如较新的设备会得到 sm_100a。如果编译时没有可用设备,TVM 会发出警告并回退到 sm_50 这一保守基线架构。
这一规则直接决定了两个实操要点:
- 交叉编译必须显式指定架构。在没有目标 GPU 的机器上为特定显卡编译时,需要补上
-arch=...,例如:
target = tvm.target.Target("cuda -arch=sm_90")
- 回退基线不足以承载新指令。当内核中使用了仅在新架构上存在的指令(如 Blackwell 的
tcgen05.*MMA、TMAcp.async.bulk.tensor等,见 threads_sync.rst)时,sm_50回退会失败或生成无法运行的代码——此时必须显式指定不低于实际硬件代际的架构。
从源码结构看,CUDA 后端的架构信息贯穿整个编译链:split_host_device_mods 依据函数属性中的 target(含 arch、kind、keys 等字段)把设备函数分组到各自的目标模块(build.py),最终由 target.build.cuda 全局函数触发 CUDA 代码生成。
三、TIRx 降低流水线:编译过程在做什么
tir_pipeline="tirx" 背后的流水线定义在 python/tvm/tirx/compilation_pipeline.py,其主干按顺序执行以下 pass:
| 阶段 | Pass | 作用 |
|---|---|---|
| 预处理 | tirx.transform.LowerTIRx |
将 tile-primitive dispatch 与高层结构降低为底层 TIR 语句 |
| 线程绑定 | s_tir.transform.UnifyThreadBinding |
统一线程/block 绑定语义 |
| 化简 | tirx.transform.StmtSimplify |
语句级化简(出现两次,前后各一次) |
| 清理 | tirx.transform.LowerTIRxOpaque |
消除 TIRx 不透明结构 |
| 布局 | tirx.transform.FlattenBuffer |
展平 Buffer 存储 |
| 类型 | tirx.transform.BF16ComputeLegalize / NarrowDataType(32) |
BF16 计算合法化、数据类型窄化到 32 位 |
| 优化 | tirx.transform.VectorizeLoop / UnrollLoop |
循环向量化(默认开启,tir.disable_vectorize 可关闭)与展开 |
| 公共子表达式 | tirx.transform.CommonSubexprElim |
默认开启,tir.disable_cse_tir 可关闭 |
| 精度 | tirx.transform.FP8ComputeLegalize |
FP8 计算合法化 |
| 校验 | tirx.transform.VerifyMemory |
内存访问合法性验证 |
| 拆分 | tirx.transform.AnnotateEntryFunc + SplitHostDevice |
标注入口函数,拆分为 host(CPU)与 device(GPU)两部分 |
| 后端 | cuda_transforms.LowerIket |
降低 CUDA IKET(内核模板相关)结构 |
| 打包 | tirx.transform.MakePackedAPI |
生成 packed 调用接口 |
| 存储 | tirx.transform.FP8StorageLegalize / BF16StorageLegalize |
FP8/BF16 存储格式合法化 |
流水线完成后,进入 finalize 阶段:host 侧执行 LowerTVMBuiltin + LowerIntrin,device 侧执行 LowerWarpMemory + StmtSimplify + LowerIntrin(compilation_pipeline.py)。
完整调用链可以概括为(python/tvm/tirx/build.py 的 tirx.build):
PrimFunc自动包装为 IRModule;- 确定目标与 host 目标(host 默认
llvm,无 LLVM 时回退c); BindTarget绑定目标属性;- 取流水线
tirx并应用; split_host_device_mods拆出 host 模块与按 target 分组的设备模块字典;- 分别施加 host/device finalize passes;
tir_to_runtime逐个调用target.build.<kind>生成设备模块并import_module进 host 模块,最终得到运行时的Module。
四、检查编译结果:IR 与生成的 CUDA C
编译完成后有三类检查手段,覆盖"高级 IR → 最终源码"两个层级:
4.1 查看 TIRx IR
scale.show() # 美化打印 TIRx(TVMScript 形式)
print(scale.script()) # 同样的内容,以字符串形式返回
.show() 与 .script() 打印的是 PrimFunc 的 TVMScript 表示,用于确认降低前的内核逻辑;这是定位"写错逻辑"而非"写错编译"问题的第一道检查点。
4.2 查看生成的 CUDA C
# 从编译好的 Executable 中取生成的 CUDA C 源码
print(exe.mod.imports[0].inspect_source())
这里依赖 Executable 的模块结构:exe.mod 是底层运行时 Module,exe.mod.imports[0] 是被导入的设备(CUDA)模块,其 .inspect_source() 返回生成的 CUDA C 文本。对上述 scale 内核,输出大致为(省略样板代码):
extern "C" __global__ void __launch_bounds__(256)
scale_kernel(float* __restrict__ A_ptr, float* __restrict__ B_ptr) {
int tx = ((int)threadIdx.x);
B_ptr[tx] = A_ptr[tx] * 2.0f;
}
可以看到 B[tx] = A[tx] * 2.0 被直接映射为按 threadIdx.x 索引的逐元素写——这是验证"TIRx 源码 → 最终内核"映射关系最直观的手段(完整示例见 first_kernel.rst)。
4.3 Executable 的延迟 JIT 机制
从 python/tvm/runtime/executable.py 的源码看,tvm.compile 返回的 Executable 并不总是一步到位:__call__ 会触发 jit(),后者检查模块导入树中是否存在 "c" 或 "static_library" 这类不可直接运行的模块;若存在,则先 export_library 导出为动态库再 load_module 加载(executable.py)。这解释了为什么包含 CUDA 源码/对象的 Executable 在首次调用时会经历一次编译链接——缓存后的再次调用则直接走 self._jitted_mod。force_recompile=True 可强制重编。
五、运行时调试辅助:Tx.print_buffer 与 Tx.hint
TIRx 提供了两个调试利器(对应源码定义在 python/tvm/tirx/op.py 与 python/tvm/tirx/script/builder/ir.py):
1. Tx.print_buffer——内核内运行期 printf
Tx.print_buffer(C.data, "float32", False, False, 1, (M,))
在 CUDA 内核中直接对 Buffer 发出运行期 printf,参数依次为:Buffer 变量、数据类型、is_string、is_scalar、维度数、形状。用于在设备端现场打印数据,排查数值错误。
2. Tx.hint——结构化提示
Tx.hint("message") # 作为语句使用
with Tx.hint("message"): # 或作为 with 块
...
Tx.hint 为代码附加结构化提示,其关键特性是在 script 往返(round-trip)过程中得以保留——写入的提示不会在打印/重新解析 TIRx 时丢失,适合把调试信息、性能注解等元数据嵌入 IR。
六、从简单到复杂:原生内核的进阶路线
原文给出了一条天然的原生(native)演进路径,每一级只增加一种能力:
| 级别 | 新增能力 | 关键原语 |
|---|---|---|
| 1. Elementwise | 首个内核 | device_entry + thread_id + 带守卫的存储 |
| 2. Shared-memory reduction | 共享内存与块级屏障 | Tx.alloc_shared + cta_sync 分隔的树形归约 |
| 3. Warp / block reduction | 跨 lane/warp 合并部分结果 | Tx.tvm_warp_shuffle_xor 或 Tx.cuda.cta_sum(warp all-reduce 完整示例见 threads_sync.rst) |
| 4. Async pipeline | 加载与计算重叠 | Tx.ptx.cp.async_(或 TMA cp.async.bulk.tensor)+ Tx.ptx.mbarrier.* / Tx.cuda.mbarrier_wait |
其中 第 2 级 给出了完整可运行的示例——一个 256 元素的 block 求和,通过共享内存树形归约实现(含共享缓冲、cta_sync、while 循环与线程谓词):
@Tx.prim_func
def block_sum(A_ptr: Tx.handle, out_ptr: Tx.handle):
A = Tx.match_buffer(A_ptr, (256,), "float32")
out = Tx.match_buffer(out_ptr, (1,), "float32")
Tx.device_entry()
bx = Tx.cta_id([1])
tx = Tx.thread_id([256])
sm = Tx.alloc_shared((256,), "float32")
sm[tx] = A[tx]
Tx.cuda.cta_sync()
s = Tx.alloc_local((1,), "int32")
s[0] = 128
while s[0] >= 1:
if tx < s[0]:
sm[tx] += sm[tx + s[0]]
Tx.cuda.cta_sync()
s[0] = s[0] // 2
if tx == 0:
out[0] = sm[0]
exe = tvm.compile(tvm.IRModule({"main": block_sum}),
target=tvm.target.Target("cuda"), tir_pipeline="tirx")
a = torch.arange(256, device="cuda", dtype=torch.float32)
out = torch.zeros(1, device="cuda")
exe(a, out) # out[0] == 32640.0(0..255 之和)
这段代码同时演示了本文的核心知识点:Tx.alloc_shared 共享内存分配、Tx.cuda.cta_sync 块级屏障、alloc_local 局部标量配合 while 循环实现归约步长折半、以及 tvm.compile + tir_pipeline="tirx" 的标准编译调用。
值得注意的还有张量互操作:编译出的 Executable 可直接接收 CUDA torch 张量(通过 TVM FFI tensor interop,无需显式转换),例如 exe(a, b) 后 torch.testing.assert_close(b, a * 2) 即可完成结果校验(详见 first_kernel.rst)。
完整的 tile 级 GEMM/attention 进阶阶梯(sync → TMA → warp specialization → 2-CTA cluster)正是建立在这些原生惯用法与可 dispatch 的 tile primitive 之上,后者详见 tile_primitives 文档。
七、下一步
- Layout(TileLayout)——Buffer 如何映射到物理资源;
- Tile Primitives——这些原生惯用法最终降低成的可 dispatch 算子;
- 配套概念:threads_sync(CUDA 内建函数与 PTX)、first_kernel(首个内核完整流程);
- API 参考:CUDA helpers 与 PTX forms。
结语
本文从 tvm.compile 的入口参数出发,完整还原了 TIRx 流水线在 compilation_pipeline.py 与 build.py 中的真实执行路径,覆盖了 CUDA 架构自动探测与回退、IR 与 CUDA C 的多层检查、Executable 的延迟 JIT、以及 Tx.print_buffer / Tx.hint 两类运行时调试手段,最后以共享内存树形归约为例串起从简单到复杂的内核演进路线。掌握了这些,你就能在 TIRx 下独立完成任意原生 CUDA 内核的编写、编译、检查与调试闭环。