跳转至

nn.SourceModule 接多输出 extern:两个坑

在 mlc-vla 里把 FlashRT 的 residual_add_rms_norm_fp8 接成 extern 时踩到。这个核出两个张量(fp16 新残差 + e4m3 量化激活),而之前接的 GeGLU 只出一个。

坑 1:shape 函数返回 list 会直接 TypeError

按 nn.SourceModule 的约定,symbols 里每个符号配一个 shape/dtype 推断函数。多输出的自然写法是返回 list:

def _shape_res_rms_fp8(residual, x, weight, scale, eps):
    return [
        nn.Tensor.placeholder(residual.shape, residual.dtype),
        nn.Tensor.placeholder(residual.shape, "float8_e4m3fn"),
    ]

报错:

TypeError: Mismatched type on argument #2 when calling:
  relax.op.call_dps_packed(0: ir.RelaxExpr, 1: relax.expr.Tuple, 2: Array<relax.TensorStructInfo>)
Expected `Array<relax.TensorStructInfo>` but got `Array[index 0: relax.TupleStructInfo]`

原因在 tvm/relax/frontend/nn/extern.py 的 ExternModule.__getitem__:

rx_outputs_sinfo = _convert(_inference_function(*input_args), "dummy").struct_info

_convert 对 list 会先包成 rx.Tuple,取 .struct_info 得到的是 TupleStructInfo,而 call_dps_packed 要的是 Array<TensorStructInfo>。这条路只支持单输出。

绕法:自己构 call_dps_packed,不动 tvm-relax

def res_rms_fp8(residual, x, weight, scale, eps):
    from tvm import relax, tirx          # 注意这个 fork 里是 tirx,不是 tir
    from tvm.relax.frontend import nn
    from tvm.relax.frontend.nn.core import wrap_nested

    _ensure_registered()   # 仍要把 SourceModule 挂上,它提供符号

    args = relax.Tuple([
        residual._expr, x._expr, weight._expr, scale._expr,
        relax.PrimValue(tirx.FloatImm("float64", float(eps))),
    ])
    out_sinfo = [
        nn.Tensor.placeholder(residual.shape, residual.dtype)._expr.struct_info,
        nn.Tensor.placeholder(residual.shape, "float8_e4m3fn")._expr.struct_info,
    ]
    return wrap_nested(relax.op.call_dps_packed("flashrt_res_rms_fp8", args, out_sinfo),
                       "flashrt_res_rms_fp8")

两点注意:

  • _SYMBOLS 里仍要挂这个符号名,哪怕它的 shape 函数永远不被调用——SourceModule._load 拿 _symbols 的 key 当 func_names 去注册符号(extern.py L73),漏了运行时报 Cannot find ffi::Function。把那个函数体写成 raise AssertionError 加注释说明为什么。
  • wrap_nested 对 TupleStructInfo 的 call 会返回 Python tuple of nn.Tensor,直接解包即可。

C++ 侧签名:输出是展平的尾参

CallTIRMutator 给每个输出各 alloc 一个 tensor,然后

args.insert(args.end(), outs.begin(), outs.end());   // call_tir_rewrite.cc L151

所以是 (输入..., out0, out1),不是收一个 tuple。标量输入(PrimValue)落在输入段末尾:

int _flashrt_res_rms_fp8(DLTensor* residual, DLTensor* x, DLTensor* weight, DLTensor* scale,
                         double eps,                       // PrimValue(float64)
                         DLTensor* res_out, DLTensor* out); // 两个输出

多输出要求每个输出的 shape 都能静态定出来(call_tir_rewrite.cc L117-119 会 ICHECK shape.defined())。

坑 2:shim 里的同目录 #include 找不到文件

SourceModule.compile 把 shim 的内容写到临时目录的 main.cu,然后在那个临时目录里编:

# nn/extern.py L369-377
with tempfile.TemporaryDirectory() as temp_dir_str:
    source_path = temp_dir / f"main{self.source_suffix}"
    source_path.write_text(self.source_code)
    _cc.create_shared(..., cwd=temp_dir)

所以 shim 里 #include "my_kernel.cuh" 解析不到——临时目录里只有 main.cu。加一条 -I 指到 shim 真正所在的目录:

options = nn.SourceModule.get_compile_options("cu") + [
    "-I", str(flashrt_root / "csrc"),
    "-I", str(_SHIM.parent),        # 这条
    f"-gencode=arch=compute_{arch},code=sm_{arch}",
]

坑 3:择路要先查 cfg 的开关,不是只查 available()

flashrt.available() 只回答「编译机上有没有 FlashRT 源码树和 nvcc」,不代表这个包想接 extern。接 extern 会把这段图换成 TVM 看不见内部的黑盒,dlight / cuBLAS 的后续融合机会一并让出,所以按 flashrt.resolve() 的约定它必须由 cfg 显式开启。

择路的第一道闸是 cfg,available() 在后面:

if not mlp.flashrt:          # cfg 开关,第一道
    return None
...
if not (flashrt.available() and flashrt.rms_fp8_supported(x)):
    return None

漏了第一道的症状:flashrt=False 的配置也接上了 extern,图里凭空多出 flashrt_* 调用。单测里数 R.quantize( 出现次数的那类断言会抓到,但如果没有这类测试就会一路带到产物里。

顺带:什么时候该派生一份核而不是直接 include

FlashRT 的 residual_add_rms_norm_fp8_kernel 把新残差写回入参,DPS 不许写输入,所以不能直接 include kernels/norm.cu 用。派生一份改成出参(不增加访存,in-place 本来也要写这一遍),并在文件头逐条记下改了什么、对应原文件哪几行。

只 include kernels/common.cuh(header-only,packed2 / to_f32 / block_reduce_sum 都在里面),不 include 1700 行的 norm.cu,编译仍是秒级。

相关