Skip to content

[Torch] Add support for aten.round.decimals op #4166

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
48 changes: 48 additions & 0 deletions include/torch-mlir/Dialect/Torch/IR/GeneratedTorchOps.td
Original file line number Diff line number Diff line change
Expand Up @@ -4562,6 +4562,54 @@ def Torch_AtenRound_Op : Torch_Op<"aten.round_", [
}];
}

def Torch_AtenRoundDecimalsOp : Torch_Op<"aten.round.decimals", [
AllowsTypeRefinement,
HasValueSemantics,
ReadOnly
]> {
let summary = "Generated op for `aten::round.decimals : (Tensor, int) -> (Tensor)`";
let arguments = (ins
AnyTorchTensorType:$self,
Torch_IntType:$decimals
);
let results = (outs
AnyTorchOptionalTensorType:$result
);
let hasCustomAssemblyFormat = 1;
let extraClassDefinition = [{
ParseResult AtenRoundDecimalsOp::parse(OpAsmParser &parser, OperationState &result) {
return parseDefaultTorchOp(parser, result, 2, 1);
}
void AtenRoundDecimalsOp::print(OpAsmPrinter &printer) {
printDefaultTorchOp(printer, *this, 2, 1);
}
}];
let hasFolder = 1;
}

def Torch_AtenRound_DecimalsOp : Torch_Op<"aten.round_.decimals", [
IsTrailingUnderscoreInplaceVariant,
AllowsTypeRefinement
]> {
let summary = "Generated op for `aten::round_.decimals : (Tensor, int) -> (Tensor)`";
let arguments = (ins
Torch_NonValueTensorType:$self,
Torch_IntType:$decimals
);
let results = (outs
AnyTorchOptionalNonValueTensorType:$result
);
let hasCustomAssemblyFormat = 1;
let extraClassDefinition = [{
ParseResult AtenRound_DecimalsOp::parse(OpAsmParser &parser, OperationState &result) {
return parseDefaultTorchOp(parser, result, 2, 1);
}
void AtenRound_DecimalsOp::print(OpAsmPrinter &printer) {
printDefaultTorchOp(printer, *this, 2, 1);
}
}];
}

def Torch_AtenTruncOp : Torch_Op<"aten.trunc", [
AllowsTypeRefinement,
HasValueSemantics,
Expand Down
13 changes: 13 additions & 0 deletions lib/Dialect/Torch/IR/TorchOps.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1992,6 +1992,19 @@ OpFoldResult AtenCeilOp::fold(FoldAdaptor adaptor) {
return {};
}

//===----------------------------------------------------------------------===//
// AtenRoundDecimalsOp
//===----------------------------------------------------------------------===//

OpFoldResult AtenRoundDecimalsOp::fold(FoldAdaptor adaptor) {
auto resultType = dyn_cast<ValueTensorType>(getType());
if (resultType && resultType.hasDtype() &&
isa<mlir::IntegerType>(resultType.getDtype())) {
return getSelf();
}
return {};
}

//===----------------------------------------------------------------------===//
// AtenRoundOp
//===----------------------------------------------------------------------===//
Expand Down
8 changes: 8 additions & 0 deletions lib/Dialect/Torch/Transforms/AbstractInterpLibrary.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6750,6 +6750,10 @@ StringRef mlir::torch::Torch::getAbstractInterpLibrary() {
" %0 = call @__torch__.torch.jit._shape_functions.unary(%arg0) : (!torch.list<int>) -> !torch.list<int>\n"
" return %0 : !torch.list<int>\n"
" }\n"
" func.func @\"__torch_mlir_shape_fn.aten.round.decimals\"(%arg0: !torch.list<int>, %arg1: !torch.int) -> !torch.list<int> {\n"
" %0 = call @__torch__.torch.jit._shape_functions.unary(%arg0) : (!torch.list<int>) -> !torch.list<int>\n"
" return %0 : !torch.list<int>\n"
" }\n"
" func.func @\"__torch_mlir_shape_fn.aten.glu\"(%arg0: !torch.list<int>, %arg1: !torch.int) -> !torch.list<int> {\n"
" %none = torch.constant.none\n"
" %str = torch.constant.str \"AssertionError: glu's dim size must be multiply of 2\"\n"
Expand Down Expand Up @@ -12896,6 +12900,10 @@ StringRef mlir::torch::Torch::getAbstractInterpLibrary() {
" %0:2 = torch.prim.TupleUnpack %arg0 : !torch.tuple<int, int> -> !torch.int, !torch.int\n"
" return %0#1 : !torch.int\n"
" }\n"
" func.func @\"__torch_mlir_dtype_fn.aten.round.decimals\"(%arg0: !torch.tuple<int, int>, %arg1: !torch.int) -> !torch.int {\n"
" %0:2 = torch.prim.TupleUnpack %arg0 : !torch.tuple<int, int> -> !torch.int, !torch.int\n"
" return %0#1 : !torch.int\n"
" }\n"
" func.func @\"__torch_mlir_dtype_fn.aten.glu\"(%arg0: !torch.tuple<int, int>, %arg1: !torch.int) -> !torch.int {\n"
" %0:2 = torch.prim.TupleUnpack %arg0 : !torch.tuple<int, int> -> !torch.int, !torch.int\n"
" return %0#1 : !torch.int\n"
Expand Down
49 changes: 49 additions & 0 deletions lib/Dialect/Torch/Transforms/DecomposeComplexOps.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11804,6 +11804,54 @@ class DecomposeAten_AssertScalarOp
};
} // namespace

namespace {
class DecomposeAtenRoundDecimalsOp
: public OpRewritePattern<AtenRoundDecimalsOp> {
public:
using OpRewritePattern<AtenRoundDecimalsOp>::OpRewritePattern;
LogicalResult matchAndRewrite(AtenRoundDecimalsOp op,
PatternRewriter &rewriter) const override {
// AtenRoundDecimalsOp is decomposed as follows if the decimals value is
// non-zero: scale = 10 ** decimals return round(x * scale) / scale
// otherwise:
// return round(x)

auto loc = op.getLoc();
auto input = op.getSelf();
auto inputType = cast<BaseTensorType>(input.getType());

if (!inputType.hasDtype() || !isa<mlir::FloatType>(inputType.getDtype())) {
return rewriter.notifyMatchFailure(
op, "unimplemented: non-floating point dtype");
}

int64_t decimals;
if (!matchPattern(op.getDecimals(), m_TorchConstantInt(&decimals))) {
return rewriter.notifyMatchFailure(
op, "non-constant decimal point is not supported.");
}

Value newOp = op->getOperand(0);
Value scale;
if (decimals) {
auto scaleVal = pow(10, decimals);
scale = rewriter.create<ConstantFloatOp>(
loc, rewriter.getF64FloatAttr(scaleVal));
newOp = rewriter.create<AtenMulScalarOp>(loc, op.getType(), input, scale);
}

newOp = rewriter.create<AtenRoundOp>(loc, op.getType(), newOp);

if (decimals) {
newOp = rewriter.create<AtenDivScalarOp>(loc, op.getType(), newOp, scale);
}

rewriter.replaceOp(op, newOp);
return success();
}
};
} // namespace

namespace {
class DecomposeComplexOpsPass
: public DecomposeComplexOpsBase<DecomposeComplexOpsPass> {
Expand Down Expand Up @@ -12113,6 +12161,7 @@ class DecomposeComplexOpsPass
addPatternIfTargetOpIsIllegal<DecomposeAtenConstrainRangeForSizeOp>(
patterns);
addPatternIfTargetOpIsIllegal<DecomposeAten_AssertScalarOp>(patterns);
addPatternIfTargetOpIsIllegal<DecomposeAtenRoundDecimalsOp>(patterns);

GreedyRewriteConfig config;
config.setUseTopDownTraversal(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,9 @@ def aten〇relu6〡shape(self: List[int]) -> List[int]:
def aten〇round〡shape(self: List[int]) -> List[int]:
return upstream_shape_functions.unary(self)

def aten〇round〇decimals〡shape(self: List[int], decimals: int) -> List[int]:
return upstream_shape_functions.unary(self)

def aten〇glu〡shape(self: List[int], dim: int = -1) -> List[int]:
if dim < 0:
dim += len(self)
Expand Down Expand Up @@ -3616,6 +3619,11 @@ def aten〇round〡dtype(self_rank_dtype: Tuple[int, int]) -> int:
self_rank, self_dtype = self_rank_dtype
return self_dtype

@check_dtype_function(_check_tensors_with_the_same_dtype(num_of_tensors=1, decimals=0))
def aten〇round〇decimals〡dtype(self_rank_dtype: Tuple[int, int], decimals: int) -> int:
self_rank, self_dtype = self_rank_dtype
return self_dtype

@check_dtype_function(_check_tensors_with_the_same_dtype(tensor_shapes=[(100,)], dim=0))
def aten〇glu〡dtype(self_rank_dtype: Tuple[int, int], dim: int = -1) -> int:
self_rank, self_dtype = self_rank_dtype
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,9 @@ def emit_with_mutating_variants(key, **kwargs):
emit_with_mutating_variants("aten::floor : (Tensor) -> (Tensor)", has_folder=True)
emit_with_mutating_variants("aten::ceil : (Tensor) -> (Tensor)", has_folder=True)
emit_with_mutating_variants("aten::round : (Tensor) -> (Tensor)", has_folder=True)
emit_with_mutating_variants(
"aten::round.decimals : (Tensor, int) -> (Tensor)", has_folder=True
)
emit_with_mutating_variants("aten::trunc : (Tensor) -> (Tensor)", has_folder=True)
emit("aten::special_expm1 : (Tensor) -> (Tensor)")
emit_with_mutating_variants(
Expand Down
20 changes: 20 additions & 0 deletions projects/pt1/python/torch_mlir_e2e_test/test_suite/elementwise.py
Original file line number Diff line number Diff line change
Expand Up @@ -6503,6 +6503,26 @@ def AtenRoundIntModule_basic(module, tu: TestUtils):
module.forward(tu.randint(5, 5, low=-10))


class AtenRoundFloatDecimalsModule(torch.nn.Module):
def __init__(self):
super().__init__()

@export
@annotate_args(
[
None,
([-1, -1], torch.float32, True),
]
)
def forward(self, x):
return torch.ops.aten.round(x, decimals=2)


@register_test_case(module_factory=lambda: AtenRoundFloatDecimalsModule())
def AtenRoundFloatDecimalsModule_basic(module, tu: TestUtils):
module.forward(tu.rand(5, 5, low=-3.0, high=3.0))


# ==============================================================================


Expand Down
Loading