[MLIR][Vector] Contraction lowering crashes on scalar results after folding a broadcast-like shape_cast
https://github.com/llvm/llvm-project/blob/9dacdcba7468b9a0ebd000b2ce797c2a85bd9319/mlir/lib/Dialect/Vector/Transforms/LowerVectorContract.cpp#L1013
Summary
Combining Vector reduction-to-contract patterns with contraction lowering crashes on a valid scalar-result vector.contract whose left-hand operand is defined by a broadcast-like vector.shape_cast.
The failure is an assertion in ContractionOpLowering::lowerParallel, which unconditionally casts the result type to VectorType even though the result is a scalar. This reproduces with standalone LLVM mlir-opt, using standard Vector and Transform dialect operations.
Reproducer
repro.mlir:
module {
func.func @repro(%x: vector<2xbf16>, %scale: bf16, %acc: bf16) -> bf16 {
%lhs = vector.shape_cast %x : vector<2xbf16> to vector<1x1x2xbf16>
%rhs = vector.broadcast %scale : bf16 to vector<1x1x2xbf16>
%out = vector.contract {
indexing_maps = [affine_map<(d0, d1, d2) -> (d0, d1, d2)>,
affine_map<(d0, d1, d2) -> (d0, d1, d2)>,
affine_map<(d0, d1, d2) -> ()>],
iterator_types = ["reduction", "reduction", "reduction"],
kind = #vector.kind<add>
} %lhs, %rhs, %acc : vector<1x1x2xbf16>, vector<1x1x2xbf16> into bf16
return %out : bf16
}
}
module attributes {transform.with_named_sequence} {
transform.named_sequence @__transform_main(
%root: !transform.any_op {transform.readonly}) {
%func = transform.structured.match ops{["func.func"]} in %root
: (!transform.any_op) -> !transform.op<"func.func">
transform.apply_patterns to %func {
transform.apply_patterns.vector.reduction_to_contract
transform.apply_patterns.vector.lower_contraction
lowering_strategy = "outerproduct"
} : !transform.op<"func.func">
transform.yield
}
}
Command:
mlir-opt repro.mlir \
--transform-interpreter \
--mlir-disable-threading
For comparison, verifying the same file without executing the Transform sequence succeeds with exit code 0:
mlir-opt repro.mlir -o /dev/null
The crashing command also keeps the default input verification enabled. Both pattern sets are applied within a single transform.apply_patterns operation.
Why the input IR is valid
The payload satisfies the Vector operation constraints:
vector.shape_castpreserves the element type and element count:vector<2xbf16>andvector<1x1x2xbf16>both contain twobf16elements. It only adds two leading unit dimensions.vector.broadcastlegally broadcasts a scalarbf16tovector<1x1x2xbf16>.- Both contraction inputs have rank three and shape
(1, 1, 2). Their identity indexing maps each have three inputs, three outputs, and no symbols. The accumulator map has three inputs and no outputs, matching the scalar accumulator. - All three iterators are reductions. Every reduction dimension appears in both input maps, and the paired extents agree:
(1, 1, 2). A reduction dimension of extent one still contributes one iteration. - There are no free or batch dimensions, so the accumulator and result are scalars of type
bf16.
The Vector dialect documentation explicitly permits a scalar accumulator and result when a contraction has no free or batch dimensions. Conceptually, this example accumulates the two products x[0] * scale and x[1] * scale into acc; the unit dimensions do not add any further products.
This legality argument describes the original input. The asymmetric contraction discussed below is produced by a standard rewrite pattern during execution, rather than supplied as the input.
Actual behavior
mlir-opt aborts with SIGABRT (shell exit code 134) while applying the patterns.
Relevant sanitized and abridged diagnostic and stack trace:
mlir-opt: /path/to/llvm-project/llvm/include/llvm/Support/Casting.h:560:
llvm::cast [To = mlir::VectorType, From = mlir::Type]:
Assertion `isa<To>(Val) && "cast<Ty>() argument of incompatible type!"' failed.
#12 (anonymous namespace)::ContractionOpLowering::lowerParallel(...)
/path/to/llvm-project/mlir/lib/Dialect/Vector/Transforms/LowerVectorContract.cpp
#13 (anonymous namespace)::ContractionOpLowering::matchAndRewriteMaskableOp(...)
/path/to/llvm-project/mlir/lib/Dialect/Vector/Transforms/LowerVectorContract.cpp
#14 mlir::vector::MaskableOpRewritePattern<mlir::vector::ContractionOp>::matchAndRewrite(...)
/path/to/llvm-project/mlir/include/mlir/Dialect/Vector/Utils/VectorUtils.h
#28 mlir::transform::ApplyPatternsOp::applyToOne(...)
/path/to/llvm-project/mlir/lib/Dialect/Transform/IR/TransformOps.cpp
With --debug-only=greedy-rewriter, the last successful relevant rewrite is CombineContractBroadcastMask. It folds the left-hand shape_cast and produces this intermediate contraction:
%out = vector.contract {
indexing_maps = [affine_map<(d0, d1, d2) -> (d2)>,
affine_map<(d0, d1, d2) -> (d0, d1, d2)>,
affine_map<(d0, d1, d2) -> ()>],
iterator_types = ["reduction", "reduction", "reduction"],
kind = #vector.kind<add>
} %x, %rhs, %acc : vector<2xbf16>, vector<1x1x2xbf16> into bf16
The next relevant pattern, ContractionOpLowering, reaches lowerParallel and triggers the assertion.
Expected behavior
Applying these standard pattern sets to the valid input should produce valid IR and preserve the scalar contraction result without crashing. If the folding and lowering combination cannot handle this case, the rewrite should leave the original operation intact.
Likely root cause
combineContractAndBroadcast accepts broadcast-like vector.shape_cast operands. It removes the two leading unit dimensions from the left-hand operand. The right-hand broadcast has a scalar source, which this folding pattern does not fold into a contraction operand. Consequently, the unit reduction dimensions remain only on the right-hand side, while the result remains scalar.
ContractionOpLowering selects these dimensions for removal through lowerParallel. Despite its name, this helper explicitly supports unit reduction dimensions appearing on only one input. However, it begins with:
VectorType resType = cast<VectorType>(op.getResultType());
That assumption fails for the scalar bf16 result before the unit-dimension handling can run.
A minimal candidate fix is to retain the general result type:
- VectorType resType = cast<VectorType>(op.getResultType());
+ Type resType = op.getResultType();
The remaining uses of resType in this helper do not require vector-specific APIs. For a unit reduction absent from the result map, resIndex is -1; the existing reshapeLoad and reshapeStore helpers already pass through scalar values for this index.
This is a proposed fix, not a claim of verification with a rebuilt compiler. A regression case should cover this combination of standard patterns starting from the valid scalar-result contraction above.
Environment
- Tool: standalone LLVM
mlir-optbuilt from a localllvm-projectsource tree. - LLVM/MLIR version:
LLVM version 24.0.0git,Optimized build with assertions. - Host OS:
Ubuntu 24.04.2 LTS,Linux 6.8.0-56-generic x86_64.
@llvm/issue-subscribers-mlir
Author: Cerulime
Summary
Combining Vector reduction-to-contract patterns with contraction lowering crashes on a valid scalar-result vector.contract whose left-hand operand is defined by a broadcast-like vector.shape_cast.
The failure is an assertion in ContractionOpLowering::lowerParallel, which unconditionally casts the result type to VectorType even though the result is a scalar. This reproduces with standalone LLVM mlir-opt, using standard Vector and Transform dialect operations.
Reproducer
repro.mlir:
module {
func.func @<!-- -->repro(%x: vector<2xbf16>, %scale: bf16, %acc: bf16) -> bf16 {
%lhs = vector.shape_cast %x : vector<2xbf16> to vector<1x1x2xbf16>
%rhs = vector.broadcast %scale : bf16 to vector<1x1x2xbf16>
%out = vector.contract {
indexing_maps = [affine_map<(d0, d1, d2) -> (d0, d1, d2)>,
affine_map<(d0, d1, d2) -> (d0, d1, d2)>,
affine_map<(d0, d1, d2) -> ()>],
iterator_types = ["reduction", "reduction", "reduction"],
kind = #vector.kind<add>
} %lhs, %rhs, %acc : vector<1x1x2xbf16>, vector<1x1x2xbf16> into bf16
return %out : bf16
}
}
module attributes {transform.with_named_sequence} {
transform.named_sequence @<!-- -->__transform_main(
%root: !transform.any_op {transform.readonly}) {
%func = transform.structured.match ops{["func.func"]} in %root
: (!transform.any_op) -> !transform.op<"func.func">
transform.apply_patterns to %func {
transform.apply_patterns.vector.reduction_to_contract
transform.apply_patterns.vector.lower_contraction
lowering_strategy = "outerproduct"
} : !transform.op<"func.func">
transform.yield
}
}
Command:
mlir-opt repro.mlir \
--transform-interpreter \
--mlir-disable-threading
For comparison, verifying the same file without executing the Transform sequence succeeds with exit code 0:
mlir-opt repro.mlir -o /dev/null
The crashing command also keeps the default input verification enabled. Both pattern sets are applied within a single transform.apply_patterns operation.
Why the input IR is valid
The payload satisfies the Vector operation constraints:
vector.shape_castpreserves the element type and element count:vector<2xbf16>andvector<1x1x2xbf16>both contain twobf16elements. It only adds two leading unit dimensions.vector.broadcastlegally broadcasts a scalarbf16tovector<1x1x2xbf16>.- Both contraction inputs have rank three and shape
(1, 1, 2). Their identity indexing maps each have three inputs, three outputs, and no symbols. The accumulator map has three inputs and no outputs, matching the scalar accumulator. - All three iterators are reductions. Every reduction dimension appears in both input maps, and the paired extents agree:
(1, 1, 2). A reduction dimension of extent one still contributes one iteration. - There are no free or batch dimensions, so the accumulator and result are scalars of type
bf16.
The Vector dialect documentation explicitly permits a scalar accumulator and result when a contraction has no free or batch dimensions. Conceptually, this example accumulates the two products x[0] * scale and x[1] * scale into acc; the unit dimensions do not add any further products.
This legality argument describes the original input. The asymmetric contraction discussed below is produced by a standard rewrite pattern during execution, rather than supplied as the input.
Actual behavior
mlir-opt aborts with SIGABRT (shell exit code 134) while applying the patterns.
Relevant sanitized and abridged diagnostic and stack trace:
mlir-opt: /path/to/llvm-project/llvm/include/llvm/Support/Casting.h:560:
llvm::cast [To = mlir::VectorType, From = mlir::Type]:
Assertion `isa<To>(Val) && "cast<Ty>() argument of incompatible type!"' failed.
#<!-- -->12 (anonymous namespace)::ContractionOpLowering::lowerParallel(...)
/path/to/llvm-project/mlir/lib/Dialect/Vector/Transforms/LowerVectorContract.cpp
#<!-- -->13 (anonymous namespace)::ContractionOpLowering::matchAndRewriteMaskableOp(...)
/path/to/llvm-project/mlir/lib/Dialect/Vector/Transforms/LowerVectorContract.cpp
#<!-- -->14 mlir::vector::MaskableOpRewritePattern<mlir::vector::ContractionOp>::matchAndRewrite(...)
/path/to/llvm-project/mlir/include/mlir/Dialect/Vector/Utils/VectorUtils.h
#<!-- -->28 mlir::transform::ApplyPatternsOp::applyToOne(...)
/path/to/llvm-project/mlir/lib/Dialect/Transform/IR/TransformOps.cpp
With --debug-only=greedy-rewriter, the last successful relevant rewrite is CombineContractBroadcastMask. It folds the left-hand shape_cast and produces this intermediate contraction:
%out = vector.contract {
indexing_maps = [affine_map<(d0, d1, d2) -> (d2)>,
affine_map<(d0, d1, d2) -> (d0, d1, d2)>,
affine_map<(d0, d1, d2) -> ()>],
iterator_types = ["reduction", "reduction", "reduction"],
kind = #vector.kind<add>
} %x, %rhs, %acc : vector<2xbf16>, vector<1x1x2xbf16> into bf16
The next relevant pattern, ContractionOpLowering, reaches lowerParallel and triggers the assertion.
Expected behavior
Applying these standard pattern sets to the valid input should produce valid IR and preserve the scalar contraction result without crashing. If the folding and lowering combination cannot handle this case, the rewrite should leave the original operation intact.
Likely root cause
combineContractAndBroadcast accepts broadcast-like vector.shape_cast operands. It removes the two leading unit dimensions from the left-hand operand. The right-hand broadcast has a scalar source, which this folding pattern does not fold into a contraction operand. Consequently, the unit reduction dimensions remain only on the right-hand side, while the result remains scalar.
ContractionOpLowering selects these dimensions for removal through lowerParallel. Despite its name, this helper explicitly supports unit reduction dimensions appearing on only one input. However, it begins with:
VectorType resType = cast<VectorType>(op.getResultType());
That assumption fails for the scalar bf16 result before the unit-dimension handling can run.
A minimal candidate fix is to retain the general result type:
- VectorType resType = cast<VectorType>(op.getResultType());
+ Type resType = op.getResultType();
The remaining uses of resType in this helper do not require vector-specific APIs. For a unit reduction absent from the result map, resIndex is -1; the existing reshapeLoad and reshapeStore helpers already pass through scalar values for this index.
This is a proposed fix, not a claim of verification with a rebuilt compiler. A regression case should cover this combination of standard patterns starting from the valid scalar-result contraction above.
Environment
- Tool: standalone LLVM
mlir-optbuilt from a localllvm-projectsource tree. - LLVM/MLIR version:
LLVM version 24.0.0git,Optimized build with assertions. - Host OS:
Ubuntu 24.04.2 LTS,Linux 6.8.0-56-generic x86_64.
Hi, I'd like to work on this one.
I reproduced the crash and verified that changing resType in lowerParallel from VectorType to Type makes it emit valid IR without crashing, and the MLIR test suite passes with the change.
What I do not understand yet is why this goes through lowerParallel when the program only has reduction iterators?
Since lowerReduction already accepts a non-vector result, my guess is that VectorType in lowerParallel assumed a parallel dimension implies a vector result, and the unit-reduction path never updated it.
Should I fix this with the Type change plus a regression test, or would you rather correct the dispatch? Happy to go either way.
Please let the maintainer decide how to fix it. As a supplement, I only fixed Type in local testing and did not find any additional issues in other samples.
@FedericoBruzzone @matthias-springer @banach-space
Thank you for the ping, @StarOne01!
If I understand correctly, the lowerParallel can handle unit-size reduction dimensions, see:
https://github.com/llvm/llvm-project/blob/c15d5c7470d1a869cb1663a5e70e5757b379e0c6/mlir/lib/Dialect/Vector/Transforms/LowerVectorContract.cpp?plain=1#L1003-L1010
That said, while lowerReduction only handles non-vector types:
https://github.com/llvm/llvm-project/blob/c15d5c7470d1a869cb1663a5e70e5757b379e0c6/mlir/lib/Dialect/Vector/Transforms/LowerVectorContract.cpp?plain=1#L1097-L1100
lowerParallel currently handles vector types:
https://github.com/llvm/llvm-project/blob/c15d5c7470d1a869cb1663a5e70e5757b379e0c6/mlir/lib/Dialect/Vector/Transforms/LowerVectorContract.cpp?plain=1#L1013
Now, why this goes through lowerParallel when the program only has reduction iterators?
By taking a look at getContractingDimMap, it seems that only treats a reduction dim as contracting if it appears in both the LHS and RHS maps
https://github.com/llvm/llvm-project/blob/c15d5c7470d1a869cb1663a5e70e5757b379e0c6/mlir/lib/Dialect/Vector/Transforms/LowerVectorContract.cpp?plain=1#L960-L968
As pointed out by @Cerulime, after CombineContractBroadcastMask, d0 and d1 appear only in the RHS map, so they are not contracting.
OVerall, from my POV, the Type change plus a regression test is fine, no dispatch change needed. Right?
Thank you @FedericoBruzzone, that cleared it up.
The naming is what confused me: lowerParallel sounds like it only handles parallel iterators, and lowerReduction sounds like it handles every reduction, so I did not expect a reduction-only program to reach lowerParallel. In practice the dispatch is by whether a dimension is contracting, and lowerParallel also handles unit reduction dimensions.
Agreed on the Type change plus a regression test, I will open a PR shortly.
Not at all, it's a pleasure :D
I agree that the name is confusing. I think we should update it somehow. What do you think, @banach-space?
@llvm/issue-subscribers-mlir-vectorops
Author: Cerulime
Summary
Combining Vector reduction-to-contract patterns with contraction lowering crashes on a valid scalar-result vector.contract whose left-hand operand is defined by a broadcast-like vector.shape_cast.
The failure is an assertion in ContractionOpLowering::lowerParallel, which unconditionally casts the result type to VectorType even though the result is a scalar. This reproduces with standalone LLVM mlir-opt, using standard Vector and Transform dialect operations.
Reproducer
repro.mlir:
module {
func.func @<!-- -->repro(%x: vector<2xbf16>, %scale: bf16, %acc: bf16) -> bf16 {
%lhs = vector.shape_cast %x : vector<2xbf16> to vector<1x1x2xbf16>
%rhs = vector.broadcast %scale : bf16 to vector<1x1x2xbf16>
%out = vector.contract {
indexing_maps = [affine_map<(d0, d1, d2) -> (d0, d1, d2)>,
affine_map<(d0, d1, d2) -> (d0, d1, d2)>,
affine_map<(d0, d1, d2) -> ()>],
iterator_types = ["reduction", "reduction", "reduction"],
kind = #vector.kind<add>
} %lhs, %rhs, %acc : vector<1x1x2xbf16>, vector<1x1x2xbf16> into bf16
return %out : bf16
}
}
module attributes {transform.with_named_sequence} {
transform.named_sequence @<!-- -->__transform_main(
%root: !transform.any_op {transform.readonly}) {
%func = transform.structured.match ops{["func.func"]} in %root
: (!transform.any_op) -> !transform.op<"func.func">
transform.apply_patterns to %func {
transform.apply_patterns.vector.reduction_to_contract
transform.apply_patterns.vector.lower_contraction
lowering_strategy = "outerproduct"
} : !transform.op<"func.func">
transform.yield
}
}
Command:
mlir-opt repro.mlir \
--transform-interpreter \
--mlir-disable-threading
For comparison, verifying the same file without executing the Transform sequence succeeds with exit code 0:
mlir-opt repro.mlir -o /dev/null
The crashing command also keeps the default input verification enabled. Both pattern sets are applied within a single transform.apply_patterns operation.
Why the input IR is valid
The payload satisfies the Vector operation constraints:
vector.shape_castpreserves the element type and element count:vector<2xbf16>andvector<1x1x2xbf16>both contain twobf16elements. It only adds two leading unit dimensions.vector.broadcastlegally broadcasts a scalarbf16tovector<1x1x2xbf16>.- Both contraction inputs have rank three and shape
(1, 1, 2). Their identity indexing maps each have three inputs, three outputs, and no symbols. The accumulator map has three inputs and no outputs, matching the scalar accumulator. - All three iterators are reductions. Every reduction dimension appears in both input maps, and the paired extents agree:
(1, 1, 2). A reduction dimension of extent one still contributes one iteration. - There are no free or batch dimensions, so the accumulator and result are scalars of type
bf16.
The Vector dialect documentation explicitly permits a scalar accumulator and result when a contraction has no free or batch dimensions. Conceptually, this example accumulates the two products x[0] * scale and x[1] * scale into acc; the unit dimensions do not add any further products.
This legality argument describes the original input. The asymmetric contraction discussed below is produced by a standard rewrite pattern during execution, rather than supplied as the input.
Actual behavior
mlir-opt aborts with SIGABRT (shell exit code 134) while applying the patterns.
Relevant sanitized and abridged diagnostic and stack trace:
mlir-opt: /path/to/llvm-project/llvm/include/llvm/Support/Casting.h:560:
llvm::cast [To = mlir::VectorType, From = mlir::Type]:
Assertion `isa<To>(Val) && "cast<Ty>() argument of incompatible type!"' failed.
#<!-- -->12 (anonymous namespace)::ContractionOpLowering::lowerParallel(...)
/path/to/llvm-project/mlir/lib/Dialect/Vector/Transforms/LowerVectorContract.cpp
#<!-- -->13 (anonymous namespace)::ContractionOpLowering::matchAndRewriteMaskableOp(...)
/path/to/llvm-project/mlir/lib/Dialect/Vector/Transforms/LowerVectorContract.cpp
#<!-- -->14 mlir::vector::MaskableOpRewritePattern<mlir::vector::ContractionOp>::matchAndRewrite(...)
/path/to/llvm-project/mlir/include/mlir/Dialect/Vector/Utils/VectorUtils.h
#<!-- -->28 mlir::transform::ApplyPatternsOp::applyToOne(...)
/path/to/llvm-project/mlir/lib/Dialect/Transform/IR/TransformOps.cpp
With --debug-only=greedy-rewriter, the last successful relevant rewrite is CombineContractBroadcastMask. It folds the left-hand shape_cast and produces this intermediate contraction:
%out = vector.contract {
indexing_maps = [affine_map<(d0, d1, d2) -> (d2)>,
affine_map<(d0, d1, d2) -> (d0, d1, d2)>,
affine_map<(d0, d1, d2) -> ()>],
iterator_types = ["reduction", "reduction", "reduction"],
kind = #vector.kind<add>
} %x, %rhs, %acc : vector<2xbf16>, vector<1x1x2xbf16> into bf16
The next relevant pattern, ContractionOpLowering, reaches lowerParallel and triggers the assertion.
Expected behavior
Applying these standard pattern sets to the valid input should produce valid IR and preserve the scalar contraction result without crashing. If the folding and lowering combination cannot handle this case, the rewrite should leave the original operation intact.
Likely root cause
combineContractAndBroadcast accepts broadcast-like vector.shape_cast operands. It removes the two leading unit dimensions from the left-hand operand. The right-hand broadcast has a scalar source, which this folding pattern does not fold into a contraction operand. Consequently, the unit reduction dimensions remain only on the right-hand side, while the result remains scalar.
ContractionOpLowering selects these dimensions for removal through lowerParallel. Despite its name, this helper explicitly supports unit reduction dimensions appearing on only one input. However, it begins with:
VectorType resType = cast<VectorType>(op.getResultType());
That assumption fails for the scalar bf16 result before the unit-dimension handling can run.
A minimal candidate fix is to retain the general result type:
- VectorType resType = cast<VectorType>(op.getResultType());
+ Type resType = op.getResultType();
The remaining uses of resType in this helper do not require vector-specific APIs. For a unit reduction absent from the result map, resIndex is -1; the existing reshapeLoad and reshapeStore helpers already pass through scalar values for this index.
This is a proposed fix, not a claim of verification with a rebuilt compiler. A regression case should cover this combination of standard patterns starting from the valid scalar-result contraction above.
Environment
- Tool: standalone LLVM
mlir-optbuilt from a localllvm-projectsource tree. - LLVM/MLIR version:
LLVM version 24.0.0git,Optimized build with assertions. - Host OS:
Ubuntu 24.04.2 LTS,Linux 6.8.0-56-generic x86_64.
I confirmed that this crash is fixed by #230256.