From 491ae5eda4cb1c21cae07187b94de91437b5744a Mon Sep 17 00:00:00 2001 From: Vivek Khandelwal Date: Wed, 26 Apr 2023 07:14:06 +0000 Subject: [PATCH] [MLIR][TORCH] Add E2E support for aten.var_mean.dim op This commit adds the decomposition for the aten.var_mean.dim op. Signed-Off By: Vivek Khandelwal --- e2e_testing/xfail_sets.py | 2 + .../Dialect/Torch/IR/GeneratedTorchOps.td | 27 ++++++++++++ .../Transforms/AbstractInterpLibrary.cpp | 12 ++++++ .../Torch/Transforms/DecomposeComplexOps.cpp | 23 +++++++++++ .../Transforms/LowerToBackendContract.cpp | 1 + .../build_tools/abstract_interp_lib_gen.py | 8 ++++ .../jit_ir/build_tools/torch_ods_gen.py | 1 + .../torch_mlir_e2e_test/test_suite/stats.py | 41 +++++++++++++++++++ 8 files changed, 115 insertions(+) diff --git a/e2e_testing/xfail_sets.py b/e2e_testing/xfail_sets.py index ef2ba02b2..cd52fb513 100644 --- a/e2e_testing/xfail_sets.py +++ b/e2e_testing/xfail_sets.py @@ -945,4 +945,6 @@ LTC_XFAIL_SET = { "PrimsViewOfModule_basic", "PrimsViewOfZeroRankModule_basic", "OneHotModule_basic", + "VarMeanDimModule_basic", + "VarMeanDimBiasedModule_basic", } diff --git a/include/torch-mlir/Dialect/Torch/IR/GeneratedTorchOps.td b/include/torch-mlir/Dialect/Torch/IR/GeneratedTorchOps.td index 614dfd6ca..c264f0df9 100644 --- a/include/torch-mlir/Dialect/Torch/IR/GeneratedTorchOps.td +++ b/include/torch-mlir/Dialect/Torch/IR/GeneratedTorchOps.td @@ -5385,6 +5385,33 @@ def Torch_AtenVarMeanOp : Torch_Op<"aten.var_mean", [ }]; } +def Torch_AtenVarMeanDimOp : Torch_Op<"aten.var_mean.dim", [ + AllowsTypeRefinement, + HasValueSemantics, + ReadOnly + ]> { + let summary = "Generated op for `aten::var_mean.dim : (Tensor, int[]?, bool, bool) -> (Tensor, Tensor)`"; + let arguments = (ins + AnyTorchTensorType:$self, + AnyTorchOptionalListOfTorchIntType:$dim, + Torch_BoolType:$unbiased, + Torch_BoolType:$keepdim + ); + let results = (outs + AnyTorchTensorType:$result0, + AnyTorchTensorType:$result1 + ); + let hasCustomAssemblyFormat = 1; + let extraClassDefinition = [{ + ParseResult AtenVarMeanDimOp::parse(OpAsmParser &parser, OperationState &result) { + return parseDefaultTorchOp(parser, result, 4, 2); + } + void AtenVarMeanDimOp::print(OpAsmPrinter &printer) { + printDefaultTorchOp(printer, *this, 4, 2); + } + }]; +} + def Torch_AtenNllLoss2dForwardOp : Torch_Op<"aten.nll_loss2d_forward", [ AllowsTypeRefinement, HasValueSemantics, diff --git a/lib/Dialect/Torch/Transforms/AbstractInterpLibrary.cpp b/lib/Dialect/Torch/Transforms/AbstractInterpLibrary.cpp index 5d38250e1..415ed0ac8 100644 --- a/lib/Dialect/Torch/Transforms/AbstractInterpLibrary.cpp +++ b/lib/Dialect/Torch/Transforms/AbstractInterpLibrary.cpp @@ -6501,6 +6501,18 @@ StringRef mlir::torch::Torch::getAbstractInterpLibrary() { " %2 = torch.prim.TupleConstruct %1, %1 : !torch.list, !torch.list -> !torch.tuple, list>\n" " return %2 : !torch.tuple, list>\n" " }\n" +" func.func @\"__torch_mlir_shape_fn.aten.var_mean.dim\"(%arg0: !torch.list, %arg1: !torch.optional>, %arg2: !torch.bool, %arg3: !torch.bool) -> !torch.tuple, list> {\n" +" %none = torch.constant.none\n" +" %0 = torch.derefine %none : !torch.none to !torch.any\n" +" %1 = call @__torch__.torch.jit._shape_functions.sum_mean_dim(%arg0, %arg1, %arg3, %0) : (!torch.list, !torch.optional>, !torch.bool, !torch.any) -> !torch.list\n" +" %2 = torch.prim.TupleConstruct %1, %1 : !torch.list, !torch.list -> !torch.tuple, list>\n" +" return %2 : !torch.tuple, list>\n" +" }\n" +" func.func @\"__torch_mlir_dtype_fn.aten.var_mean.dim\"(%arg0: !torch.tuple, %arg1: !torch.optional>, %arg2: !torch.bool, %arg3: !torch.bool) -> !torch.tuple {\n" +" %0:2 = torch.prim.TupleUnpack %arg0 : !torch.tuple -> !torch.int, !torch.int\n" +" %1 = torch.prim.TupleConstruct %0#1, %0#1 : !torch.int, !torch.int -> !torch.tuple\n" +" return %1 : !torch.tuple\n" +" }\n" " func.func @\"__torch_mlir_shape_fn.aten.var_mean\"(%arg0: !torch.list, %arg1: !torch.bool) -> !torch.tuple, list> {\n" " %0 = torch.prim.ListConstruct : () -> !torch.list\n" " %1 = torch.prim.ListConstruct : () -> !torch.list\n" diff --git a/lib/Dialect/Torch/Transforms/DecomposeComplexOps.cpp b/lib/Dialect/Torch/Transforms/DecomposeComplexOps.cpp index 040cc5f4e..9c245458c 100644 --- a/lib/Dialect/Torch/Transforms/DecomposeComplexOps.cpp +++ b/lib/Dialect/Torch/Transforms/DecomposeComplexOps.cpp @@ -4298,6 +4298,28 @@ class DecomposeAtenOneHotOp : public OpRewritePattern { } // namespace +namespace { +// Decompose `aten.var_mean.dim` op into `aten.var.dim` and +// `aten.mean.dim` op. +class DecomposeAtenVarMeanDimOp : public OpRewritePattern { +public: + using OpRewritePattern::OpRewritePattern; + LogicalResult matchAndRewrite(AtenVarMeanDimOp op, + PatternRewriter &rewriter) const override { + Location loc = op.getLoc(); + Value noneVal = rewriter.create(loc); + Value var = rewriter.create(loc, op.getType(0), op.getSelf(), + op.getDim(), op.getUnbiased(), + op.getKeepdim()); + Value mean = rewriter.create( + loc, op.getType(0), op.getSelf(), op.getDim(), op.getKeepdim(), + /*dtype=*/noneVal); + rewriter.replaceOp(op, {var, mean}); + return success(); + } +}; +} // namespace + namespace { class DecomposeComplexOpsPass : public DecomposeComplexOpsBase { @@ -4460,6 +4482,7 @@ public: addPatternIfTargetOpIsIllegal(patterns); addPatternIfTargetOpIsIllegal(patterns); addPatternIfTargetOpIsIllegal(patterns); + addPatternIfTargetOpIsIllegal(patterns); GreedyRewriteConfig config; config.useTopDownTraversal = true; diff --git a/lib/Dialect/Torch/Transforms/LowerToBackendContract.cpp b/lib/Dialect/Torch/Transforms/LowerToBackendContract.cpp index 7940cf81f..2c712ffb4 100644 --- a/lib/Dialect/Torch/Transforms/LowerToBackendContract.cpp +++ b/lib/Dialect/Torch/Transforms/LowerToBackendContract.cpp @@ -476,6 +476,7 @@ static void markDecomposedOpsAsIllegal(MLIRContext *context, target.addIllegalOp(); target.addIllegalOp(); target.addIllegalOp(); + target.addIllegalOp(); for (auto &opName : backendLegalOpsSet) { target.addLegalOp( OperationName(kTorchOpPrefix + opName.first().str(), context)); diff --git a/python/torch_mlir/dialects/torch/importer/jit_ir/build_tools/abstract_interp_lib_gen.py b/python/torch_mlir/dialects/torch/importer/jit_ir/build_tools/abstract_interp_lib_gen.py index 84f1ccc4e..28fb4bbba 100644 --- a/python/torch_mlir/dialects/torch/importer/jit_ir/build_tools/abstract_interp_lib_gen.py +++ b/python/torch_mlir/dialects/torch/importer/jit_ir/build_tools/abstract_interp_lib_gen.py @@ -332,6 +332,14 @@ def aten〇var_mean〇correction〡shape(self: List[int], dim: Optional[List[int out = upstream_shape_functions.sum_mean_dim(self, dim, keepdim, None) return out, out +def aten〇var_mean〇dim〡shape(self: List[int], dim: Optional[List[int]], unbiased: bool = True, keepdim: bool = False) -> Tuple[List[int], List[int]]: + out = upstream_shape_functions.sum_mean_dim(self, dim, keepdim, None) + return out, out + +def aten〇var_mean〇dim〡dtype(self_rank_dtype: Tuple[int, int], dim: Optional[List[int]], unbiased: bool = True, keepdim: bool = False) -> Tuple[int, int]: + _, self_dtype = self_rank_dtype + return self_dtype, self_dtype + def aten〇var_mean〡shape(self: List[int], unbiased: bool = True) -> Tuple[List[int], List[int]]: return [], [] diff --git a/python/torch_mlir/dialects/torch/importer/jit_ir/build_tools/torch_ods_gen.py b/python/torch_mlir/dialects/torch/importer/jit_ir/build_tools/torch_ods_gen.py index 1aef60af8..bec43fc1e 100644 --- a/python/torch_mlir/dialects/torch/importer/jit_ir/build_tools/torch_ods_gen.py +++ b/python/torch_mlir/dialects/torch/importer/jit_ir/build_tools/torch_ods_gen.py @@ -422,6 +422,7 @@ def emit_ops(emitter_td: TextEmitter, registry: Registry): emit("aten::var.correction : (Tensor, int[]?, Scalar?, bool) -> (Tensor)") emit("aten::var_mean.correction : (Tensor, int[]?, Scalar?, bool) -> (Tensor, Tensor)") emit("aten::var_mean : (Tensor, bool) -> (Tensor, Tensor)") + emit("aten::var_mean.dim : (Tensor, int[]?, bool, bool) -> (Tensor, Tensor)") emit("aten::nll_loss2d_forward : (Tensor, Tensor, Tensor?, int, int) -> (Tensor, Tensor)") emit("aten::nll_loss2d_backward : (Tensor, Tensor, Tensor, Tensor?, int, int, Tensor) -> (Tensor)") emit("aten::nll_loss_forward : (Tensor, Tensor, Tensor?, int, int) -> (Tensor, Tensor)") diff --git a/python/torch_mlir_e2e_test/test_suite/stats.py b/python/torch_mlir_e2e_test/test_suite/stats.py index 26ac9aabd..c6398b48e 100644 --- a/python/torch_mlir_e2e_test/test_suite/stats.py +++ b/python/torch_mlir_e2e_test/test_suite/stats.py @@ -1000,3 +1000,44 @@ class VarMeanBiasedModule(torch.nn.Module): @register_test_case(module_factory=lambda: VarMeanBiasedModule()) def VarMeanBiasedModule_basic(module, tu: TestUtils): module.forward(tu.rand(3, 4, 7)) + + +# ============================================================================== + + +class VarMeanDimModule(torch.nn.Module): + + def __init__(self): + super().__init__() + + @export + @annotate_args([ + None, + ([-1, -1, -1], torch.float32, True), + ]) + def forward(self, x): + return torch.ops.aten.var_mean(x, dim=[1]) + + +@register_test_case(module_factory=lambda: VarMeanDimModule()) +def VarMeanDimModule_basic(module, tu: TestUtils): + module.forward(tu.rand(3, 4, 7)) + + +class VarMeanDimBiasedModule(torch.nn.Module): + + def __init__(self): + super().__init__() + + @export + @annotate_args([ + None, + ([-1, -1, -1], torch.float32, True), + ]) + def forward(self, x): + return torch.ops.aten.var_mean(x, dim=[1], unbiased=False, keepdim=True) + + +@register_test_case(module_factory=lambda: VarMeanDimBiasedModule()) +def VarMeanDimBiasedModule_basic(module, tu: TestUtils): + module.forward(tu.rand(3, 4, 7))