添加Permute倒置Rewrite Pattern时执行多次重写

Viewed 93

根据社区发布的pattern添加案例教程,我尝试在Relu算子中添加了Permute倒置相关的pattern,我写了一个空的Pattern,仅仅输出一条语句,但是在测试时发现这里的语句被执行了11次,我感到十分困惑,这里不应该是只执行一次吗?
下面是我的测试用例生成的IR

#loc = loc(unknown)
module attributes {module.chip = "ALL", module.name = "permutereluchange", module.platform = "ONNX", module.state = "TOP_F32", module.weight_file = "permutereluchange_top_f32_all_origin_weight.npz"} {
  func.func @main(%arg0: tensor<1x16x128x128xf32> loc(unknown)) -> tensor<128x128x16x1xf32> {
    %0 = "top.None"() : () -> none loc(#loc)
    %1 = "top.Input"(%arg0) : (tensor<1x16x128x128xf32>) -> tensor<1x16x128x128xf32> loc(#loc1)
    %2 = "top.Permute"(%1) {order = [3, 2, 1, 0]} : (tensor<1x16x128x128xf32>) -> tensor<128x128x16x1xf32> loc(#loc2)
    %3 = "top.Relu"(%2) : (tensor<128x128x16x1xf32>) -> tensor<128x128x16x1xf32> loc(#loc3)
    return %3 : tensor<128x128x16x1xf32> loc(#loc)
  } loc(#loc)
} loc(#loc)
#loc1 = loc("input")
#loc2 = loc("transpose_output_Transpose")
#loc3 = loc("output_Relu")

我希望完成该Pattern以交换算子,我打算在Relu中编写逻辑以新增替换旧算子达到置换的目的,是否这里有其他需要注意的地方,期待回复。

1 Answers

执行多次是正常的。但是这里也有问题。

在执行rewrite pattern时返回值有success和failure之分。
当返回为success时,代表mlir文件被修改,此时会再次执行所有的pattern。
当返回为failure时,代表mlir文件未被修改,就停止执行pattern。

你这里没有修改图,却返回success,会导致重复执行pattern。没有改图,应该返回failure。

但是这里执行11次,是因为mlir本身的机制导致,如果图未改变,最多执行10次就会返回。

WeChat8e0bd4d65f81100123b359086c5a86ed.png