MLIR 23.0.0git
TosaFolders.cpp
Go to the documentation of this file.
1//===- TosaFolders.cpp ----------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Fold TOSA operations
10//
11//===----------------------------------------------------------------------===//
12
13#include <functional>
14#include <numeric>
15
22#include "mlir/IR/Matchers.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/ADT/SmallVector.h"
25
26using namespace mlir;
27using namespace mlir::tosa;
28
29namespace {
30
31/// Apply the given transformation \p toApply to every element of the tensor to
32/// be transformed \p toTransform.
33///
34/// Elements of \p toTransform are extracted as \p SrcValueType.
35///
36/// \returns A tensor with the same size as \p toTransform, containing
37/// \p TargetValueType values of type \p TargetType.
38template <class SrcValType, class TargetValType, class TargetType>
39DenseElementsAttr applyElementWise(
40 const DenseElementsAttr &toTransform,
41 const std::function<TargetValType(const SrcValType &)> &toApply,
42 TargetType targetType) {
43 SmallVector<TargetValType> transformedValues;
44 // We already know the amount of values we will insert, reserve space for
45 // all of them to avoid dynamic resizing
46 transformedValues.reserve(toTransform.getNumElements());
47 for (auto val : toTransform.getValues<SrcValType>()) {
48 auto transformedVal = toApply(val);
49 transformedValues.push_back(transformedVal);
50 }
51
52 // Make sure that the output tensor has the expected output type
53 auto inShape = toTransform.getType();
54 auto outTy = inShape.cloneWith({}, targetType);
55
56 return DenseElementsAttr::get(outTy, transformedValues);
57}
58
59template DenseElementsAttr applyElementWise<APFloat, APFloat, FloatType>(
60 const DenseElementsAttr &toTransform,
61 const std::function<APFloat(const APFloat &)> &toApply,
62 FloatType targetType);
63
64/// Function that checks if the type contained in \p toCheck is float.
65LogicalResult notifyIfNotFloat(TypedValue<TensorType> toCheck, TosaOp location,
66 PatternRewriter &rewriter) {
67 if (isa<FloatType>(toCheck.getType().getElementType())) {
68 return success();
69 }
70 return rewriter.notifyMatchFailure(location,
71 "Unexpected input tensor type: the "
72 "TOSA spec only allows floats");
73}
74
75/// Function that checks if \p toCheck is a dense TOSA constant tensor.
76LogicalResult notifyIfNoTosaDenseConstantTensor(TypedValue<TensorType> toCheck,
77 TosaOp location,
78 PatternRewriter &rewriter) {
79 // Check whether the tensor is constant and dense
80 // TODO We currently ensure the tensor is dense by using the correct type for
81 // the bind_value, however we do not actually need this value. It would be
82 // nicer to only have a check here.
84 if (!matchPattern(toCheck, m_Constant(&tmp))) {
85 return rewriter.notifyMatchFailure(location,
86 "Non-const or non-dense input tensor");
87 }
88
89 // Make sure it actually is a TOSA constant (the match allows for other
90 // constants as well)
91 if (isa<ConstOp>(toCheck.getDefiningOp())) {
92 return success();
93 }
94
95 return rewriter.notifyMatchFailure(location,
96 "The reciprocal can only be folded if "
97 "it operates on a TOSA constant");
98}
99
100/// Function that checks if \p toCheck is a dense TOSA constant float tensor.
101LogicalResult notifyIfNotConstantFloatTosaTensor(TypedValue<TensorType> toCheck,
102 TosaOp location,
103 PatternRewriter &rewriter) {
104 auto floatCheck = notifyIfNotFloat(toCheck, location, rewriter);
105 if (failed(floatCheck)) {
106 return floatCheck;
107 }
108 return notifyIfNoTosaDenseConstantTensor(toCheck, location, rewriter);
109}
110
111/// Heuristic to decide when to replace a unary operation on a constant with the
112/// folded value.
113/// Folding operations on constants can lead to an increased memory usage
114/// whenever the input cannot be replaced but a new constant is inserted. Hence,
115/// this will currently only suggest folding when the memory impact is
116/// negligible.
117/// Takes the \p unaryOp and the constant input \p values.
118/// \returns Whether folding should be applied.
119bool constantUnaryOpShouldBeFolded(TosaOp unaryOp, DenseElementsAttr values) {
120 assert(unaryOp->getNumOperands() == 1);
121 auto inputOp = unaryOp->getOperand(0);
122
123 // If the input is a splat, we don't care for the number of users
124 if (isa<SplatElementsAttr>(values)) {
125 return true;
126 }
127
128 // If this is the only use of the tensor it should be replaced as no
129 // additional memory is required
130 return inputOp.hasOneUse();
131}
132
133template <typename RangeType>
134DenseElementsAttr transposeType(const RangeType &data, ShapedType inputType,
135 ShapedType outputType,
136 llvm::ArrayRef<int64_t> permValues) {
137 using ElementType = std::decay_t<decltype(*std::begin(data))>;
138
139 assert(inputType.getElementType() == outputType.getElementType());
140
141 if (inputType.getNumElements() == 0)
143
144 auto inputShape = inputType.getShape();
145
146 // The inverted permutation map and strides of the output are used to compute
147 // the contribution of a given dimension to the destination linear index in
148 // an order-independent way.
149 auto outputStrides = computeStrides(outputType.getShape());
150 auto invertedPermValues = invertPermutationVector(permValues);
151
152 auto initialValue = *std::begin(data);
153 SmallVector<ElementType> outputValues(inputType.getNumElements(),
154 initialValue);
155
156 for (const auto &it : llvm::enumerate(data)) {
157 auto srcLinearIndex = it.index();
158
159 uint64_t dstLinearIndex = 0;
160 for (int64_t dim = inputShape.size() - 1; dim >= 0; --dim) {
161 // Compute the index into the current dimension of the source vector.
162 auto sourceIndexForDim = srcLinearIndex % inputShape[dim];
163 srcLinearIndex /= inputShape[dim];
164
165 // Add the contribution of the current dimension to the output using the
166 // permutation map.
167 dstLinearIndex +=
168 outputStrides[invertedPermValues[dim]] * sourceIndexForDim;
169 }
170
171 outputValues[dstLinearIndex] = it.value();
172 }
173
174 return DenseElementsAttr::get(outputType,
175 llvm::ArrayRef<ElementType>(outputValues));
176}
177
178// A type specialized transposition of an ElementsAttr.
179// This implementation tries to operate on the underlying data in its raw
180// representation when possible to avoid allocating a large number of Attribute
181// objects.
182DenseElementsAttr transpose(ElementsAttr attr, ShapedType inputType,
183 ShapedType outputType,
184 llvm::ArrayRef<int64_t> permValues) {
185 // Handle generic ElementsAttr
186 if (auto data = attr.tryGetValues<bool>())
187 return transposeType(*data, inputType, outputType, permValues);
188
189 if (auto data = attr.tryGetValues<int8_t>())
190 return transposeType(*data, inputType, outputType, permValues);
191
192 if (auto data = attr.tryGetValues<int16_t>())
193 return transposeType(*data, inputType, outputType, permValues);
194
195 if (auto data = attr.tryGetValues<int32_t>())
196 return transposeType(*data, inputType, outputType, permValues);
197
198 if (auto data = attr.tryGetValues<int64_t>())
199 return transposeType(*data, inputType, outputType, permValues);
200
201 if (auto data = attr.tryGetValues<float>())
202 return transposeType(*data, inputType, outputType, permValues);
203
204 if (auto data = attr.tryGetValues<APFloat>())
205 return transposeType(*data, inputType, outputType, permValues);
206
207 // Handle DenseResourceElementsAttr
208 if (isa<DenseResourceElementsAttr>(attr)) {
209 auto elementTy = attr.getElementType();
210
211 if (auto data = tryGetDenseResourceValues<bool>(attr);
212 data && elementTy.isInteger(1))
213 return transposeType(*data, inputType, outputType, permValues);
214
215 if (auto data = tryGetDenseResourceValues<int8_t>(attr);
216 data && elementTy.isInteger(8))
217 return transposeType(*data, inputType, outputType, permValues);
218
219 if (auto data = tryGetDenseResourceValues<int16_t>(attr);
220 data && elementTy.isInteger(16))
221 return transposeType(*data, inputType, outputType, permValues);
222
223 if (auto data = tryGetDenseResourceValues<int32_t>(attr);
224 data && elementTy.isInteger(32))
225 return transposeType(*data, inputType, outputType, permValues);
226
227 if (auto data = tryGetDenseResourceValues<int64_t>(attr);
228 data && elementTy.isInteger(64))
229 return transposeType(*data, inputType, outputType, permValues);
230
231 if (auto data = tryGetDenseResourceValues<float>(attr);
232 data && elementTy.isF32())
233 return transposeType(*data, inputType, outputType, permValues);
234 }
235
236 return nullptr;
237}
238
239struct TosaFoldConstantTranspose : public OpRewritePattern<tosa::TransposeOp> {
241
242 LogicalResult matchAndRewrite(tosa::TransposeOp op,
243 PatternRewriter &rewriter) const override {
244 auto outputType = cast<ShapedType>(op.getType());
245 if (!outputType.hasRank() || !outputType.hasStaticShape())
246 return failure();
247 // TOSA supports quantized types.
248 if (!outputType.getElementType().isIntOrIndexOrFloat())
249 return failure();
250
251 ElementsAttr inputValues;
252 if (!matchPattern(op.getInput1(), m_Constant(&inputValues)))
253 return failure();
254 // Make sure the input is a constant that has a single user.
255 if (!llvm::hasSingleElement(op.getInput1().getDefiningOp()->getUsers()))
256 return failure();
257
258 auto permValues = llvm::map_to_vector(
259 op.getPerms(), [](const int32_t v) { return static_cast<int64_t>(v); });
260
261 auto inputType = cast<ShapedType>(op.getInput1().getType());
262
263 auto resultAttr = transpose(inputValues, inputType, outputType, permValues);
264 if (!resultAttr) {
265 return rewriter.notifyMatchFailure(
266 op, "unsupported attribute or element type");
267 }
268
269 rewriter.replaceOpWithNewOp<tosa::ConstOp>(op, outputType, resultAttr);
270 return success();
271 }
272};
273
274struct TosaFoldConstantReciprocal : public OpRewritePattern<ReciprocalOp> {
275
277
278 LogicalResult matchAndRewrite(ReciprocalOp recip,
279 PatternRewriter &rewriter) const override {
280 auto inputTensor = recip.getInput1();
281
282 // Check that we can apply folding
283 auto preCondCheck =
284 notifyIfNotConstantFloatTosaTensor(inputTensor, recip, rewriter);
285 if (failed(preCondCheck)) {
286 return preCondCheck;
287 }
288
289 // Extract the tensor values
290 DenseElementsAttr inputValues;
291 matchPattern(inputTensor, m_Constant(&inputValues));
292
293 // Check whether this should be folded.
294 if (!constantUnaryOpShouldBeFolded(recip, inputValues)) {
295 return rewriter.notifyMatchFailure(
296 recip, "Currently, reciprocals will only be folded if the input "
297 "tensor has a single user");
298 }
299
300 if (inputTensor.getType() != recip.getType())
301 return rewriter.notifyMatchFailure(
302 recip, "input tensor and reciprocal output have different type");
303
304 // Create a new tensor with the updated values
305 auto newTensor = applyElementWise<APFloat, APFloat, FloatType>(
306 inputValues, &ReciprocalOp::calcOneElement,
307 cast<FloatType>(inputValues.getElementType()));
308
309 // Replace the use of the reciprocal with the transformed tensor
310 rewriter.replaceOpWithNewOp<ConstOp>(recip, newTensor.getType(), newTensor);
311 return success();
312 }
313};
314
315/// Getting the axes position of the element which is located
316/// in the tensor at the counter index
317
319getPositionFromIndex(int64_t index, llvm::ArrayRef<int64_t> tensorShape) {
320 int64_t remaining = index;
321 llvm::SmallVector<int64_t> position(tensorShape.size(), 0);
322 for (int64_t i = tensorShape.size() - 1; i >= 0; --i) {
323 position[i] = remaining % tensorShape[i];
324 remaining /= tensorShape[i];
325 }
326 return position;
327}
328
329/// Getting the index of the element which is located at the
330/// axes position in the tensor
331
332int64_t getIndexFromPosition(llvm::ArrayRef<int64_t> position,
333 llvm::ArrayRef<int64_t> tensorShape) {
334 int64_t index = 0;
335 int64_t multiplierTmp = 1;
336 for (int64_t i = position.size() - 1; i >= 0; --i) {
337 index += position[i] * multiplierTmp;
338 multiplierTmp *= tensorShape[i];
339 }
340 return index;
341}
342
343template <typename OperationType>
344llvm::APInt calculateReducedValue(const mlir::ElementsAttr &oldTensorAttr,
346 int64_t reductionAxis,
347 int64_t reductionIndex) {
348
349 llvm::SmallVector<int64_t> newShape(oldShape);
350 newShape[reductionAxis] = 1;
351 /// Let's calculate the position of the index
353 getPositionFromIndex(reductionIndex, newShape);
354 auto oldTensor = oldTensorAttr.getValues<llvm::APInt>();
355 /// Starting from the first positon along the reduction axis
356 position[reductionAxis] = 0;
357 int64_t indexAtOldTensor = getIndexFromPosition(position, oldShape);
358 llvm::APInt reducedValue = oldTensor[indexAtOldTensor];
359
360 for (int64_t reductionAxisVal = 1; reductionAxisVal < oldShape[reductionAxis];
361 ++reductionAxisVal) {
362
363 int64_t stride = llvm::product_of(oldShape.drop_front(reductionAxis + 1));
364 int64_t index = indexAtOldTensor + stride * reductionAxisVal;
365 reducedValue =
366 OperationType::calcOneElement(reducedValue, oldTensor[index]);
367 }
368 return reducedValue;
369}
370
371template <typename OperationType>
372struct ReduceConstantOptimization : public OpRewritePattern<OperationType> {
373
374 ReduceConstantOptimization(MLIRContext *context,
375 bool aggressiveReduceConstant)
376 : OpRewritePattern<OperationType>(context),
377 aggressiveReduceConstant(aggressiveReduceConstant) {}
378
379 using OpRewritePattern<OperationType>::OpRewritePattern;
380
381 LogicalResult matchAndRewrite(OperationType op,
382 PatternRewriter &rewriter) const override {
383 Value inputOp = op.getInput();
384 auto constOp = inputOp.getDefiningOp<tosa::ConstOp>();
385
386 if (!constOp)
387 return rewriter.notifyMatchFailure(
388 op, "reduce input must be const operation");
389
390 if (!inputOp.hasOneUse() && !this->aggressiveReduceConstant)
391 return rewriter.notifyMatchFailure(
392 op, "input operation has more than one user");
393
394 auto resultType = cast<ShapedType>(op.getOutput().getType());
395
396 if (!resultType.hasStaticShape())
397 return rewriter.notifyMatchFailure(op, "result type shape is not static");
398
399 auto reductionAxis = op.getAxis();
400 const auto denseElementsAttr = constOp.getValues();
401 const auto shapedOldElementsValues =
402 cast<ShapedType>(denseElementsAttr.getType());
403
404 if (!llvm::isa<IntegerType>(shapedOldElementsValues.getElementType()))
405 return rewriter.notifyMatchFailure(
406 op, "reduce input currently supported with integer type");
407
408 auto oldShape = shapedOldElementsValues.getShape();
409 auto newShape = resultType.getShape();
410
411 int64_t newNumOfElements = llvm::product_of(newShape);
412 llvm::SmallVector<APInt> newReducedTensor(newNumOfElements);
413
414 for (int64_t reductionIndex = 0; reductionIndex < newNumOfElements;
415 ++reductionIndex) {
416
417 /// Let's reduce all the elements along this reduction axis
418 newReducedTensor[reductionIndex] = calculateReducedValue<OperationType>(
419 denseElementsAttr, oldShape, reductionAxis, reductionIndex);
420 }
421
422 auto rankedTensorType = cast<RankedTensorType>(resultType);
423 auto denseAttr =
424 mlir::DenseElementsAttr::get(rankedTensorType, newReducedTensor);
425 rewriter.replaceOpWithNewOp<tosa::ConstOp>(op, rankedTensorType, denseAttr);
426 return success();
427 }
428 const bool aggressiveReduceConstant;
429};
430
431} // namespace
432
434 RewritePatternSet &patterns,
435 bool aggressiveReduceConstant) {
436 patterns.add<ReduceConstantOptimization<ReduceAllOp>>(
437 ctx, aggressiveReduceConstant);
438 patterns.add<ReduceConstantOptimization<ReduceAnyOp>>(
439 ctx, aggressiveReduceConstant);
440 patterns.add<ReduceConstantOptimization<ReduceMaxOp>>(
441 ctx, aggressiveReduceConstant);
442 patterns.add<ReduceConstantOptimization<ReduceMinOp>>(
443 ctx, aggressiveReduceConstant);
444 patterns.add<ReduceConstantOptimization<ReduceProductOp>>(
445 ctx, aggressiveReduceConstant);
446 patterns.add<ReduceConstantOptimization<ReduceSumOp>>(
447 ctx, aggressiveReduceConstant);
448}
449
451 MLIRContext *ctx, RewritePatternSet &patterns) {
452 patterns.add<TosaFoldConstantTranspose>(ctx);
453}
454
456 MLIRContext *ctx, RewritePatternSet &patterns) {
457 patterns.add<TosaFoldConstantReciprocal>(ctx);
458}
return success()
An attribute that represents a reference to a dense vector or tensor object.
auto getValues() const
Return the held element values as a range of the given type.
int64_t getNumElements() const
Returns the number of elements held by this attribute.
Type getElementType() const
Return the element type of this DenseElementsAttr.
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
ShapedType getType() const
Return the type of this ElementsAttr, guaranteed to be a vector or tensor with static shape.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:63
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
bool hasOneUse() const
Returns true if this value has exactly one use.
Definition Value.h:197
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:717
void populateTosaConstantReduction(MLIRContext *ctx, RewritePatternSet &patterns, bool aggressiveReduceConstant)
void populateTosaFoldConstantReciprocalPatterns(MLIRContext *ctx, RewritePatternSet &patterns)
std::optional< ArrayRef< T > > tryGetDenseResourceValues(ElementsAttr attr)
void populateTosaFoldConstantTransposePatterns(MLIRContext *ctx, RewritePatternSet &patterns)
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
SmallVector< int64_t > computeStrides(ArrayRef< int64_t > sizes)
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
Definition Value.h:494
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
SmallVector< int64_t > invertPermutationVector(ArrayRef< int64_t > permutation)
Helper method to apply to inverse a permutation.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...