Skip to content

Commit c59dc1a

Browse files
author
Ofri Frishman
committed
[MLIR] Add pattern to bubble up tensor.extract_slice
Add a pattern that bubbles up tensor.extract_slice through tensor.expand_shape. This pattern enables tiling and fusing op chains which contain tensor.expand_shape if added as a cleanup pattern of tile and fuse utility. Without this pattern that would not be possible, as tensor.expand_shape does not implement the tiling interface. In addition, registering this pattern as a cleanup pattern for transform.structured.fuse. The pattren was first implement in IREE project by Quinn Dawkins and is being upstreamed.
1 parent 73413bd commit c59dc1a

File tree

5 files changed

+353
-0
lines changed

5 files changed

+353
-0
lines changed

mlir/include/mlir/Dialect/Tensor/Transforms/Transforms.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,12 @@ void populateFoldTensorSubsetIntoVectorTransferPatterns(
5858
void populateMergeConsecutiveInsertExtractSlicePatterns(
5959
RewritePatternSet &patterns);
6060

61+
/// Appends patterns that are used to bubble up tensor.extract slice op above
62+
/// its producer. When used as cleanup patterns of tile and fuse, enables fusing
63+
/// the producer with the consumer even if the producer does not implement the
64+
/// tiling interface.
65+
void populateBubbleUpExtractSliceOpPatterns(RewritePatternSet &patterns);
66+
6167
/// Populates `patterns` with patterns that drop redundant tensor.insert_slice
6268
/// rank expansions.
6369
void populateDropRedundantInsertSliceRankExpansionPatterns(

mlir/lib/Dialect/Linalg/TransformOps/LinalgTransformOps.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,7 @@ transform::FuseOp::apply(transform::TransformRewriter &rewriter,
582582
RewritePatternSet patterns(context);
583583
tensor::ExtractSliceOp::getCanonicalizationPatterns(patterns, context);
584584
tensor::populateMergeConsecutiveInsertExtractSlicePatterns(patterns);
585+
tensor::populateBubbleUpExtractSliceOpPatterns(patterns);
585586
tileAndFuseOptions.cleanupPatterns = std::move(patterns);
586587
}
587588

Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
1+
//===- BubbleUpExtractSlice.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+
// Swap a `tensor.extract_slice` with the producer of the source in some cases
10+
// where that is valid. When used as cleanup patterns of tile and fuse, enables
11+
// fusing the producer with the consumer even if the producer does not implement
12+
// the tiling interface.
13+
//
14+
//===----------------------------------------------------------------------===//
15+
16+
#include "mlir/Dialect/Affine/IR/AffineOps.h"
17+
#include "mlir/Dialect/Arith/Utils/Utils.h"
18+
#include "mlir/Dialect/Tensor/Transforms/Transforms.h"
19+
#include "mlir/Dialect/Tensor/Utils/Utils.h"
20+
#include "mlir/IR/BuiltinTypes.h"
21+
#include "mlir/IR/OpDefinition.h"
22+
#include "mlir/IR/PatternMatch.h"
23+
#include "mlir/Interfaces/ValueBoundsOpInterface.h"
24+
25+
using namespace mlir;
26+
using namespace mlir::tensor;
27+
28+
/// Converts `tensor.extract_slice(tensor.expand_shape)` to
29+
/// `tensor.expand_shape(tensor.extract_slice)`.
30+
/// For this transformation to be possible, the slice must be fully contiguous
31+
/// within each reassociation group of the expand_shape. If the transformation
32+
/// is not possible, or if the slice is rank reducting, the function returns
33+
/// failure.
34+
///
35+
/// Example:
36+
/// ```
37+
/// %reshape = tensor.expand_shape %in [[0, 1], [2, 3], [4, 5, 6]]
38+
/// tensor<8x16x32xf32> to tensor<2x4x2x8x4x2x4xf32>
39+
/// %slice = tensor.extract_slice %reshape ...
40+
/// tensor<2x4x2x8x4x2x4xf32> to tensor<2x4x1x5x1x1x4xf32>
41+
///
42+
/// // The transformation is possible because each reassociation group has a
43+
/// // contiguous slice. (i.e., [2x4->2x4], [2x8->1x5], [4x2x4->1x1x4])
44+
/// // After the transformation:
45+
///
46+
/// %slice = tensor.extract_slice %in ...
47+
/// tensor<8x16x32xf32> to tensor<8x5x4xf32>
48+
/// %reshape = tensor.expand_shape %slice [[0, 1], [2, 3], [4, 5, 6]]
49+
/// tensor<8x5x4xf32> to tensor<2x4x1x5x1x1x4xf32>
50+
/// ```
51+
static LogicalResult
52+
swapExpandShapeWithSlice(RewriterBase &rewriter,
53+
tensor::ExpandShapeOp expandShapeOp,
54+
tensor::ExtractSliceOp sliceOp) {
55+
SmallVector<OpFoldResult> offsets = sliceOp.getMixedOffsets();
56+
SmallVector<OpFoldResult> sizes = sliceOp.getMixedSizes();
57+
58+
if (static_cast<size_t>(sliceOp.getResultType().getRank()) != sizes.size()) {
59+
return rewriter.notifyMatchFailure(sliceOp,
60+
"unimplemented: rank reducing slice");
61+
}
62+
63+
// Helper variables and function for accumulating the new offset and length
64+
// values.
65+
Location loc = expandShapeOp->getLoc();
66+
AffineExpr d0, d1, d2;
67+
bindDims(rewriter.getContext(), d0, d1, d2);
68+
// Multiply two integers.
69+
auto mul = [&](OpFoldResult v1, OpFoldResult v2) {
70+
auto mulMap = AffineMap::get(2, 0, {d0 * d1});
71+
return affine::makeComposedFoldedAffineApply(rewriter, loc, mulMap,
72+
{v1, v2});
73+
};
74+
75+
SmallVector<OpFoldResult> outputShape =
76+
getMixedValues(expandShapeOp.getStaticOutputShape(),
77+
expandShapeOp.getOutputShape(), rewriter);
78+
79+
auto isZeroOffsetAndFullSize = [](OpFoldResult offset, OpFoldResult sliceSize,
80+
OpFoldResult size) {
81+
if (!isConstantIntValue(offset, 0))
82+
return false;
83+
FailureOr<bool> maybeEqual =
84+
ValueBoundsConstraintSet::areEqual(sliceSize, size);
85+
return llvm::succeeded(maybeEqual) && maybeEqual.value();
86+
};
87+
88+
// First verify that this is a full slice of the expanded tensor.
89+
for (const ReassociationIndices &indices :
90+
expandShapeOp.getReassociationIndices()) {
91+
int64_t i = 0;
92+
int64_t e = indices.size();
93+
// Find the first expanded dim after the first dim with non-unit extracted
94+
// size.
95+
for (; i < e; ++i) {
96+
if (!isConstantIntValue(sizes[indices[i]], 1)) {
97+
// +1 to skip the first non-unit size dim.
98+
i++;
99+
break;
100+
}
101+
}
102+
103+
// Verify that all subsequent dimensions extract the full size of the
104+
// source tensor.
105+
for (; i < e; ++i) {
106+
int64_t expandedDim = indices[i];
107+
if (!isZeroOffsetAndFullSize(offsets[expandedDim], sizes[expandedDim],
108+
outputShape[expandedDim])) {
109+
return rewriter.notifyMatchFailure(
110+
sliceOp, "Not a contiguous slice of the expanded tensor.");
111+
}
112+
}
113+
}
114+
115+
// Compute new offsets, lengths, and strides.
116+
SmallVector<OpFoldResult> newOffsets, newLengths, newStrides;
117+
for (const ReassociationIndices &indices :
118+
expandShapeOp.getReassociationIndices()) {
119+
OpFoldResult newSize = rewriter.getIndexAttr(1);
120+
SmallVector<OpFoldResult> basis, delinOffsets;
121+
122+
int64_t i = 0;
123+
int64_t e = indices.size();
124+
// Offset = cumulative product of leading unit extracted dims.
125+
for (; i < e; ++i) {
126+
int64_t expandedDim = indices[i];
127+
if (!isConstantIntValue(sizes[expandedDim], 1))
128+
break;
129+
130+
basis.push_back(outputShape[expandedDim]);
131+
delinOffsets.push_back(offsets[expandedDim]);
132+
}
133+
134+
if (i != e) {
135+
int64_t expandedDim = indices[i];
136+
basis.push_back(outputShape[expandedDim]);
137+
delinOffsets.push_back(offsets[expandedDim]);
138+
newSize = sizes[expandedDim];
139+
i++;
140+
}
141+
142+
for (; i < e; ++i) {
143+
OpFoldResult fullSize = outputShape[indices[i]];
144+
basis.push_back(fullSize);
145+
delinOffsets.push_back(rewriter.getIndexAttr(0));
146+
newSize = mul(newSize, fullSize);
147+
}
148+
SmallVector<Value> offsetVals =
149+
llvm::map_to_vector(delinOffsets, [&](OpFoldResult ofr) {
150+
return getValueOrCreateConstantIndexOp(rewriter, loc, ofr);
151+
});
152+
OpFoldResult newOffset = rewriter
153+
.create<affine::AffineLinearizeIndexOp>(
154+
loc, offsetVals, basis, /*disjoint=*/true)
155+
.getResult();
156+
newOffsets.push_back(newOffset);
157+
newLengths.push_back(newSize);
158+
159+
// Only unit stride supported.
160+
newStrides.push_back(rewriter.getIndexAttr(1));
161+
}
162+
163+
// The shape of the result can be obtained from the sizes passed in.
164+
SmallVector<Value> dynDims;
165+
SmallVector<int64_t> shape;
166+
dispatchIndexOpFoldResults(sizes, dynDims, shape);
167+
RankedTensorType resultType = RankedTensorType::get(
168+
shape, expandShapeOp.getResultType().getElementType());
169+
170+
// Create a new ExtractSliceOp and ExpandShapeOp.
171+
Value newSliceOp = rewriter.create<tensor::ExtractSliceOp>(
172+
loc, expandShapeOp.getSrc(), newOffsets, newLengths, newStrides);
173+
auto newExpandShapeOp = rewriter.create<tensor::ExpandShapeOp>(
174+
loc, resultType, newSliceOp, expandShapeOp.getReassociationIndices(),
175+
sizes);
176+
rewriter.replaceOp(sliceOp, newExpandShapeOp);
177+
return success();
178+
}
179+
180+
namespace {
181+
182+
struct SwapExpandShapeWithSlicePattern
183+
: public OpRewritePattern<tensor::ExtractSliceOp> {
184+
using OpRewritePattern<tensor::ExtractSliceOp>::OpRewritePattern;
185+
186+
LogicalResult matchAndRewrite(tensor::ExtractSliceOp sliceOp,
187+
PatternRewriter &rewriter) const override {
188+
auto expandOp = sliceOp.getSource().getDefiningOp<tensor::ExpandShapeOp>();
189+
if (!expandOp) {
190+
return failure();
191+
}
192+
193+
if (!sliceOp.hasUnitStride()) {
194+
return rewriter.notifyMatchFailure(sliceOp,
195+
"unsupported: non-unit stride");
196+
}
197+
198+
return swapExpandShapeWithSlice(rewriter, expandOp, sliceOp);
199+
}
200+
};
201+
202+
} // namespace
203+
204+
void mlir::tensor::populateBubbleUpExtractSliceOpPatterns(
205+
RewritePatternSet &patterns) {
206+
patterns.add<SwapExpandShapeWithSlicePattern>(patterns.getContext());
207+
}

mlir/lib/Dialect/Tensor/Transforms/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ add_mlir_dialect_library(MLIRTensorTransforms
1111
RewriteAsConstant.cpp
1212
SwapExtractSliceWithProducerPatterns.cpp
1313
SubsetInsertionOpInterfaceImpl.cpp
14+
BubbleUpExtractSlice.cpp
1415

1516
ADDITIONAL_HEADER_DIRS
1617
${MLIR_MAIN_INCLUDE_DIR}/mlir/Dialect/Tensor/Transforms

mlir/test/Dialect/Linalg/transform-op-fuse.mlir

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,3 +278,141 @@ module attributes {transform.with_named_sequence} {
278278
transform.yield
279279
}
280280
}
281+
282+
// -----
283+
284+
// CHECK-LABEL: func.func @swap_expand_shape_with_extract_slice
285+
// CHECK: scf.for %[[X:[A-Za-z0-9]+]] = {{.*}}
286+
// CHECK: scf.for %[[Y:[A-Za-z0-9]+]] = {{.*}}
287+
// CHECK: scf.for %[[Z:[A-Za-z0-9]+]] = {{.*}}
288+
// CHECK: %[[LINEAR_IDX:.+]] = affine.linearize_index disjoint [%[[X]], %[[Y]], %[[Z]]] by (2, 3, 10)
289+
// CHECK: %[[SLICE:.+]] = tensor.extract_slice %{{.*}}[%[[LINEAR_IDX]]] [5] [1] : tensor<60xf32> to tensor<5xf32>
290+
// CHECK: %[[EXPAND:.+]] = tensor.expand_shape %[[SLICE]] {{\[\[}}0, 1, 2]] output_shape [1, 1, 5]
291+
// CHECK: linalg.exp ins(%[[EXPAND]]
292+
func.func @swap_expand_shape_with_extract_slice(%0: tensor<60xf32>) -> tensor<2x3x10xf32> {
293+
%expand = tensor.expand_shape %0 [[0, 1, 2]] output_shape [2, 3, 10] : tensor<60xf32> into tensor<2x3x10xf32>
294+
%empty = tensor.empty() : tensor<2x3x10xf32>
295+
%exp = linalg.exp ins(%expand : tensor<2x3x10xf32>) outs(%empty : tensor<2x3x10xf32>) -> tensor<2x3x10xf32>
296+
return %exp : tensor<2x3x10xf32>
297+
}
298+
299+
module attributes {transform.with_named_sequence} {
300+
transform.named_sequence @__transform_main(%arg0: !transform.any_op {transform.readonly}) {
301+
%0 = transform.structured.match ops{["linalg.exp"]} in %arg0 : (!transform.any_op) -> !transform.any_op
302+
%transformed, %loops:3 = transform.structured.fuse %0 [1, 1, 5] interchange [0, 1, 2] apply_cleanup = true :
303+
(!transform.any_op) -> (!transform.any_op, !transform.op<"scf.for">, !transform.any_op, !transform.any_op)
304+
transform.yield
305+
}
306+
}
307+
308+
// -----
309+
310+
// CHECK-LABEL: func.func @swap_expand_shape_with_extract_slice_full_inner_dim
311+
// CHECK: scf.for %[[X:[A-Za-z0-9]+]] = {{.*}}
312+
// CHECK: scf.for %[[Y:[A-Za-z0-9]+]] = {{.*}}
313+
// CHECK: %[[LINEAR_IDX:.+]] = affine.linearize_index disjoint [%[[X]], %[[Y]]{{.*}} by (3, 4, 10)
314+
// CHECK: %[[SLICE:.+]] = tensor.extract_slice %{{.*}}[%[[LINEAR_IDX]]] [20] [1] : tensor<120xf32> to tensor<20xf32>
315+
// CHECK: %[[EXPAND:.+]] = tensor.expand_shape %[[SLICE]] {{\[\[}}0, 1, 2]] output_shape [1, 2, 10]
316+
// CHECK: linalg.exp ins(%[[EXPAND]]
317+
func.func @swap_expand_shape_with_extract_slice_full_inner_dim(%0: tensor<120xf32>) -> tensor<3x4x10xf32> {
318+
%expand = tensor.expand_shape %0 [[0, 1, 2]] output_shape [3, 4, 10] : tensor<120xf32> into tensor<3x4x10xf32>
319+
%empty = tensor.empty() : tensor<3x4x10xf32>
320+
%exp = linalg.exp ins(%expand : tensor<3x4x10xf32>) outs(%empty : tensor<3x4x10xf32>) -> tensor<3x4x10xf32>
321+
return %exp : tensor<3x4x10xf32>
322+
}
323+
324+
module attributes {transform.with_named_sequence} {
325+
transform.named_sequence @__transform_main(%arg0: !transform.any_op {transform.readonly}) {
326+
%0 = transform.structured.match ops{["linalg.exp"]} in %arg0 : (!transform.any_op) -> !transform.any_op
327+
%transformed, %loops:2 = transform.structured.fuse %0 [1, 2, 0] interchange [0, 1, 2] apply_cleanup = true :
328+
(!transform.any_op) -> (!transform.any_op, !transform.op<"scf.for">, !transform.any_op)
329+
transform.yield
330+
}
331+
}
332+
333+
// -----
334+
335+
// CHECK-LABEL: func.func @swap_expand_shape_with_extract_slice_full_inner_dim
336+
// CHECK: tensor.expand_shape
337+
// CHECK: scf.for
338+
// CHECK: scf.for
339+
// CHECK: scf.for
340+
// CHECK: linalg.exp
341+
func.func @swap_expand_shape_with_extract_slice_full_inner_dim(%0: tensor<120xf32>) -> tensor<3x4x10xf32> {
342+
%expand = tensor.expand_shape %0 [[0, 1, 2]] output_shape [3, 4, 10] : tensor<120xf32> into tensor<3x4x10xf32>
343+
%empty = tensor.empty() : tensor<3x4x10xf32>
344+
%exp = linalg.exp ins(%expand : tensor<3x4x10xf32>) outs(%empty : tensor<3x4x10xf32>) -> tensor<3x4x10xf32>
345+
return %exp : tensor<3x4x10xf32>
346+
}
347+
348+
module attributes {transform.with_named_sequence} {
349+
transform.named_sequence @__transform_main(%arg0: !transform.any_op {transform.readonly}) {
350+
%0 = transform.structured.match ops{["linalg.exp"]} in %arg0 : (!transform.any_op) -> !transform.any_op
351+
%transformed, %loops:3 = transform.structured.fuse %0 [1, 2, 5] interchange [0, 1, 2] apply_cleanup = true :
352+
(!transform.any_op) -> (!transform.any_op, !transform.op<"scf.for">, !transform.any_op, !transform.any_op)
353+
transform.yield
354+
}
355+
}
356+
357+
// -----
358+
359+
// CHECK-LABEL: func.func @swap_expand_shape_with_extract_slice_multiple_expanded_dims
360+
// CHECK: %[[C0:.+]] = arith.constant 0 : index
361+
// CHECK: scf.for %[[X:[A-Za-z0-9]+]] = {{.*}}
362+
// CHECK: scf.for %[[Y:[A-Za-z0-9]+]] = {{.*}}
363+
// CHECK: scf.for %[[Z:[A-Za-z0-9]+]] = {{.*}}
364+
// CHECK: scf.for %[[W:[A-Za-z0-9]+]] = {{.*}}
365+
// CHECK: %[[LINEAR_IDX0:.+]] = affine.linearize_index disjoint [%[[X]], %[[Y]], %[[C0]]] by (3, 4, 10)
366+
// CHECK: %[[LINEAR_IDX1:.+]] = affine.linearize_index disjoint [%[[Z]], %[[W]]] by (7, 8)
367+
// CHECK: %[[SLICE:.+]] = tensor.extract_slice %{{.*}}[%[[LINEAR_IDX0]], %[[LINEAR_IDX1]]] [20, 4] [1, 1] : tensor<120x56xf32> to tensor<20x4xf32>
368+
// CHECK: %[[EXPAND:.+]] = tensor.expand_shape %[[SLICE]] {{\[\[}}0, 1, 2], [3, 4]] output_shape [1, 2, 10, 1, 4]
369+
// CHECK: linalg.exp ins(%[[EXPAND]]
370+
module {
371+
func.func @swap_expand_shape_with_extract_slice_multiple_expanded_dims(%0: tensor<120x56xf32>) -> tensor<3x4x10x7x8xf32> {
372+
%expand = tensor.expand_shape %0 [[0, 1, 2], [3, 4]] output_shape [3, 4, 10, 7, 8] : tensor<120x56xf32> into tensor<3x4x10x7x8xf32>
373+
%empty = tensor.empty() : tensor<3x4x10x7x8xf32>
374+
%exp = linalg.exp ins(%expand : tensor<3x4x10x7x8xf32>) outs(%empty : tensor<3x4x10x7x8xf32>) -> tensor<3x4x10x7x8xf32>
375+
return %exp : tensor<3x4x10x7x8xf32>
376+
}
377+
}
378+
379+
module attributes {transform.with_named_sequence} {
380+
transform.named_sequence @__transform_main(%arg0: !transform.any_op {transform.readonly}) {
381+
%0 = transform.structured.match ops{["linalg.exp"]} in %arg0 : (!transform.any_op) -> !transform.any_op
382+
%transformed, %loops:4 = transform.structured.fuse %0 [1, 2, 0, 1, 4] interchange [0, 1, 2, 3, 4] apply_cleanup = true :
383+
(!transform.any_op) -> (!transform.any_op, !transform.op<"scf.for">, !transform.any_op, !transform.any_op, !transform.any_op)
384+
transform.yield
385+
}
386+
}
387+
388+
// -----
389+
390+
// CHECK: scf.for %[[X:[A-Za-z0-9]+]] = {{.*}}
391+
// CHECK: %[[LINEAR_IDX:.+]] = affine.linearize_index disjoint [%[[X]], {{.*}} by (8, 32)
392+
// CHECK: %[[SLICE:.+]] = tensor.extract_slice %{{.*}}[0, 0, %[[LINEAR_IDX]]] [1, 1800, 32] [1, 1, 1] : tensor<1x1800x256xf32> to tensor<1x1800x32xf32>
393+
// CHECK: %[[ABS:.+]] = linalg.abs ins(%[[SLICE]]
394+
// CHECK: %[[EXPAND:.+]] = tensor.expand_shape %[[ABS]] {{\[\[}}0], [1], [2, 3]] output_shape [1, 1800, 1, 32]
395+
// CHECK: linalg.exp ins(%[[EXPAND]]
396+
module {
397+
func.func @swap_expand_shape_with_extract_slice_and_fuse_with_expand_producer(%0: tensor<1x1800x256xf32>) -> tensor<1x1800x8x32xf32> {
398+
%empty1 = tensor.empty() : tensor<1x1800x256xf32>
399+
%exp1 = linalg.abs ins(%0 : tensor<1x1800x256xf32>) outs(%empty1 : tensor<1x1800x256xf32>) -> tensor<1x1800x256xf32>
400+
%expand = tensor.expand_shape %exp1 [[0], [1], [2, 3]] output_shape [1, 1800, 8, 32] : tensor<1x1800x256xf32> into tensor<1x1800x8x32xf32>
401+
%empty2 = tensor.empty() : tensor<1x1800x8x32xf32>
402+
%exp2 = linalg.exp ins(%expand : tensor<1x1800x8x32xf32>) outs(%empty2 : tensor<1x1800x8x32xf32>) -> tensor<1x1800x8x32xf32>
403+
return %exp2 : tensor<1x1800x8x32xf32>
404+
}
405+
}
406+
407+
module attributes {transform.with_named_sequence} {
408+
transform.named_sequence @__transform_main(%arg0: !transform.any_op {transform.readonly}) {
409+
%0 = transform.structured.match ops{["linalg.exp"]} in %arg0 : (!transform.any_op) -> !transform.any_op
410+
%transformed, %loops:1 = transform.structured.fuse %0 [0, 0, 1, 0] interchange [0, 1, 2, 3] apply_cleanup = true :
411+
(!transform.any_op) -> (!transform.any_op, !transform.op<"scf.for">)
412+
transform.yield
413+
}
414+
}
415+
416+
417+
418+

0 commit comments

Comments
 (0)