Skip to content

[StableHLO] Add onnx.Dim lowering to StableHLO #2738

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Conversion/ONNXToStablehlo/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ add_onnx_mlir_library(OMONNXToStablehlo
Tensor/Concat.cpp
Tensor/Constant.cpp
Tensor/DepthToSpace.cpp
Tensor/Dim.cpp
Tensor/Expand.cpp
Tensor/Flatten.cpp
Tensor/Gather.cpp
Expand Down
2 changes: 2 additions & 0 deletions src/Conversion/ONNXToStablehlo/ConvertONNXToStablehlo.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ void populateONNXToStablehloConversionPattern(
populateLoweringONNXConcatOpToStablehloPattern(patterns, ctx);
populateLoweringONNXConstantOpToStablehloPattern(patterns, ctx);
populateLoweringONNXDepthToSpaceOpToStablehloPattern(patterns, ctx);
populateLoweringONNXDimOpToStablehloPattern(patterns, ctx);
populateLoweringONNXExpandOpToStablehloPattern(patterns, ctx);
populateLoweringONNXFlattenOpToStablehloPattern(patterns, ctx);
populateLoweringONNXGatherOpToStablehloPattern(patterns, ctx);
Expand Down Expand Up @@ -87,6 +88,7 @@ struct FrontendToStablehloLoweringPass

void getDependentDialects(DialectRegistry &registry) const override {
registry.insert<mlir::stablehlo::StablehloDialect>();
registry.insert<mlir::arith::ArithDialect>();
registry.insert<shape::ShapeDialect>();
}

Expand Down
2 changes: 2 additions & 0 deletions src/Conversion/ONNXToStablehlo/ONNXToStablehloCommon.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,8 @@ void populateLoweringONNXConcatOpToStablehloPattern(
RewritePatternSet &, MLIRContext *);
void populateLoweringONNXConstantOpToStablehloPattern(
RewritePatternSet &, MLIRContext *);
void populateLoweringONNXDimOpToStablehloPattern(
RewritePatternSet &, MLIRContext *);
void populateLoweringONNXDepthToSpaceOpToStablehloPattern(
RewritePatternSet &, MLIRContext *);
void populateLoweringONNXExpandOpToStablehloPattern(
Expand Down
64 changes: 64 additions & 0 deletions src/Conversion/ONNXToStablehlo/Tensor/Dim.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/

//===----------------- Dim.cpp - Lowering Dim Op ----------------===//
//
// Copyright 2022-2024
//
// =============================================================================
//
// This file lowers the ONNXDim operator to the Tensor dialect.
//
//===----------------------------------------------------------------------===//

#include "src/Conversion/ONNXToStablehlo/ONNXToStablehloCommon.hpp"

using namespace mlir;

namespace onnx_mlir {

namespace {

struct ONNXDimOpLoweringToStablehlo : public ConversionPattern {
ONNXDimOpLoweringToStablehlo(MLIRContext *ctx)
: ConversionPattern(ONNXDimOp::getOperationName(), 1, ctx) {}

LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final {
Location loc = op->getLoc();
ONNXDimOp dimOp = cast<ONNXDimOp>(op);
int64_t axis = dimOp.getAxis();

// Check that axis is a valid dimension index
Value tensorArg = operands[0];
assert(tensorArg.getType().isa<RankedTensorType>() &&
"Expected ranked tensor type");

RankedTensorType tensorType = tensorArg.getType().cast<RankedTensorType>();
int64_t rank = tensorType.getRank();

assert((axis >= 0 && axis < rank) &&
"Axis must be in the range [0, input tensor rank - 1]");

Value dimValue = rewriter.create<tensor::DimOp>(loc, tensorArg, axis);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we use stablehlo.get_dimension_size so we don't need to use tensor dialect?

Copy link
Collaborator Author

@brnorris03 brnorris03 Mar 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possibly, but it does make this way more complex than the tensor option, primarily because stablehlo.get_dimension_size returns tensor<i32> which must then be converted to the tensor<1x64> expected result type (so both the shape and size of the element type change). And of course there is a chance for overflow if the results exceeds i32 (which wouldn't happen with thetensor conversion). I think that in general it would be best to avoid i64 -> i32 -> i64 conversions.

Copy link
Collaborator Author

@brnorris03 brnorris03 Mar 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a particular reason why the tensor dialect should be avoided? I am also able to use the shape dialect (a bit more verbosely) for this, but that gets lowered to the tensor.dim op anyway. I also don't know how to avoid using tensor.from_elements (which is used in the lowering of a couple of other ops).

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps, @Connor-XY would like to use stablehlo ops at this level as many as possible. Not sure why stablehlo.get_dimension_size returns tensor<i32> while its input axis is small but i64 :)

Copy link
Collaborator Author

@brnorris03 brnorris03 Mar 6, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's understandable, but I don't actually see how I can avoid using tensor dialect ops entirely here. And also don't quite understand why I should avoid the ones (e.g., tensor.from_elements) that are already used in merged conversions. Also if using stablehlo.get_dimension_size, I am not able to successfully do the different-size index type conversions (i32->i64, going through index doesn't work). Any suggestions?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I would like to convert it to stablehlo ops as much as we can. It is fine to convert it to shape or tensor dialect if it is hard to do so with pure stablehlo ops. It is possible to use stablehlo.get_dimension_size to get tensor<i32>, then stablehlo.reshape to get tensor<1xi32>, and then stablehlo.convert to convert it from tensor<1xi32> to tensor<1xi64>.


Type dimType = dimOp.getDim().getType();
Type indexValueType = dimType.cast<ShapedType>().getElementType();
Value castedIndex =
rewriter.create<arith::IndexCastOp>(loc, indexValueType, dimValue);
Value indexTensor = rewriter.create<tensor::FromElementsOp>(
loc, dimType, ArrayRef<Value>{castedIndex});
rewriter.replaceOp(op, indexTensor);
return success();
}
};

} // namespace

void populateLoweringONNXDimOpToStablehloPattern(
RewritePatternSet &patterns, MLIRContext *ctx) {
patterns.insert<ONNXDimOpLoweringToStablehlo>(ctx);
}

} // namespace onnx_mlir
12 changes: 8 additions & 4 deletions src/Dialect/ONNX/ONNXOps/Additional/Dim.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,16 @@ LogicalResult ONNXDimOpShapeHelper::computeShape() {
//===----------------------------------------------------------------------===//

LogicalResult ONNXDimOp::verify() {
// Input data must be ranked.
if (!hasShapeAndRank(this->getData()))
return failure();
// Axis must be in [0, rank -1].
return emitOpError("input must have shape and rank.");

int64_t axis = this->getAxis();
return failure((axis < 0) || (axis >= getRank(this->getData().getType())));
if ((axis < 0) || (axis >= getRank(this->getData().getType())))
return emitOpError("attribute ")
<< ONNXDimOp::getAxisAttrName() << " value is " << axis
<< ", accepted range is [0, "
<< getRank(this->getData().getType()) - 1 << "].";
return success();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks so much for the explicit error messages! Really appreciate it.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:-) You are welcome!

}

//===----------------------------------------------------------------------===//
Expand Down
29 changes: 29 additions & 0 deletions test/mlir/conversion/onnx_to_stablehlo/Tensor/Dim.mlir
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// RUN: onnx-mlir-opt --convert-onnx-to-stablehlo --canonicalize %s -split-input-file -verify-diagnostics | FileCheck %s

// -----

func.func @test_dim_1(%arg0 : tensor<5x?x1x32xf32>) -> tensor<1xi64> {
%1 = "onnx.Dim"(%arg0) { axis = 1 : si64} : (tensor<5x?x1x32xf32>) -> tensor<1xi64>
return %1 : tensor<1xi64>
}
// CHECK-LABEL: func.func @test_dim_1
// CHECK-SAME: ([[PARAM:%.+]]: tensor<5x?x1x32xf32>) -> tensor<1xi64> {
// CHECK-NEXT: [[CONST_1:%.+]] = arith.constant 1 : index
// CHECK-NEXT: [[DIM:%.+]] = tensor.dim [[PARAM]], [[CONST_1]] : tensor<5x?x1x32xf32>
// CHECK-NEXT: [[INDEX_CAST:%.+]] = arith.index_cast [[DIM]] : index to i64
// CHECK-NEXT: [[FROM_ELEMENTS:%.+]] = tensor.from_elements [[INDEX_CAST]] : tensor<1xi64>
// CHECK-NEXT: return [[FROM_ELEMENTS]] : tensor<1xi64>
// CHECK: }

// -----

func.func @test_dim_2(%arg0 : tensor<5x7xf32>) -> tensor<1xi64> {
%1 = "onnx.Dim"(%arg0) { axis = 0 : si64} : (tensor<5x7xf32>) -> tensor<1xi64>
return %1 : tensor<1xi64>
}

// CHECK-LABEL: func.func @test_dim_2
// CHECK-SAME: ([[PARAM:%.+]]: tensor<5x7xf32>) -> tensor<1xi64> {
// CHECK-NEXT: [[CONST:%.+]] = arith.constant dense<5> : tensor<1xi64>
// CHECK-NEXT: return [[CONST]] : tensor<1xi64>
// CHECK: }
16 changes: 16 additions & 0 deletions test/mlir/onnx/invalid.mlir
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,22 @@ func.func @test_concat_from_sequence_verifier_2(%arg0 : !onnx.Seq<tensor<5x5x1x3

// -----

func.func @test_dim_verifier_1(%arg0 : tensor<*xf32>) -> tensor<i64> {
// expected-error @+1 {{input must have shape and rank}}
%1 = "onnx.Dim"(%arg0) {axis = 0 : si64} : (tensor<*xf32>) -> tensor<i64>
"onnx.Return"(%1) : (tensor<i64>) -> ()
}

// -----

func.func @test_dim_verifier_2(%arg0 : tensor<5x5xf32>) -> tensor<i64> {
// expected-error @+1 {{'onnx.Dim' op attribute "axis" value is -1, accepted range is [0, 1].}}
%1 = "onnx.Dim"(%arg0) {axis = -1 : si64} : (tensor<5x5xf32>) -> tensor<i64>
"onnx.Return"(%1) : (tensor<i64>) -> ()
}

// -----

func.func @test_dequantize_linear_verifier_1(%arg0 : tensor<5x5x1xi32>, %arg1 : tensor<3xf32>, %arg2 : tensor<3xi32>) -> tensor<*xf32> {
// expected-error @+1 {{onnx.DequantizeLinear: 'axis' value is 3, accepted range is [-3, 2]}}
%1 = "onnx.DequantizeLinear"(%arg0, %arg1, %arg2) {axis = 3 : si64} : (tensor<5x5x1xi32>, tensor<3xf32>, tensor<3xi32>) -> tensor<*xf32>
Expand Down