Skip to content

Commit 7bb34e8

Browse files
hanhanWtensorflower-gardener
authored andcommitted
Add support for lowering variadic mhlo.reduce op.
Also add more lowering for body ops. Some MinOp and MaxOp can be legalized to SelectOp + CompareOp. PiperOrigin-RevId: 369891551 Change-Id: I292c08306184d4a60d7e8909b6f3da6358f61e58
1 parent 1a990bf commit 7bb34e8

2 files changed

Lines changed: 93 additions & 41 deletions

File tree

‎tensorflow/compiler/mlir/hlo/lib/Dialect/mhlo/transforms/legalize_to_linalg.cc‎

Lines changed: 50 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1473,8 +1473,8 @@ struct ReduceRegionXLAOpConversion : public OpConversionPattern<OpTy> {
14731473
})) {
14741474
return failure();
14751475
}
1476-
Value result = lmhlo::HloOpToStdScalarOp::map<OpTy>(op, args[0].getType(),
1477-
args, &rewriter);
1476+
Value result = lmhlo::HloOpToStdScalarOp::map<OpTy>(
1477+
op, getElementTypeOrSelf(op.getType()), args, &rewriter);
14781478
rewriter.replaceOp(op, result);
14791479
return success();
14801480
}
@@ -1518,58 +1518,65 @@ class ReduceOnTensorsConversion : public OpConversionPattern<mhlo::ReduceOp> {
15181518
ConversionPatternRewriter& rewriter) const final {
15191519
Location loc = op.getLoc();
15201520
mhlo::ReduceOp::Adaptor adaptor(args);
1521-
if (op.getNumOperands() != 2) {
1522-
return op.emitError("expects exactly two operands");
1523-
}
1524-
Value src = adaptor.inputs()[0];
1525-
auto src_type = src.getType().cast<ShapedType>();
1521+
1522+
int num_inputs = static_cast<int>(adaptor.inputs().size());
1523+
auto src_type = adaptor.inputs()[0].getType().cast<ShapedType>();
15261524
int src_rank = src_type.getRank();
15271525
if (!src_rank) {
15281526
return rewriter.notifyMatchFailure(op, "expects known-rank args");
15291527
}
15301528

1531-
// Check if init_value is constant. If so, inline the value into the region.
1532-
Value init_value = adaptor.init_values()[0];
1533-
Attribute init_const_val = GetInitValueAsConst(init_value);
1534-
if (init_const_val) {
1535-
init_value = rewriter.create<ConstantOp>(
1536-
init_value.getDefiningOp()->getLoc(), init_const_val);
1537-
} else {
1538-
init_value = rewriter.create<tensor::ExtractOp>(loc, init_value);
1529+
SmallVector<int64_t, 4> reduction_dims = Extract1DVector(op.dimensions());
1530+
1531+
SmallVector<Value> inputs, outputs;
1532+
SmallVector<AffineMap, 3> indexing_maps;
1533+
for (int i = 0; i < num_inputs; ++i) {
1534+
Value src = adaptor.inputs()[i];
1535+
if (src.getType() != src_type) return failure();
1536+
1537+
// Check if init_value is constant. If so, inline the value into the
1538+
// region.
1539+
Value init_value = adaptor.init_values()[i];
1540+
Attribute init_const_val = GetInitValueAsConst(init_value);
1541+
if (init_const_val) {
1542+
init_value = rewriter.create<ConstantOp>(
1543+
init_value.getDefiningOp()->getLoc(), init_const_val);
1544+
} else {
1545+
init_value = rewriter.create<tensor::ExtractOp>(loc, init_value);
1546+
}
1547+
1548+
inputs.push_back(src);
1549+
auto result_type = op.getResult(i).getType().cast<ShapedType>();
1550+
SmallVector<Value, 8> dyn_shape = GetReduceOpInitTensorDynSizes(
1551+
rewriter, loc, src, result_type, reduction_dims);
1552+
auto init_tensor = GetInitTensor(rewriter, loc, result_type, dyn_shape);
1553+
Value filled_tensor =
1554+
rewriter.create<linalg::FillOp>(loc, init_tensor, init_value)
1555+
.result();
1556+
outputs.push_back(filled_tensor);
15391557
}
15401558

1541-
// Prepare indexing maps for linalg generic op. The elements are for src and
1542-
// dst. Transpose `src` to make the reduction loops be the innermost,
1559+
// Prepare indexing maps for linalg generic op. The elements are for src
1560+
// and dst. Transpose `src` to make the reduction loops be the innermost,
15431561
// because it's easier to fully utilize processors.
1544-
SmallVector<AffineMap, 3> indexing_maps;
1545-
SmallVector<int64_t, 4> reduction_dims = Extract1DVector(op.dimensions());
1546-
indexing_maps.emplace_back(GetTransposeMapForReduction(
1547-
rewriter.getContext(), src_rank, reduction_dims));
1562+
indexing_maps.append(
1563+
num_inputs, GetTransposeMapForReduction(rewriter.getContext(), src_rank,
1564+
reduction_dims));
15481565

15491566
// The indexing map of `dst` should drop the reduction loops. Since the
15501567
// reduction loops now are all in the innermost, drops
1551-
// `reduction_dims.size()` dimensions. We don't need an inverse permutation
1552-
// here because they are the same.
1568+
// `reduction_dims.size()` dimensions. We don't need an inverse
1569+
// permutation here because they are the same.
15531570
SmallVector<AffineExpr, 4> exprs;
15541571
for (int i = 0, e = src_rank - reduction_dims.size(); i < e; ++i)
15551572
exprs.push_back(rewriter.getAffineDimExpr(i));
1556-
indexing_maps.emplace_back(AffineMap::get(src_rank, /*symbolCount=*/0,
1557-
exprs, rewriter.getContext()));
1558-
1559-
SmallVector<Value, 2> inputs = {adaptor.inputs()[0]};
1560-
Type result_type = op.getResult(0).getType();
1561-
auto shaped_type = result_type.cast<ShapedType>();
1562-
SmallVector<Value, 8> dyn_shape = GetReduceOpInitTensorDynSizes(
1563-
rewriter, loc, adaptor.inputs()[0], result_type.cast<ShapedType>(),
1564-
reduction_dims);
1565-
auto init_tensor = GetInitTensor(rewriter, loc, shaped_type, dyn_shape);
1566-
Value filled_tensor =
1567-
rewriter.create<linalg::FillOp>(loc, init_tensor, init_value)
1568-
.getResult(0);
1573+
indexing_maps.append(num_inputs,
1574+
AffineMap::get(src_rank, /*symbolCount=*/0, exprs,
1575+
rewriter.getContext()));
15691576

15701577
auto linalg_op = rewriter.create<linalg::GenericOp>(
15711578
loc, /*resultTensorTypes=*/op.getResultTypes(), inputs,
1572-
/*outputBuffers=*/ValueRange{filled_tensor}, indexing_maps,
1579+
/*outputBuffers=*/ValueRange{outputs}, indexing_maps,
15731580
GetParallelAndReductionIterators(src_rank, reduction_dims.size()));
15741581

15751582
// Convert the signature of the body. The reduce op region apply function
@@ -1579,10 +1586,10 @@ class ReduceOnTensorsConversion : public OpConversionPattern<mhlo::ReduceOp> {
15791586
// be converted to "(f32, f32, f32)".
15801587
Region& region = linalg_op.region();
15811588
rewriter.inlineRegionBefore(op.body(), region, region.end());
1582-
TypeConverter::SignatureConversion signatureConverter(2);
1583-
signatureConverter.addInputs(0, src_type.getElementType());
1584-
signatureConverter.addInputs(1, src_type.getElementType());
1585-
rewriter.applySignatureConversion(&region, signatureConverter);
1589+
TypeConverter::SignatureConversion signature_converter(num_inputs * 2);
1590+
for (int i = 0; i < num_inputs * 2; ++i)
1591+
signature_converter.addInputs(i, src_type.getElementType());
1592+
rewriter.applySignatureConversion(&region, signature_converter);
15861593
rewriter.replaceOp(op, linalg_op.getResults());
15871594
return success();
15881595
}
@@ -2272,6 +2279,8 @@ void populateHLOToLinalgConversionPattern(MLIRContext* context,
22722279
ReduceRegionXLAOpConversion<mhlo::MaxOp>,
22732280
ReduceRegionXLAOpConversion<mhlo::AndOp>,
22742281
ReduceRegionXLAOpConversion<mhlo::OrOp>,
2282+
ReduceRegionXLAOpConversion<mhlo::SelectOp>,
2283+
ReduceRegionXLAOpConversion<mhlo::CompareOp>,
22752284
ReduceRegionReturnOpConversion>(context);
22762285
}
22772286

‎tensorflow/compiler/mlir/hlo/tests/hlo-legalize-to-linalg.mlir‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1506,6 +1506,49 @@ func @reduce_dynamic(%arg0: tensor<?x?xi32>, %arg1: tensor<i32>) -> tensor<?xi32
15061506

15071507
// -----
15081508

1509+
func @variadic_reduce(%arg0: tensor<9x2xi32>, %arg1: tensor<9x2xi32>) -> (tensor<2xi32>, tensor<2xi32>) {
1510+
%cst0 = mhlo.constant dense<-2147483648> : tensor<i32>
1511+
%cst1 = mhlo.constant dense<0> : tensor<i32>
1512+
%res0, %res1 = "mhlo.reduce"(%arg0, %arg1, %cst0, %cst1) ( {
1513+
^bb0(%arg2: tensor<i32>, %arg3: tensor<i32>, %arg15: tensor<i32>, %arg16: tensor<i32>): // no predecessors
1514+
%669 = "mhlo.compare"(%arg2, %arg15) {comparison_direction = "GE"} : (tensor<i32>, tensor<i32>) -> tensor<i1>
1515+
%670 = "mhlo.select"(%669, %arg2, %arg15) : (tensor<i1>, tensor<i32>, tensor<i32>) -> tensor<i32>
1516+
%671 = "mhlo.compare"(%arg2, %arg15) {comparison_direction = "EQ"} : (tensor<i32>, tensor<i32>) -> tensor<i1>
1517+
%672 = mhlo.minimum %arg3, %arg16 : tensor<i32>
1518+
%673 = "mhlo.select"(%669, %arg3, %arg16) : (tensor<i1>, tensor<i32>, tensor<i32>) -> tensor<i32>
1519+
%674 = "mhlo.select"(%671, %672, %673) : (tensor<i1>, tensor<i32>, tensor<i32>) -> tensor<i32>
1520+
"mhlo.return"(%670, %674) : (tensor<i32>, tensor<i32>) -> ()
1521+
}) {dimensions = dense<0> : tensor<1xi64>} : (tensor<9x2xi32>, tensor<9x2xi32>, tensor<i32>, tensor<i32>) -> (tensor<2xi32>, tensor<2xi32>)
1522+
return %res0, %res1 : tensor<2xi32>, tensor<2xi32>
1523+
}
1524+
// CHECK-DAG: #[[MAP0:.*]] = affine_map<(d0, d1) -> (d1, d0)>
1525+
// CHECK-DAG: #[[MAP1:.*]] = affine_map<(d0, d1) -> (d0)>
1526+
// CHECK: func @variadic_reduce
1527+
// CHECK-SAME: %[[ARG0:[a-zA-Z0-9_]*]]
1528+
// CHECK-SAME: %[[ARG1:[a-zA-Z0-9_]*]]
1529+
// CHECK: %[[CST0:.*]] = constant -2147483648 : i32
1530+
// CHECK: %[[INIT0:.*]] = linalg.init_tensor [2] : tensor<2xi32>
1531+
// CHECK: %[[FILL0:.*]] = linalg.fill(%[[INIT0]], %[[CST0]])
1532+
// CHECK: %[[CST1:.*]] = constant 0 : i32
1533+
// CHECK: %[[INIT1:.*]] = linalg.init_tensor [2] : tensor<2xi32>
1534+
// CHECK: %[[FILL1:.*]] = linalg.fill(%[[INIT1]], %[[CST1]])
1535+
// CHECK: %[[RES:.+]]:2 = linalg.generic {
1536+
// CHECK-SAME: indexing_maps = [#[[MAP0]], #[[MAP0]], #[[MAP1]], #[[MAP1]]]
1537+
// CHECK-SAME: iterator_types = ["parallel", "reduction"]
1538+
// CHECK-SAME: ins(%[[ARG0]], %[[ARG1]] : tensor<9x2xi32>, tensor<9x2xi32>)
1539+
// CHECK-SAME: outs(%[[FILL0]], %[[FILL1]] : tensor<2xi32>, tensor<2xi32>)
1540+
// CHECK-NEXT: ^bb0(%[[IN0:.*]]: i32, %[[IN1:.*]]: i32, %[[OUT0:.*]]: i32, %[[OUT1:.*]]: i32):
1541+
// CHECK-NEXT: %[[T1:.*]] = cmpi sge, %[[IN0]], %[[OUT0]] : i32
1542+
// CHECK-NEXT: %[[T2:.*]] = select %[[T1]], %[[IN0]], %[[OUT0]] : i32
1543+
// CHECK-NEXT: %[[T3:.*]] = cmpi eq, %[[IN0]], %[[OUT0]] : i32
1544+
// CHECK-NEXT: %[[T4:.*]] = cmpi slt, %[[IN1]], %[[OUT1]] : i32
1545+
// CHECK-NEXT: %[[T5:.*]] = select %[[T4]], %[[IN1]], %[[OUT1]] : i32
1546+
// CHECK-NEXT: %[[T6:.*]] = select %[[T1]], %[[IN1]], %[[OUT1]] : i32
1547+
// CHECK-NEXT: %[[T7:.*]] = select %[[T3]], %[[T5]], %[[T6]] : i32
1548+
// CHECK-NEXT: linalg.yield %[[T2]], %[[T7]]
1549+
1550+
// -----
1551+
15091552
func @slice_whole_stride(%arg0: tensor<3x4xi32>) -> tensor<1x4xi32> {
15101553
%0 = "mhlo.slice"(%arg0) {
15111554
start_indices = dense<[1, 0]> : tensor<2xi64>,

0 commit comments

Comments
 (0)