[MLIR][Linalg] `--convert-arith-to-llvm` rewrites a `linalg.matmul` body and leaves the op unverifiable
Reproducer
small.mlir
func.func @f(%a: memref<2x3xi32>, %b: memref<3x2xi32>, %c: memref<2x2xi32>) {
linalg.matmul ins(%a, %b : memref<2x3xi32>, memref<3x2xi32>) outs(%c : memref<2x2xi32>)
return
}
To reproduce:
mlir-opt small.mlir -o /dev/null # parses and verifies
mlir-opt small.mlir --convert-arith-to-llvm
Crash:
small.mlir:2:3: error: expected add/mul op in the body
linalg.matmul ins(%a, %b : memref<2x3xi32>, memref<3x2xi32>) outs(%c : memref<2x2xi32>)
^
small.mlir:2:3: note: see current operation:
"linalg.matmul"(%arg0, %arg1, %arg2) <{indexing_maps = [affine_map<(d0, d1, d2) -> (d0, d2)>, affine_map<(d0, d1, d2) -> (d2, d1)>, affine_map<(d0, d1, d2) -> (d0, d1)>], operandSegmentSizes = array<i32: 2, 1>}> ({
^bb0(%arg3: i32, %arg4: i32, %arg5: i32):
%0 = "llvm.mul"(%arg3, %arg4) <{overflowFlags = 0 : i32}> : (i32, i32) -> i32
%1 = "llvm.add"(%arg5, %0) <{overflowFlags = 0 : i32}> : (i32, i32) -> i32
"linalg.yield"(%1) : (i32) -> ()
}) : (memref<2x3xi32>, memref<3x2xi32>, memref<2x2xi32>) -> ()
@llvm/issue-subscribers-mlir-linalg
Author: Xintong Zhou (zxt5)
small.mlir
func.func @<!-- -->f(%a: memref<2x3xi32>, %b: memref<3x2xi32>, %c: memref<2x2xi32>) {
linalg.matmul ins(%a, %b : memref<2x3xi32>, memref<3x2xi32>) outs(%c : memref<2x2xi32>)
return
}
To reproduce:
mlir-opt small.mlir -o /dev/null # parses and verifies
mlir-opt small.mlir --convert-arith-to-llvm
Crash:
small.mlir:2:3: error: expected add/mul op in the body
linalg.matmul ins(%a, %b : memref<2x3xi32>, memref<3x2xi32>) outs(%c : memref<2x2xi32>)
^
small.mlir:2:3: note: see current operation:
"linalg.matmul"(%arg0, %arg1, %arg2) <{indexing_maps = [affine_map<(d0, d1, d2) -> (d0, d2)>, affine_map<(d0, d1, d2) -> (d2, d1)>, affine_map<(d0, d1, d2) -> (d0, d1)>], operandSegmentSizes = array<i32: 2, 1>}> ({
^bb0(%arg3: i32, %arg4: i32, %arg5: i32):
%0 = "llvm.mul"(%arg3, %arg4) <{overflowFlags = 0 : i32}> : (i32, i32) -> i32
%1 = "llvm.add"(%arg5, %0) <{overflowFlags = 0 : i32}> : (i32, i32) -> i32
"linalg.yield"(%1) : (i32) -> ()
}) : (memref<2x3xi32>, memref<3x2xi32>, memref<2x2xi32>) -> ()
Not sure this should happen in the first place. You want rewrites to look inside regions, for example, on an scf.loop or linalg.generic op, but not on linalg.matmul, even though it's just another region with arith ops inside. The named ops have special semantics. Even if the rewrite hadn't produced "unverifieable code", it could still be wrong semantics (doesn't represent a matmul anymore / can't be converted to category form / etc.).
@ftynse @joker-eph @banach-space @javedabsar1
Do we differentiate the region type (opaque, traversable, etc)?
Why does linalg.matmul carry a region in the first place, if the body must always consist of arith.mul and arith.add?
I think I see why this happens and there is a missing interface implementation.
Let me explain. Above example uses convert-arith-to-llvm and one could say use convert-to-llvm, but that too fails currently.
./bin/mlir-opt --convert-to-llvm try.mlir
try.mlir:2:3: error: expected add/mul op in the body
linalg.matmul ins(%a, %b : memref<2x3xi32>, memref<3x2xi32>) outs(%c : memref<2x2xi32>)
^
Likely the linalg dialect does not implement ConvertToLLVMPatternInterface, so only the ops inside region-body of linalg.matmul get converted arith.add -> llvm.add. But then linalg.matmul implements ContractionOpInterface which has a verifier verifyContractionInterface that checks the body for arith::MulIOp/arith::AddIOp ==> https://github.com/llvm/llvm-project/blob/main/mlir/lib/Dialect/Linalg/IR/LinalgInterfaces.cpp#L576 and https://github.com/llvm/llvm-project/blob/main/mlir/lib/Dialect/Linalg/IR/LinalgInterfaces.cpp#L547. It looks for arith.add/mul which are no longer there.
of course, a lowering like this works:
// ./bin/mlir-opt -linalg-generalize-named-ops -convert-linalg-to-loops --convert-arith-to-llvm try.mlir
module {
func.func @f(%arg0: memref<2x3xi32>, %arg1: memref<3x2xi32>, %arg2: memref<2x2xi32>) {
...
scf.for %arg3 = %1 to %3 step %5 {
scf.for %arg4 = %1 to %3 step %5 {
scf.for %arg5 = %1 to %7 step %5 {
%8 = memref.load %arg0[%arg3, %arg5] : memref<2x3xi32>
%9 = memref.load %arg1[%arg5, %arg4] : memref<3x2xi32>
%10 = memref.load %arg2[%arg3, %arg4] : memref<2x2xi32>
%11 = llvm.mul %8, %9 : i32
..
I can try to fix the issue if no one else comes forward.
Likely the linalg dialect does not implement ConvertToLLVMPatternInterface
That sounds right, and the linalg dialect should not implement that interface. There is no direct lowering path from linalg to LLVM.
Why does
linalg.matmulcarry a region in the first place, if the body must always consist ofarith.mulandarith.add?
This is a property of all StructuredOps in Linalg. The idea was to keep it like a generic but with different syntax and easier pattern matching (per op, not generic properties). The vast majority of Linalg ops are structured, and this issue occurs with all of those.
Likely the linalg dialect does not implement ConvertToLLVMPatternInterface
That sounds right, and the
linalgdialect should not implement that interface. There is no direct lowering path fromlinalgto LLVM.
Right, there's linalg-to-loops, which lower the structured ops to SCF + arith/maths, and then that to LLVM. I agree it's not a good idea to have also an LLVM lowering (bypassing SCF).
This is why I was thinking about an opaque region type instead, so that a generic lower to LLVM pass leaves the Linalg ops alone, until a linalg-to-loops pass can run.
Without a default pass pipeline, it's not reasonable to expect linalg-to-loops to always run before convert-to-llvm.
This is why I was thinking about an opaque region type instead, so that a generic lower to LLVM pass leaves the Linalg ops alone, until a linalg-to-loops pass can run.
Sounds reasonable.
This is a property of all StructuredOps in Linalg. The idea was to keep it like a generic but with different syntax and easier pattern matching (per op, not generic properties).
Perhaps converting named Linalg Ops to LLVM should trigger a hard fail?
Is this problem actually specific to the ConvertToLLVM pass? Any pass that matches+rewrites the ops inside the linalg.matmul will produce invalid IR. I don't really see a way to fix this issue.
This is a property of all StructuredOps in Linalg. The idea was to keep it like a generic but with different syntax and easier pattern matching (per op, not generic properties).
I would have expected a mechanism based on op interfaces instead of these "dummy" ops. (E.g. an op interface method that returns or builds the region ops on demand.) I feel like this current implementation violates the IR verifier best practice to only verify local aspects of an operation. But it is what it is...
Is this problem actually specific to the
ConvertToLLVMpass? Any pass that matches+rewrites the ops inside thelinalg.matmulwill produce invalid IR.
Correct. It's a problem to any pass that inspects Linalg structured op's region and does things that affects it's own verifier. Some passes are "fine", for example if they just change the ops inside generics while keeping the same dialects (ex. inst-combine-like), while the LLVM conversion inserts illegal instructions to the body.
This is not a problem that only affects Linalg. They affect any operation (of any dialect) that has a region carrying additional semantics. This does not affect SCF because the loops don't carry semantics beyond loop structure, so the payload is irrelevant. The problem is the assumption that the body is independent from the encompassing op as a requirement for dialect design.
This has not been the design of Linalg for a very long time. The verifier may have been a more recent development, to make sure we are carrying that semantics across rewrites, but the assumption was there from the get-go.
I feel like this current implementation violates the IR verifier best practice to only verify local aspects of an operation.
It does not. The region is part of the operation, and the verifier is just making sure it's within the accepted bounds.
I would have expected a mechanism based on op interfaces instead of these "dummy" ops. (E.g. an op interface method that returns or builds the region ops on demand.)
Those operations were created long before we had forms and morphisms in Linalg. Creating "on demand" made no sense, because demand was at every rewrite, so always having a region or building a new region for every rewrite is equivalent (with the former cheaper).
The two alternatives I see forward, none of them are simple:
Opaque Named Operation
We remove all named operations from the StructuredOp (basically killing the interface, since only generic will remain), make them into full ops without a body, and create a massive conversion mechanism to/from generic and category forms, that reconstruct the whole thing every time via op interfaces. (similar to @matthias-springer proposal).
Pros:
- Existing rewrite / transform don't need to change (except the ones that previously worked with Linalg and will break)
Cons:
- Heavy change inside Linalg, hard to do, hard to verify (tablegen, C++, tests, forms, morphisms)
- Explicit re-implementation of the existing interfaces (tiling, fusion) for every named op
- Explicit duplication for every little change (and hard for newcomers to see they need to do this)
Opaque Regions
We create a new attribute for "opaque regions" where dialects want full control of what's inside because the semantic matters. This means rewrites are not allowed to descend into those regions (as if the op had no regions). This may be a small change to an interface and a default implementation for all existing dialects that Linalg simply overrides.
Alternatively, we could even create a new type of region that the current rewrites don't see (like getOpaqueRegion() instead of getRegion()). But I'd prefer an interface solution, or the code will get brittle fast.
Pros:
- No big changes anywhere in code / tablegen / tests
- Other dialects can expand their verifiers to look inside their regions that carry semantics
Cons:
- New attribute / region type affects all dialects (mitigated by default behaviour)
Perhaps converting named Linalg Ops to LLVM should trigger a hard fail?
I agree that one should never try to lower Linalg to LLVM directly. Doing so is much more likely that the user doesn't know they have to lower to SCF first, and have failed to add that pass. This is not just named ops, but any Linalg op will have the same problem.
But how do we say "don't run this rewrite on this dialect" in a reasonable way? And how do we guarantee someone else, with a similar rewrite that is not in the "non-grata table" also gets stopped?
It's also not just LLVM. In the matmul case, the verifier is expecting mul + add in the body (accumulating on the output). Adding LLVM ops, even though they're still mul + add chain, breaks validation because they're not the expected ones (arith).
For example, if a rewrite adds a bunch of ops (casts etc) but leaves the mul/add chain intact: all good. However, if a rewrite removed the add (thinking it's redundant), then hard fail --> not a matmul.
The general problem is simply that "some operations have regions and those regions have specific semantics that must be retained to continue to implement the same operation". Not all rewrites are valid in those cases and it's up to the pass (or the rewrite, or the fold, or the conversion) to "know what it is doing".