Skip to content

Commit 0f115e4

Browse files
author
Spenser Bauman
committed
[mlir][tensor] Implement constant folder for tensor.pad
Extend the folding ability of the RewriteAsConstant patterns to include tensor.pad operations on constants. The new pattern with constant fold tensor.pad operations which operate on tensor constants and have statically resolvable padding sizes/values. %init = arith.constant dense<[[6, 7], [8, 9]]> : tensor<2x2xi32> %pad_value = arith.constant 0 : i32 %0 = tensor.pad %init low[1, 1] high[1, 1] { ^bb0(%arg1: index, %arg2: index): tensor.yield %pad_value : i32 } : tensor<2x2xi32> to tensor<4x4xi32> becomes %cst = arith.constant dense<[[0, 0, 0, 0], [0, 6, 7, 0], [0, 8, 9, 0], [0, 0, 0, 0]]> : tensor<4x4xi32>
1 parent 597ac47 commit 0f115e4

File tree

3 files changed

+234
-2
lines changed

3 files changed

+234
-2
lines changed

mlir/lib/Dialect/Tensor/Transforms/RewriteAsConstant.cpp

Lines changed: 150 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,12 @@
88
//
99
#include "mlir/Dialect/Tensor/IR/Tensor.h"
1010
#include "mlir/Dialect/Tensor/Transforms/Transforms.h"
11+
#include "mlir/Dialect/Utils/IndexingUtils.h"
1112
#include "mlir/IR/Matchers.h"
1213
#include "mlir/IR/PatternMatch.h"
1314

15+
#include "llvm/ADT/TypeSwitch.h"
16+
1417
using namespace mlir;
1518
using namespace mlir::tensor;
1619

@@ -45,9 +48,155 @@ struct GenerateToConstant : public OpRewritePattern<GenerateOp> {
4548
}
4649
};
4750

51+
/// Transform a linear index from one indexing space to another given:
52+
///
53+
/// - the shape of the source indexing space,
54+
/// - the strides of the target indexing space,
55+
/// - a linear index into the source indexing space.
56+
///
57+
/// This function is logically a sequence of linearize/delinearize over
58+
/// different bases but avoids allocating intermediate SmallVectors.
59+
int64_t transformIndexSpace(ArrayRef<int64_t> inputShape,
60+
ArrayRef<int64_t> outputStrides,
61+
int64_t srcLinearIndex) {
62+
assert(inputShape.size() == outputStrides.size());
63+
64+
int64_t dstLinearIndex = 0;
65+
66+
for (int64_t dim = inputShape.size() - 1; dim >= 0; --dim) {
67+
// Compute the index into the current dimension of the source tensor.
68+
// `quotient` is the remaining linear index after accounting for the
69+
// current dimension.
70+
//
71+
// `remainder` is the index into the source tensor for the current
72+
// dimension.
73+
auto [quotient, remainder] = std::div(srcLinearIndex, inputShape[dim]);
74+
75+
srcLinearIndex = quotient;
76+
77+
// Add the contribution of the current dimension to the output using the
78+
// permutation map.
79+
dstLinearIndex += outputStrides[dim] * remainder;
80+
}
81+
82+
return dstLinearIndex;
83+
}
84+
85+
template <typename ElemType, typename AttrType>
86+
Value constantFoldPadOp(PatternRewriter &rewriter, Location loc,
87+
DenseElementsAttr input, AttrType padValue,
88+
ArrayRef<int64_t> padLow, ArrayRef<int64_t> padHigh) {
89+
auto inputValues = input.tryGetValues<ElemType>();
90+
if (failed(inputValues))
91+
return nullptr;
92+
93+
auto oldShape = input.getType().getShape();
94+
95+
// Compute the output shape of the new value.
96+
auto newShape =
97+
llvm::map_to_vector(llvm::zip(oldShape, padLow, padHigh),
98+
[](std::tuple<int64_t, int64_t, int64_t> pack) {
99+
auto [old, low, high] = pack;
100+
return old + low + high;
101+
});
102+
103+
int64_t outputSize = computeProduct(newShape);
104+
105+
// Fully initialize the vector with the padding value.
106+
// The non-padded area will then be copied.
107+
SmallVector<ElemType> values(outputSize, padValue.getValue());
108+
109+
// Strides for input and output are used to transform between the indexing
110+
// space of the input and output tensors.
111+
SmallVector<int64_t> outputStrides = computeStrides(newShape);
112+
113+
// The contribution of the low padding to the offset in the output tensor.
114+
// This is the starting position of the source tensor within the padding
115+
// tensor.
116+
int64_t startingOffset = linearize(padLow, outputStrides);
117+
118+
// Copy values from the input tensor to the corresponding sub-region
119+
// of the output tensor.
120+
for (auto [inputIndex, inputValue] : llvm::enumerate(*inputValues)) {
121+
auto outputIndex = transformIndexSpace(oldShape, outputStrides, inputIndex);
122+
values[outputIndex + startingOffset] = inputValue;
123+
}
124+
125+
// Create an attribute for the folded value.
126+
auto newType = input.getType().clone(newShape);
127+
auto newAttr = DenseElementsAttr::get(newType, values);
128+
129+
Operation *constantOp =
130+
rewriter.getContext()
131+
->getLoadedDialect<TensorDialect>()
132+
->materializeConstant(rewriter, newAttr, newType, loc);
133+
134+
return constantOp ? constantOp->getResult(0) : nullptr;
135+
}
136+
137+
struct PadOpToConstant final : public OpRewritePattern<PadOp> {
138+
using OpRewritePattern<PadOp>::OpRewritePattern;
139+
140+
LogicalResult matchAndRewrite(PadOp padTensorOp,
141+
PatternRewriter &rewriter) const override {
142+
if (padTensorOp.getNofold())
143+
return rewriter.notifyMatchFailure(
144+
padTensorOp, "refusing to fold nofold pad operation");
145+
146+
TypedValue<RankedTensorType> input = padTensorOp.getSource();
147+
RankedTensorType resultType = padTensorOp.getResult().getType();
148+
149+
DenseElementsAttr inputAttr = nullptr;
150+
if (!matchPattern(input, m_Constant(&inputAttr)))
151+
return failure();
152+
153+
Value paddingValue = padTensorOp.getConstantPaddingValue();
154+
155+
// Extract the constant value used for padding or bail out.
156+
Attribute paddingAttr = nullptr;
157+
if (!paddingValue || !matchPattern(paddingValue, m_Constant(&paddingAttr)))
158+
return rewriter.notifyMatchFailure(padTensorOp,
159+
"unable to get constant value");
160+
161+
// Try to extract the constant values of the low and high padding.
162+
auto lowPad = getConstantIntValues(padTensorOp.getMixedLowPad());
163+
auto highPad = getConstantIntValues(padTensorOp.getMixedHighPad());
164+
165+
// If the padding cannot be extracted, bail out.
166+
if (!lowPad || !highPad)
167+
return rewriter.notifyMatchFailure(padTensorOp,
168+
"unable to extract constant padding");
169+
170+
Location loc = padTensorOp.getLoc();
171+
172+
// Try constant folding the supported cases of integer and float values.
173+
Value newOp =
174+
llvm::TypeSwitch<Attribute, Value>(paddingAttr)
175+
.Case([&](FloatAttr floatAttr) {
176+
return constantFoldPadOp<llvm::APFloat>(
177+
rewriter, loc, inputAttr, floatAttr, *lowPad, *highPad);
178+
})
179+
.Case([&](IntegerAttr integerAttr) {
180+
return constantFoldPadOp<llvm::APInt>(
181+
rewriter, loc, inputAttr, integerAttr, *lowPad, *highPad);
182+
})
183+
.Default(Value());
184+
185+
if (!newOp)
186+
return rewriter.notifyMatchFailure(padTensorOp,
187+
"tensor type not supported");
188+
189+
if (newOp.getType() != resultType)
190+
newOp = rewriter.create<tensor::CastOp>(loc, resultType, newOp);
191+
192+
rewriter.replaceOp(padTensorOp, newOp);
193+
return success();
194+
}
195+
};
196+
48197
} // namespace
49198

50199
void mlir::tensor::populateRewriteAsConstantPatterns(
51200
RewritePatternSet &patterns) {
52-
patterns.add<GenerateToConstant>(patterns.getContext());
201+
patterns.add<GenerateToConstant, PadOpToConstant>(patterns.getContext());
53202
}

mlir/lib/Dialect/Utils/IndexingUtils.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ int64_t mlir::computeProduct(ArrayRef<int64_t> basis) {
9292
assert(llvm::all_of(basis, [](int64_t s) { return s > 0; }) &&
9393
"basis must be nonnegative");
9494
if (basis.empty())
95-
return 0;
95+
return 1;
9696
return std::accumulate(basis.begin(), basis.end(), 1,
9797
std::multiplies<int64_t>());
9898
}

mlir/test/Dialect/Tensor/rewrite-as-constant.mlir

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,86 @@ func.func @tensor_generate_constant() -> tensor<2x3x5xf32> {
2121
} : tensor<2x3x5xf32>
2222
return %0 : tensor<2x3x5xf32>
2323
}
24+
25+
// CHECK-LABEL: func @pad_of_ints(
26+
// CHECK: %[[cst:.*]] = arith.constant dense<[
27+
// CHECK: [0, 0, 0, 0],
28+
// CHECK: [0, 6, 7, 0],
29+
// CHECK: [0, 8, 9, 0],
30+
// CHECK: [0, 0, 0, 0]
31+
// CHECK: ]> : tensor<4x4xi32>
32+
// CHECK: %[[cast:.*]] = tensor.cast %[[cst]] : tensor<4x4xi32> to tensor<?x?xi32>
33+
// CHECK: return %[[cast]]
34+
func.func @pad_of_ints() -> tensor<?x?xi32> {
35+
%init = arith.constant dense<[[6, 7], [8, 9]]> : tensor<2x2xi32>
36+
%pad_value = arith.constant 0 : i32
37+
38+
%c1 = arith.constant 1 : index
39+
40+
%0 = tensor.pad %init low[%c1, %c1] high[%c1, %c1] {
41+
^bb0(%arg1: index, %arg2: index):
42+
tensor.yield %pad_value : i32
43+
} : tensor<2x2xi32> to tensor<?x?xi32>
44+
45+
return %0 : tensor<?x?xi32>
46+
}
47+
48+
// CHECK-LABEL: func @pad_of_floats(
49+
// CHECK: %[[cst:.*]] = arith.constant dense<[
50+
// CHECK: [0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00],
51+
// CHECK: [0.000000e+00, 6.000000e+00, 7.000000e+00, 0.000000e+00],
52+
// CHECK: [0.000000e+00, 8.000000e+00, 9.000000e+00, 0.000000e+00],
53+
// CHECK: [0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00]
54+
// CHECK: ]> : tensor<4x4xf32>
55+
// CHECK: return %[[cst]]
56+
57+
func.func @pad_of_floats() -> tensor<4x4xf32> {
58+
%init = arith.constant dense<[[6.0, 7.0], [8.0, 9.0]]> : tensor<2x2xf32>
59+
%pad_value = arith.constant 0.0 : f32
60+
61+
%0 = tensor.pad %init low[1, 1] high[1, 1] {
62+
^bb0(%arg1: index, %arg2: index):
63+
tensor.yield %pad_value : f32
64+
} : tensor<2x2xf32> to tensor<4x4xf32>
65+
66+
return %0 : tensor<4x4xf32>
67+
}
68+
69+
// CHECK-LABEL: func @pad_of_ints_no_low_dims(
70+
// CHECK: %[[cst:.*]] = arith.constant dense<[
71+
// CHECK: [6, 7, 0],
72+
// CHECK: [8, 9, 0],
73+
// CHECK: [0, 0, 0]
74+
// CHECK: ]> : tensor<3x3xi32>
75+
// CHECK: return %[[cst]]
76+
func.func @pad_of_ints_no_low_dims() -> tensor<3x3xi32> {
77+
%init = arith.constant dense<[[6, 7], [8, 9]]> : tensor<2x2xi32>
78+
%pad_value = arith.constant 0 : i32
79+
80+
%0 = tensor.pad %init low[0, 0] high[1, 1] {
81+
^bb0(%arg1: index, %arg2: index):
82+
tensor.yield %pad_value : i32
83+
} : tensor<2x2xi32> to tensor<3x3xi32>
84+
85+
return %0 : tensor<3x3xi32>
86+
}
87+
88+
// CHECK-LABEL: func @pad_of_ints_no_high_dims(
89+
// CHECK: %[[cst:.*]] = arith.constant dense<[
90+
// CHECK: [0, 0, 0],
91+
// CHECK: [0, 6, 7],
92+
// CHECK: [0, 8, 9]
93+
// CHECK: ]> : tensor<3x3xi32>
94+
// CHECK: return %[[cst]]
95+
func.func @pad_of_ints_no_high_dims() -> tensor<3x3xi32> {
96+
%init = arith.constant dense<[[6, 7], [8, 9]]> : tensor<2x2xi32>
97+
%pad_value = arith.constant 0 : i32
98+
99+
%0 = tensor.pad %init low[1, 1] high[0, 0] {
100+
^bb0(%arg1: index, %arg2: index):
101+
tensor.yield %pad_value : i32
102+
} : tensor<2x2xi32> to tensor<3x3xi32>
103+
104+
return %0 : tensor<3x3xi32>
105+
}
106+

0 commit comments

Comments
 (0)