Skip to content

Commit

Permalink
[torch] emit aten.Softshrink and aten.Hardshrink (llvm#3248)
Browse files Browse the repository at this point in the history
as title
  • Loading branch information
Xinyu Yang authored May 8, 2024
1 parent c77f3b5 commit abef114
Show file tree
Hide file tree
Showing 8 changed files with 309 additions and 0 deletions.
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 @@ -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", [
AllowsTypeRefinement,
HasValueSemantics,
Expand Down
25 changes: 25 additions & 0 deletions lib/Dialect/Torch/Transforms/AbstractInterpLibrary.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
" return %0 : !torch.list<int>\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"
" %0 = call @__torch__.torch.jit._shape_functions.unary(%arg0) : (!torch.list<int>) -> !torch.list<int>\n"
" return %0 : !torch.list<int>\n"
Expand Down Expand Up @@ -9798,6 +9806,23 @@ StringRef mlir::torch::Torch::getAbstractInterpLibrary() {
" }\n"
" return %0#1 : !torch.int\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"
" %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"
Expand Down
116 changes: 116 additions & 0 deletions lib/Dialect/Torch/Transforms/DecomposeComplexOps.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1913,6 +1913,120 @@ class DecomposeAtenLogSigmoidOp : public OpRewritePattern<AtenLogSigmoidOp> {
};
} // 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.
namespace {
class DecomposeAtenMatmulOp : public OpRewritePattern<AtenMatmulOp> {
Expand Down Expand Up @@ -7664,6 +7778,8 @@ class DecomposeComplexOpsPass
addPatternIfTargetOpIsIllegal<DecomposeAten_LogSoftmaxOp>(patterns);
addPatternIfTargetOpIsIllegal<DecomposeAtenLogSoftmaxIntOp>(patterns);
addPatternIfTargetOpIsIllegal<DecomposeAtenLogSigmoidOp>(patterns);
addPatternIfTargetOpIsIllegal<DecomposeAtenHardshrinkOp>(patterns);
addPatternIfTargetOpIsIllegal<DecomposeAtenSoftshrinkOp>(patterns);
addPatternIfTargetOpIsIllegal<DecomposeAtenEmptyLikeOp>(patterns);
addPatternIfTargetOpIsIllegal<
DecomposeConstantTensorAllocLikeOp<AtenOnesLikeOp, 1>>(patterns);
Expand Down
2 changes: 2 additions & 0 deletions lib/Dialect/Torch/Transforms/LowerToBackendContract.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,8 @@ static void markDecomposedOpsAsIllegal(MLIRContext *context,
target.addIllegalOp<Aten_LogSoftmaxOp>();
target.addIllegalOp<AtenLogSoftmaxIntOp>();
target.addIllegalOp<AtenLogSigmoidOp>();
target.addIllegalOp<AtenHardshrinkOp>();
target.addIllegalOp<AtenSoftshrinkOp>();
target.addIllegalOp<AtenEmptyLikeOp>();
target.addIllegalOp<AtenOnesLikeOp>();
target.addIllegalOp<AtenZerosLikeOp>();
Expand Down
6 changes: 6 additions & 0 deletions projects/pt1/e2e_testing/xfail_sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -1438,6 +1438,8 @@
"ElementwiseTruncIntModule_basic",
"ElementwiseTruncModule_basic",
"ElementwiseLogSigmoidModule_basic",
"ElementwiseHardshrinkStaticModule_basic",
"ElementwiseSoftshrinkStaticModule_basic",
}

STABLEHLO_CRASHING_SET = {
Expand Down Expand Up @@ -1667,6 +1669,10 @@
"ElementwiseSeluModule_basic",
"ElementwiseSigmoidModule_basic",
"ElementwiseSignModule_basic",
"ElementwiseHardshrinkModule_basic",
"ElementwiseHardshrinkStaticModule_basic",
"ElementwiseSoftshrinkModule_basic",
"ElementwiseSoftshrinkStaticModule_basic",
"ElementwiseSqrtIntModule_basic",
"ElementwiseSqrtModule_basic",
"ElementwiseSubScalarFloatModule_basic",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,12 @@ def aten〇log〡shape(self: List[int]) -> List[int]:
def aten〇log_sigmoid〡shape(self: List[int]) -> List[int]:
return upstream_shape_functions.unary(self)

def aten〇hardshrink〡shape(self: List[int], lambd: float = 0.5) -> List[int]:
return upstream_shape_functions.unary(self)

def aten〇softshrink〡shape(self: List[int], lambd: float = 0.5) -> List[int]:
return upstream_shape_functions.unary(self)

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

Expand Down Expand Up @@ -2098,6 +2104,18 @@ def aten〇log_sigmoid〡dtype(self_rank_dtype: Tuple[int, int]) -> int:
assert not self_dtype == torch.bool
return self_dtype

@check_dtype_function(_check_tensors_with_the_same_dtype(num_of_tensors=1, lambd=0.5))
def aten〇hardshrink〡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 aten〇softshrink〡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))
def aten〇logit〡dtype(self_rank_dtype: Tuple[int, int], eps: Optional[float] = None) -> int:
self_rank, self_dtype = self_rank_dtype
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,8 @@ def emit_with_mutating_variants(key, **kwargs):
emit("aten::isclose : (Tensor, Tensor, float, float, bool) -> (Tensor)")
emit("aten::glu : (Tensor, int) -> (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
emit("aten::unbind_copy.int : (Tensor, int) -> (Tensor[])")
Expand Down
92 changes: 92 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 @@ -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):
def __init__(self):
super().__init__()
Expand Down

0 comments on commit abef114

Please sign in to comment.