[torch] emit aten.Softshrink and aten.Hardshrink (#3248)

as title
pull/3300/head
Xinyu Yang 2024-05-08 15:20:45 +08:00 committed by GitHub
parent c77f3b559a
commit abef114c0c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 309 additions and 0 deletions

View File

@ -5019,6 +5019,54 @@ def Torch_AtenLogSigmoidOp : Torch_Op<"aten.log_sigmoid", [
}]; }];
} }
def Torch_AtenHardshrinkOp : Torch_Op<"aten.hardshrink", [
AllowsTypeRefinement,
HasValueSemantics,
ReadOnly
]> {
let summary = "Generated op for `aten::hardshrink : (Tensor, Scalar) -> (Tensor)`";
let arguments = (ins
AnyTorchTensorType:$self,
AnyTorchScalarType:$lambd
);
let results = (outs
AnyTorchOptionalTensorType:$result
);
let hasCustomAssemblyFormat = 1;
let extraClassDefinition = [{
ParseResult AtenHardshrinkOp::parse(OpAsmParser &parser, OperationState &result) {
return parseDefaultTorchOp(parser, result, 2, 1);
}
void AtenHardshrinkOp::print(OpAsmPrinter &printer) {
printDefaultTorchOp(printer, *this, 2, 1);
}
}];
}
def Torch_AtenSoftshrinkOp : Torch_Op<"aten.softshrink", [
AllowsTypeRefinement,
HasValueSemantics,
ReadOnly
]> {
let summary = "Generated op for `aten::softshrink : (Tensor, Scalar) -> (Tensor)`";
let arguments = (ins
AnyTorchTensorType:$self,
AnyTorchScalarType:$lambd
);
let results = (outs
AnyTorchOptionalTensorType:$result
);
let hasCustomAssemblyFormat = 1;
let extraClassDefinition = [{
ParseResult AtenSoftshrinkOp::parse(OpAsmParser &parser, OperationState &result) {
return parseDefaultTorchOp(parser, result, 2, 1);
}
void AtenSoftshrinkOp::print(OpAsmPrinter &printer) {
printDefaultTorchOp(printer, *this, 2, 1);
}
}];
}
def Torch_AtenUnbindCopyIntOp : Torch_Op<"aten.unbind_copy.int", [ def Torch_AtenUnbindCopyIntOp : Torch_Op<"aten.unbind_copy.int", [
AllowsTypeRefinement, AllowsTypeRefinement,
HasValueSemantics, HasValueSemantics,

View File

@ -6514,6 +6514,14 @@ StringRef mlir::torch::Torch::getAbstractInterpLibrary() {
" %0 = call @__torch__.torch.jit._shape_functions.unary(%arg0) : (!torch.list<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" " return %0 : !torch.list<int>\n"
" }\n" " }\n"
" func.func @\"__torch_mlir_shape_fn.aten.hardshrink\"(%arg0: !torch.list<int>, %arg1: !torch.float) -> !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.softshrink\"(%arg0: !torch.list<int>, %arg1: !torch.float) -> !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.mish\"(%arg0: !torch.list<int>) -> !torch.list<int> {\n" " func.func @\"__torch_mlir_shape_fn.aten.mish\"(%arg0: !torch.list<int>) -> !torch.list<int> {\n"
" %0 = call @__torch__.torch.jit._shape_functions.unary(%arg0) : (!torch.list<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" " return %0 : !torch.list<int>\n"
@ -9798,6 +9806,23 @@ StringRef mlir::torch::Torch::getAbstractInterpLibrary() {
" }\n" " }\n"
" return %0#1 : !torch.int\n" " return %0#1 : !torch.int\n"
" }\n" " }\n"
" func.func @\"__torch_mlir_dtype_fn.aten.hardshrink\"(%arg0: !torch.tuple<int, int>, %arg1: !torch.number) -> !torch.int {\n"
" %int4 = torch.constant.int 4\n"
" %int11 = torch.constant.int 11\n"
" %0:2 = torch.prim.TupleUnpack %arg0 : !torch.tuple<int, int> -> !torch.int, !torch.int\n"
" %1 = torch.aten.eq.int %0#1, %int11 : !torch.int, !torch.int -> !torch.bool\n"
" %2 = torch.prim.If %1 -> (!torch.int) {\n"
" torch.prim.If.yield %int4 : !torch.int\n"
" } else {\n"
" torch.prim.If.yield %0#1 : !torch.int\n"
" }\n"
" return %2 : !torch.int\n"
" }\n"
" func.func @\"__torch_mlir_dtype_fn.aten.softshrink\"(%arg0: !torch.tuple<int, int>, %arg1: !torch.number) -> !torch.int {\n"
" %0:2 = torch.prim.TupleUnpack %arg0 : !torch.tuple<int, int> -> !torch.int, !torch.int\n"
" %1 = call @__torch__._get_dtype_of_floating_point_op(%0#1) : (!torch.int) -> !torch.int\n"
" return %1 : !torch.int\n"
" }\n"
" func.func @\"__torch_mlir_dtype_fn.aten.logit\"(%arg0: !torch.tuple<int, int>, %arg1: !torch.optional<float>) -> !torch.int {\n" " func.func @\"__torch_mlir_dtype_fn.aten.logit\"(%arg0: !torch.tuple<int, int>, %arg1: !torch.optional<float>) -> !torch.int {\n"
" %0:2 = torch.prim.TupleUnpack %arg0 : !torch.tuple<int, int> -> !torch.int, !torch.int\n" " %0:2 = torch.prim.TupleUnpack %arg0 : !torch.tuple<int, int> -> !torch.int, !torch.int\n"
" %1 = call @__torch__._get_dtype_of_floating_point_op(%0#1) : (!torch.int) -> !torch.int\n" " %1 = call @__torch__._get_dtype_of_floating_point_op(%0#1) : (!torch.int) -> !torch.int\n"

View File

@ -1913,6 +1913,120 @@ public:
}; };
} // namespace } // namespace
// SoftShrink(x, lambda) function:
// Applies a shrinkage function where:
// - If x > lambda, returns x - lambda
// - If x < -lambda, returns x + lambda
// - Otherwise, returns 0
namespace {
class DecomposeAtenSoftshrinkOp : public OpRewritePattern<AtenSoftshrinkOp> {
public:
using OpRewritePattern<AtenSoftshrinkOp>::OpRewritePattern;
LogicalResult matchAndRewrite(AtenSoftshrinkOp op,
PatternRewriter &rewriter) const override {
Location loc = op.getLoc();
Value self = op.getSelf();
Value lambdValue = op.getLambd();
auto resTy = dyn_cast<ValueTensorType>(op.getType());
if (!resTy || !resTy.hasDtype() || !resTy.hasSizes()) {
return rewriter.notifyMatchFailure(op,
"result should have dtype and size");
}
double lambd;
if (!matchPattern(lambdValue, m_TorchConstantFloat(&lambd))) {
return rewriter.notifyMatchFailure(
op, "expected lambd to be a constant float");
}
Value zero =
rewriter.create<ConstantFloatOp>(loc, rewriter.getF64FloatAttr(0.0));
Value neglambd = rewriter.create<Torch::ConstantFloatOp>(
loc, rewriter.getF64FloatAttr(-lambd));
Value poslambd = rewriter.create<Torch::ConstantFloatOp>(
loc, rewriter.getF64FloatAttr(lambd));
Value constOneFloat =
rewriter.create<ConstantFloatOp>(loc, rewriter.getF64FloatAttr(1.0));
auto boolResType =
resTy.getWithSizesAndDtype(resTy.getSizes(), rewriter.getI1Type());
Value posMask =
rewriter.create<AtenGtScalarOp>(loc, boolResType, self, poslambd);
Value negMask =
rewriter.create<AtenLtScalarOp>(loc, boolResType, self, neglambd);
Value posValue = rewriter.create<AtenSubScalarOp>(loc, resTy, self,
poslambd, constOneFloat);
Value negValue = rewriter.create<AtenAddScalarOp>(loc, resTy, self,
neglambd, constOneFloat);
Value result = rewriter.create<AtenWhereScalarOtherOp>(loc, resTy, posMask,
posValue, zero);
result =
rewriter.create<AtenWhereSelfOp>(loc, resTy, negMask, negValue, result);
rewriter.replaceOp(op, result);
return success();
}
};
} // namespace
// HardShrink(x, lambda) function:
// Applies a shrinkage function where:
// - If x > lambda, returns x
// - If x < -lambda, returns x
// - Otherwise, returns 0
namespace {
class DecomposeAtenHardshrinkOp : public OpRewritePattern<AtenHardshrinkOp> {
public:
using OpRewritePattern<AtenHardshrinkOp>::OpRewritePattern;
LogicalResult matchAndRewrite(AtenHardshrinkOp op,
PatternRewriter &rewriter) const override {
Location loc = op.getLoc();
Value self = op.getSelf();
Value lambdValue = op.getLambd();
auto resTy = dyn_cast<ValueTensorType>(op.getType());
if (!resTy || !resTy.hasDtype() || !resTy.hasSizes()) {
return rewriter.notifyMatchFailure(op,
"result should have dtype and size");
}
double lambd;
if (!matchPattern(lambdValue, m_TorchConstantFloat(&lambd))) {
return rewriter.notifyMatchFailure(
op, "expected lambd to be a constant float");
}
Value zero =
rewriter.create<ConstantFloatOp>(loc, rewriter.getF64FloatAttr(0.0));
Value neglambd = rewriter.create<Torch::ConstantFloatOp>(
loc, rewriter.getF64FloatAttr(-lambd));
Value poslambd = rewriter.create<Torch::ConstantFloatOp>(
loc, rewriter.getF64FloatAttr(lambd));
auto boolResType =
resTy.getWithSizesAndDtype(resTy.getSizes(), rewriter.getI1Type());
Value posMask =
rewriter.create<AtenGtScalarOp>(loc, boolResType, self, poslambd);
Value negMask =
rewriter.create<AtenLtScalarOp>(loc, boolResType, self, neglambd);
Value result = rewriter.create<AtenWhereScalarOtherOp>(loc, resTy, posMask,
self, zero);
result =
rewriter.create<AtenWhereSelfOp>(loc, resTy, negMask, self, result);
rewriter.replaceOp(op, result);
return success();
}
};
} // namespace
// Decompose aten.matmul into: aten.mm and aten.bmm according to ranks. // Decompose aten.matmul into: aten.mm and aten.bmm according to ranks.
namespace { namespace {
class DecomposeAtenMatmulOp : public OpRewritePattern<AtenMatmulOp> { class DecomposeAtenMatmulOp : public OpRewritePattern<AtenMatmulOp> {
@ -7664,6 +7778,8 @@ public:
addPatternIfTargetOpIsIllegal<DecomposeAten_LogSoftmaxOp>(patterns); addPatternIfTargetOpIsIllegal<DecomposeAten_LogSoftmaxOp>(patterns);
addPatternIfTargetOpIsIllegal<DecomposeAtenLogSoftmaxIntOp>(patterns); addPatternIfTargetOpIsIllegal<DecomposeAtenLogSoftmaxIntOp>(patterns);
addPatternIfTargetOpIsIllegal<DecomposeAtenLogSigmoidOp>(patterns); addPatternIfTargetOpIsIllegal<DecomposeAtenLogSigmoidOp>(patterns);
addPatternIfTargetOpIsIllegal<DecomposeAtenHardshrinkOp>(patterns);
addPatternIfTargetOpIsIllegal<DecomposeAtenSoftshrinkOp>(patterns);
addPatternIfTargetOpIsIllegal<DecomposeAtenEmptyLikeOp>(patterns); addPatternIfTargetOpIsIllegal<DecomposeAtenEmptyLikeOp>(patterns);
addPatternIfTargetOpIsIllegal< addPatternIfTargetOpIsIllegal<
DecomposeConstantTensorAllocLikeOp<AtenOnesLikeOp, 1>>(patterns); DecomposeConstantTensorAllocLikeOp<AtenOnesLikeOp, 1>>(patterns);

View File

@ -371,6 +371,8 @@ static void markDecomposedOpsAsIllegal(MLIRContext *context,
target.addIllegalOp<Aten_LogSoftmaxOp>(); target.addIllegalOp<Aten_LogSoftmaxOp>();
target.addIllegalOp<AtenLogSoftmaxIntOp>(); target.addIllegalOp<AtenLogSoftmaxIntOp>();
target.addIllegalOp<AtenLogSigmoidOp>(); target.addIllegalOp<AtenLogSigmoidOp>();
target.addIllegalOp<AtenHardshrinkOp>();
target.addIllegalOp<AtenSoftshrinkOp>();
target.addIllegalOp<AtenEmptyLikeOp>(); target.addIllegalOp<AtenEmptyLikeOp>();
target.addIllegalOp<AtenOnesLikeOp>(); target.addIllegalOp<AtenOnesLikeOp>();
target.addIllegalOp<AtenZerosLikeOp>(); target.addIllegalOp<AtenZerosLikeOp>();

View File

@ -1438,6 +1438,8 @@ STABLEHLO_PASS_SET = {
"ElementwiseTruncIntModule_basic", "ElementwiseTruncIntModule_basic",
"ElementwiseTruncModule_basic", "ElementwiseTruncModule_basic",
"ElementwiseLogSigmoidModule_basic", "ElementwiseLogSigmoidModule_basic",
"ElementwiseHardshrinkStaticModule_basic",
"ElementwiseSoftshrinkStaticModule_basic",
} }
STABLEHLO_CRASHING_SET = { STABLEHLO_CRASHING_SET = {
@ -1667,6 +1669,10 @@ TOSA_PASS_SET = {
"ElementwiseSeluModule_basic", "ElementwiseSeluModule_basic",
"ElementwiseSigmoidModule_basic", "ElementwiseSigmoidModule_basic",
"ElementwiseSignModule_basic", "ElementwiseSignModule_basic",
"ElementwiseHardshrinkModule_basic",
"ElementwiseHardshrinkStaticModule_basic",
"ElementwiseSoftshrinkModule_basic",
"ElementwiseSoftshrinkStaticModule_basic",
"ElementwiseSqrtIntModule_basic", "ElementwiseSqrtIntModule_basic",
"ElementwiseSqrtModule_basic", "ElementwiseSqrtModule_basic",
"ElementwiseSubScalarFloatModule_basic", "ElementwiseSubScalarFloatModule_basic",

View File

@ -254,6 +254,12 @@ def atenlog〡shape(self: List[int]) -> List[int]:
def atenlog_sigmoid〡shape(self: List[int]) -> List[int]: def atenlog_sigmoid〡shape(self: List[int]) -> List[int]:
return upstream_shape_functions.unary(self) return upstream_shape_functions.unary(self)
def atenhardshrink〡shape(self: List[int], lambd: float = 0.5) -> List[int]:
return upstream_shape_functions.unary(self)
def atensoftshrink〡shape(self: List[int], lambd: float = 0.5) -> List[int]:
return upstream_shape_functions.unary(self)
def atenmish〡shape(self: List[int]) -> List[int]: def atenmish〡shape(self: List[int]) -> List[int]:
return upstream_shape_functions.unary(self) return upstream_shape_functions.unary(self)
@ -2098,6 +2104,18 @@ def atenlog_sigmoid〡dtype(self_rank_dtype: Tuple[int, int]) -> int:
assert not self_dtype == torch.bool assert not self_dtype == torch.bool
return self_dtype return self_dtype
@check_dtype_function(_check_tensors_with_the_same_dtype(num_of_tensors=1, lambd=0.5))
def atenhardshrink〡dtype(self_rank_dtype: Tuple[int, int], lambd: Union[int, float, complex] = 0.5) -> int:
self_rank, self_dtype = self_rank_dtype
if self_dtype == torch.bool:
return torch.int64
return self_dtype
@check_dtype_function(_check_tensors_with_the_same_dtype(num_of_tensors=1, lambd=0.5))
def atensoftshrink〡dtype(self_rank_dtype: Tuple[int, int], lambd: Union[int, float, complex] = 0.5) -> int:
self_rank, self_dtype = self_rank_dtype
return _get_dtype_of_floating_point_op(self_dtype)
@check_dtype_function(_check_tensors_with_the_same_dtype(num_of_tensors=1)) @check_dtype_function(_check_tensors_with_the_same_dtype(num_of_tensors=1))
def atenlogit〡dtype(self_rank_dtype: Tuple[int, int], eps: Optional[float] = None) -> int: def atenlogit〡dtype(self_rank_dtype: Tuple[int, int], eps: Optional[float] = None) -> int:
self_rank, self_dtype = self_rank_dtype self_rank, self_dtype = self_rank_dtype

View File

@ -480,6 +480,8 @@ def emit_ops(emitter_td: TextEmitter, registry: Registry):
emit("aten::isclose : (Tensor, Tensor, float, float, bool) -> (Tensor)") emit("aten::isclose : (Tensor, Tensor, float, float, bool) -> (Tensor)")
emit("aten::glu : (Tensor, int) -> (Tensor)") emit("aten::glu : (Tensor, int) -> (Tensor)")
emit("aten::log_sigmoid : (Tensor) -> (Tensor)") emit("aten::log_sigmoid : (Tensor) -> (Tensor)")
emit("aten::hardshrink : (Tensor, Scalar) -> (Tensor)")
emit("aten::softshrink : (Tensor, Scalar) -> (Tensor)")
# Ops with dynamic number of outputs # Ops with dynamic number of outputs
emit("aten::unbind_copy.int : (Tensor, int) -> (Tensor[])") emit("aten::unbind_copy.int : (Tensor, int) -> (Tensor[])")

View File

@ -2205,6 +2205,98 @@ def ElementwiseLogSigmoidModule_basic(module, tu: TestUtils):
# ============================================================================== # ==============================================================================
class ElementwiseSoftshrinkModule(torch.nn.Module):
def __init__(self):
super().__init__()
@export
@annotate_args(
[
None,
([-1, -1], torch.float32, True),
]
)
def forward(self, a):
return torch.ops.aten.softshrink(a)
@register_test_case(module_factory=lambda: ElementwiseSoftshrinkModule())
def ElementwiseSoftshrinkModule_basic(module, tu: TestUtils):
module.forward(tu.rand(3, 4))
# ==============================================================================
class ElementwiseSoftshrinkStaticModule(torch.nn.Module):
def __init__(self):
super().__init__()
@export
@annotate_args(
[
None,
([4, 5, 6], torch.float32, True),
]
)
def forward(self, a):
return torch.ops.aten.softshrink(a, 2.0)
@register_test_case(module_factory=lambda: ElementwiseSoftshrinkStaticModule())
def ElementwiseSoftshrinkStaticModule_basic(module, tu: TestUtils):
module.forward(tu.rand(4, 5, 6))
# ==============================================================================
class ElementwiseHardshrinkModule(torch.nn.Module):
def __init__(self):
super().__init__()
@export
@annotate_args(
[
None,
([-1, -1, -1], torch.float32, True),
]
)
def forward(self, a):
return torch.ops.aten.hardshrink(a, 1.0)
@register_test_case(module_factory=lambda: ElementwiseHardshrinkModule())
def ElementwiseHardshrinkModule_basic(module, tu: TestUtils):
module.forward(tu.rand(3, 4, 5))
# ==============================================================================
class ElementwiseHardshrinkStaticModule(torch.nn.Module):
def __init__(self):
super().__init__()
@export
@annotate_args(
[
None,
([4, 5, 6], torch.float32, True),
]
)
def forward(self, a):
return torch.ops.aten.hardshrink(a, 2.0)
@register_test_case(module_factory=lambda: ElementwiseHardshrinkStaticModule())
def ElementwiseHardshrinkStaticModule_basic(module, tu: TestUtils):
module.forward(tu.rand(4, 5, 6))
# ==============================================================================
class ElementwiseErfModule(torch.nn.Module): class ElementwiseErfModule(torch.nn.Module):
def __init__(self): def __init__(self):
super().__init__() super().__init__()