Skip to content

Commit 712b20f

Browse files
committed
add the code for aten.hinge_embedding_loss op
1 parent acf7fdd commit 712b20f

File tree

8 files changed

+247
-0
lines changed

8 files changed

+247
-0
lines changed

include/torch-mlir/Dialect/Torch/IR/GeneratedTorchOps.td

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9478,6 +9478,32 @@ def Torch_AtenNllLossBackwardOp : Torch_Op<"aten.nll_loss_backward", [
94789478
}];
94799479
}
94809480

9481+
def Torch_AtenHingeEmbeddingLossOp : Torch_Op<"aten.hinge_embedding_loss", [
9482+
AllowsTypeRefinement,
9483+
HasValueSemantics,
9484+
ReadOnly
9485+
]> {
9486+
let summary = "Generated op for `aten::hinge_embedding_loss : (Tensor, Tensor, float, int) -> (Tensor)`";
9487+
let arguments = (ins
9488+
AnyTorchTensorType:$self,
9489+
AnyTorchTensorType:$target,
9490+
Torch_FloatType:$margin,
9491+
Torch_IntType:$reduction
9492+
);
9493+
let results = (outs
9494+
AnyTorchOptionalTensorType:$result
9495+
);
9496+
let hasCustomAssemblyFormat = 1;
9497+
let extraClassDefinition = [{
9498+
ParseResult AtenHingeEmbeddingLossOp::parse(OpAsmParser &parser, OperationState &result) {
9499+
return parseDefaultTorchOp(parser, result, 4, 1);
9500+
}
9501+
void AtenHingeEmbeddingLossOp::print(OpAsmPrinter &printer) {
9502+
printDefaultTorchOp(printer, *this, 4, 1);
9503+
}
9504+
}];
9505+
}
9506+
94819507
def Torch_AtenBincountOp : Torch_Op<"aten.bincount", [
94829508
AllowsTypeRefinement,
94839509
HasValueSemantics,

lib/Dialect/Torch/Transforms/AbstractInterpLibrary.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10700,6 +10700,20 @@ StringRef mlir::torch::Torch::getAbstractInterpLibrary() {
1070010700
" %0 = call @__torch__.torch.jit._shape_functions.unary(%arg1) : (!torch.list<int>) -> !torch.list<int>\n"
1070110701
" return %0 : !torch.list<int>\n"
1070210702
" }\n"
10703+
" func.func @\"__torch_mlir_shape_fn.aten.hinge_embedding_loss\"(%arg0: !torch.list<int>, %arg1: !torch.list<int>, %arg2: !torch.float, %arg3: !torch.int) -> !torch.list<int> {\n"
10704+
" %int1 = torch.constant.int 1\n"
10705+
" %int2 = torch.constant.int 2\n"
10706+
" %0 = torch.prim.ListConstruct %int1, %int2 : (!torch.int, !torch.int) -> !torch.list<int>\n"
10707+
" %1 = torch.aten.__contains__.int_list %0, %arg3 : !torch.list<int>, !torch.int -> !torch.bool\n"
10708+
" %2 = torch.prim.If %1 -> (!torch.list<int>) {\n"
10709+
" %3 = torch.prim.ListConstruct : () -> !torch.list<int>\n"
10710+
" torch.prim.If.yield %3 : !torch.list<int>\n"
10711+
" } else {\n"
10712+
" %3 = func.call @__torch__.torch.jit._shape_functions.unary(%arg0) : (!torch.list<int>) -> !torch.list<int>\n"
10713+
" torch.prim.If.yield %3 : !torch.list<int>\n"
10714+
" }\n"
10715+
" return %2 : !torch.list<int>\n"
10716+
" }\n"
1070310717
" func.func @\"__torch_mlir_shape_fn.aten.mse_loss\"(%arg0: !torch.list<int>, %arg1: !torch.list<int>, %arg2: !torch.int) -> !torch.list<int> {\n"
1070410718
" %int0 = torch.constant.int 0\n"
1070510719
" %0 = torch.aten.eq.int %arg2, %int0 : !torch.int, !torch.int -> !torch.bool\n"
@@ -13387,6 +13401,14 @@ StringRef mlir::torch::Torch::getAbstractInterpLibrary() {
1338713401
" }\n"
1338813402
" return %6 : !torch.int\n"
1338913403
" }\n"
13404+
" func.func @\"__torch_mlir_dtype_fn.aten.hinge_embedding_loss\"(%arg0: !torch.tuple<int, int>, %arg1: !torch.tuple<int, int>, %arg2: !torch.float, %arg3: !torch.int) -> !torch.int {\n"
13405+
" %0:2 = torch.prim.TupleUnpack %arg0 : !torch.tuple<int, int> -> !torch.int, !torch.int\n"
13406+
" %1:2 = torch.prim.TupleUnpack %arg1 : !torch.tuple<int, int> -> !torch.int, !torch.int\n"
13407+
" %2 = torch.prim.ListConstruct %0#0, %1#0 : (!torch.int, !torch.int) -> !torch.list<optional<int>>\n"
13408+
" %3 = torch.prim.ListConstruct %0#1, %1#1 : (!torch.int, !torch.int) -> !torch.list<int>\n"
13409+
" %4 = call @__torch__.torch_mlir.jit_ir_importer.build_tools.library_generator.promote_dtypes(%2, %3) : (!torch.list<optional<int>>, !torch.list<int>) -> !torch.int\n"
13410+
" return %4 : !torch.int\n"
13411+
" }\n"
1339013412
" func.func @\"__torch_mlir_dtype_fn.aten.max_pool2d_with_indices_backward\"(%arg0: !torch.tuple<int, int>, %arg1: !torch.tuple<int, int>, %arg2: !torch.list<int>, %arg3: !torch.list<int>, %arg4: !torch.list<int>, %arg5: !torch.list<int>, %arg6: !torch.bool, %arg7: !torch.tuple<int, int>) -> !torch.int {\n"
1339113413
" %none = torch.constant.none\n"
1339213414
" %str = torch.constant.str \"AssertionError: \"\n"

lib/Dialect/Torch/Transforms/DecomposeComplexOps.cpp

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10553,6 +10553,89 @@ class DecomposeAtenNllLossForwardOp
1055310553
};
1055410554
} // namespace
1055510555

10556+
namespace {
10557+
// Decompostion of aten.hinge_embedding_loss op
10558+
// Ref:
10559+
// https://github.com/pytorch/pytorch/blob/main/aten/src/ATen/native/Loss.cpp#L182
10560+
// The Hinge Embedding Loss:
10561+
// | input, if target == 1
10562+
// loss(x) = |
10563+
// | max(0, margin - input), if target == -1
10564+
class DecomposeHingeEmbeddingLoss
10565+
: public OpRewritePattern<AtenHingeEmbeddingLossOp> {
10566+
using OpRewritePattern<AtenHingeEmbeddingLossOp>::OpRewritePattern;
10567+
LogicalResult matchAndRewrite(AtenHingeEmbeddingLossOp op,
10568+
PatternRewriter &rewriter) const override {
10569+
Location loc = op.getLoc();
10570+
auto input = op.getSelf();
10571+
auto target = op.getTarget();
10572+
10573+
auto inputTy = dyn_cast<ValueTensorType>(input.getType());
10574+
if (!inputTy.hasDtype() || !inputTy.hasSizes())
10575+
return rewriter.notifyMatchFailure(op, "input must have dtype and size");
10576+
10577+
auto targetTy = dyn_cast<ValueTensorType>(target.getType());
10578+
if (!targetTy.hasDtype() || !targetTy.hasSizes())
10579+
return rewriter.notifyMatchFailure(op, "target must have dtype and size");
10580+
auto resultTy = dyn_cast<ValueTensorType>(op.getType());
10581+
Value minusOne = getConstantWithGivenDtypeAndValue(rewriter, loc, -1,
10582+
targetTy.getDtype());
10583+
Value one = getConstantWithGivenDtypeAndValue(rewriter, loc, 1,
10584+
targetTy.getDtype());
10585+
Value zero = getConstantWithGivenDtypeAndValue(rewriter, loc, 0,
10586+
targetTy.getDtype());
10587+
Value alpha =
10588+
rewriter.create<ConstantIntOp>(loc, rewriter.getI64IntegerAttr(1));
10589+
auto boolType = targetTy.getWithSizesAndDtype(targetTy.getSizes(),
10590+
rewriter.getI1Type());
10591+
// input - margin
10592+
auto inputMinusMargin = rewriter.create<AtenSubScalarOp>(
10593+
loc, inputTy, input, op.getMargin(), alpha);
10594+
// multiply by -1 to get margin - input
10595+
auto marginDiff = rewriter.create<AtenMulScalarOp>(
10596+
loc, inputTy, inputMinusMargin, minusOne);
10597+
// max(0, margin - input) => clamping the minimum value of margin - input at
10598+
// 0
10599+
auto marginClamp =
10600+
rewriter.create<AtenClampMinOp>(loc, inputTy, marginDiff, zero);
10601+
// Compute mask: target != 1
10602+
auto targetNotOne =
10603+
rewriter.create<AtenNeScalarOp>(loc, boolType, target, one);
10604+
// If target != 1 use marginClamp otherwise 0.
10605+
auto outputMargin = rewriter.create<AtenWhereScalarOtherOp>(
10606+
loc, inputTy, targetNotOne, marginClamp, zero);
10607+
// Compute mask: target != -1
10608+
auto targetNotMinusOne =
10609+
rewriter.create<AtenNeScalarOp>(loc, boolType, target, minusOne);
10610+
// If target != -1 use the original input. Otherwise 0.
10611+
auto outputSelf = rewriter.create<AtenWhereScalarOtherOp>(
10612+
loc, inputTy, targetNotMinusOne, input, zero);
10613+
// Add : outputMargin + outputSelf
10614+
auto output = rewriter.create<AtenAddTensorOp>(loc, inputTy, outputMargin,
10615+
outputSelf, /*alpha=*/alpha);
10616+
int64_t reduction;
10617+
if (!matchPattern(op.getReduction(), m_TorchConstantInt(&reduction))) {
10618+
return rewriter.notifyMatchFailure(op,
10619+
"reduction should be a constant int!");
10620+
}
10621+
Value loss;
10622+
Value none = rewriter.create<ConstantNoneOp>(loc);
10623+
// reduction: mean
10624+
if (reduction == 1) {
10625+
loss = rewriter.create<AtenMeanOp>(loc, resultTy, output, none);
10626+
} else if (reduction == 2) {
10627+
// reduction: sum
10628+
loss = rewriter.create<AtenSumOp>(loc, resultTy, output, none);
10629+
} else {
10630+
// reduction: none
10631+
loss = output;
10632+
}
10633+
rewriter.replaceOp(op, loss);
10634+
return success();
10635+
}
10636+
};
10637+
} // namespace
10638+
1055610639
namespace {
1055710640
class DecomposeAtenBinaryCrossEntropyWithLogitsOp
1055810641
: public OpRewritePattern<AtenBinaryCrossEntropyWithLogitsOp> {
@@ -12467,6 +12550,7 @@ class DecomposeComplexOpsPass
1246712550
addPatternIfTargetOpIsIllegal<DecomposeAtenOneHotOp>(patterns);
1246812551
addPatternIfTargetOpIsIllegal<DecomposeAtenCrossEntropyLossOp>(patterns);
1246912552
addPatternIfTargetOpIsIllegal<DecomposeAtenNllLossForwardOp>(patterns);
12553+
addPatternIfTargetOpIsIllegal<DecomposeHingeEmbeddingLoss>(patterns);
1247012554
addPatternIfTargetOpIsIllegal<DecomposeAtenBinaryCrossEntropyWithLogitsOp>(
1247112555
patterns);
1247212556
addPatternIfTargetOpIsIllegal<DecomposeAtenVarMeanDimOp>(patterns);

lib/Dialect/Torch/Transforms/LowerToBackendContract.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -538,6 +538,7 @@ static void markDecomposedOpsAsIllegal(MLIRContext *context,
538538
target.addIllegalOp<AtenLerpTensorOp>();
539539
target.addIllegalOp<AtenMseLossOp>();
540540
target.addIllegalOp<AtenL1LossOp>();
541+
target.addIllegalOp<AtenHingeEmbeddingLossOp>();
541542
target.addIllegalOp<AtenRandintLowOp>();
542543
target.addIllegalOp<AtenRandintOp>();
543544
target.addIllegalOp<AtenVarMeanCorrectionOp>();

projects/pt1/e2e_testing/xfail_sets.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1795,6 +1795,9 @@
17951795
"L1LossMeanReductionModule_basic",
17961796
"L1LossNoReductionModule_basic",
17971797
"L1LossSumReductionModule_basic",
1798+
"HingeEmbeddingLossReductionMeanModule_basic",
1799+
"HingeEmbeddingLossReductionSumModule_basic",
1800+
"HingeEmbeddingLossWithoutReductionModule_basic",
17981801
"PixelShuffleModuleStaticRank3Int64_basic",
17991802
"PixelShuffleModuleStaticRank4Float32_basic",
18001803
"RandIntLowModule_basic",
@@ -2968,6 +2971,10 @@
29682971
"GtFloatIntModule_basic",
29692972
"GtIntModule_basic",
29702973
"HardtanhBackward_basic",
2974+
"HingeEmbeddingLossBasicModule_basic",
2975+
"HingeEmbeddingLossReductionMeanModule_basic",
2976+
"HingeEmbeddingLossReductionSumModule_basic",
2977+
"HingeEmbeddingLossWithoutReductionModule_basic",
29712978
"HstackBasicComplexModule_basic",
29722979
"HstackBasicFloatModule_basic",
29732980
"HstackBasicIntFloatModule_basic",
@@ -3978,6 +3985,10 @@
39783985
"NllLossStaticModule_mean_basic",
39793986
"NllLossStaticModule_sum_basic",
39803987
"NllLossStaticModule_weight_basic",
3988+
"HingeEmbeddingLossBasicModule_basic",
3989+
"HingeEmbeddingLossReductionMeanModule_basic",
3990+
"HingeEmbeddingLossReductionSumModule_basic",
3991+
"HingeEmbeddingLossWithoutReductionModule_basic",
39813992
"Exp2StaticModule_basic",
39823993
"ElementwiseRreluWithNoiseEvalModule_basic",
39833994
"ElementwiseRreluWithNoiseEvalStaticModule_basic",

projects/pt1/python/torch_mlir/jit_ir_importer/build_tools/abstract_interp_lib_gen.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2186,6 +2186,12 @@ def aten〇nll_loss_forward〡shape(self: List[int], target: List[int], weight:
21862186
def aten〇nll_loss_backward〡shape(grad_output: List[int], self: List[int], target: List[int], weight: Optional[List[int]], reduction: int, ignore_index: int, total_weight: List[int]) -> List[int]:
21872187
return upstream_shape_functions.unary(self)
21882188

2189+
def aten〇hinge_embedding_loss〡shape(self: List[int], target: List[int], margin: float = 1., reduction: int = 1) -> List[int]:
2190+
if reduction in [1,2]:
2191+
return []
2192+
else:
2193+
return upstream_shape_functions.unary(self)
2194+
21892195
# TODO: upstream this
21902196
def aten〇mse_loss〡shape(self: List[int], target: List[int], reduction: int = 1) -> List[int]:
21912197
if reduction == 0:
@@ -3972,6 +3978,13 @@ def aten〇nll_loss_backward〡dtype(grad_output_rank_dtype: Tuple[int, int], se
39723978
return torch.int64
39733979
return result
39743980

3981+
def aten〇hinge_embedding_loss〡dtype(self_rank_dtype: Tuple[int, int], target_rank_dtype: Tuple[int, int], margin: float = 1., reduction: int = 1) -> int:
3982+
self_rank, self_dtype = self_rank_dtype
3983+
target_rank, target_dtype = target_rank_dtype
3984+
ranks: List[Optional[int]] = [self_rank, target_rank]
3985+
dtypes = [self_dtype, target_dtype]
3986+
return promote_dtypes(ranks, dtypes)
3987+
39753988
@check_dtype_function(_check_tensors_with_the_same_dtype(
39763989
None, [(2, 4, 7, 6), (2, 4, 6, 5)], None, None,
39773990
[2, 2], [1, 1], [1, 1], [1, 1], False, TensorOfShape(2, 4, 7, 6, dtype=torch.int64)) +

projects/pt1/python/torch_mlir/jit_ir_importer/build_tools/torch_ods_gen.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -761,6 +761,7 @@ def emit_with_mutating_variants(key, **kwargs):
761761
emit(
762762
"aten::nll_loss_backward : (Tensor, Tensor, Tensor, Tensor?, int, int, Tensor) -> (Tensor)"
763763
)
764+
emit("aten::hinge_embedding_loss : (Tensor, Tensor, float, int) -> (Tensor)")
764765
emit("aten::bincount : (Tensor, Tensor?, int) -> (Tensor)")
765766
emit("aten::linalg_vector_norm : (Tensor, Scalar, int[]?, bool, int?) -> (Tensor)")
766767
emit("aten::linalg_norm : (Tensor, Scalar?, int[]?, bool, int?) -> (Tensor)")

projects/pt1/python/torch_mlir_e2e_test/test_suite/reduction.py

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2455,6 +2455,95 @@ def BinaryCrossEntropyWithLogitsStaticModule_basic(module, tu: TestUtils):
24552455
# ==============================================================================
24562456

24572457

2458+
class HingeEmbeddingLossBasicModule(torch.nn.Module):
2459+
def __init__(self):
2460+
super().__init__()
2461+
2462+
@export
2463+
@annotate_args(
2464+
[
2465+
None,
2466+
([-1, -1, -1], torch.float32, True),
2467+
([-1, -1, -1], torch.float32, True),
2468+
]
2469+
)
2470+
def forward(self, input, target):
2471+
return torch.ops.aten.hinge_embedding_loss(
2472+
input, target, margin=1.5, reduction=1
2473+
)
2474+
2475+
2476+
@register_test_case(module_factory=lambda: HingeEmbeddingLossBasicModule())
2477+
def HingeEmbeddingLossBasicModule_basic(module, tu: TestUtils):
2478+
module.forward(tu.rand(1, 2, 3), tu.rand(1, 2, 3))
2479+
2480+
2481+
class HingeEmbeddingLossReductionMeanModule(torch.nn.Module):
2482+
def __init__(self):
2483+
super().__init__()
2484+
2485+
@export
2486+
@annotate_args(
2487+
[
2488+
None,
2489+
([8, 1], torch.float32, True),
2490+
([1, 1], torch.float32, True),
2491+
]
2492+
)
2493+
def forward(self, input, target):
2494+
return torch.ops.aten.hinge_embedding_loss(input, target, reduction=1)
2495+
2496+
2497+
@register_test_case(module_factory=lambda: HingeEmbeddingLossReductionMeanModule())
2498+
def HingeEmbeddingLossReductionMeanModule_basic(module, tu: TestUtils):
2499+
module.forward(tu.rand(8, 1), tu.rand(1, 1))
2500+
2501+
2502+
class HingeEmbeddingLossReductionSumModule(torch.nn.Module):
2503+
def __init__(self):
2504+
super().__init__()
2505+
2506+
@export
2507+
@annotate_args(
2508+
[
2509+
None,
2510+
([2, 5], torch.float32, True),
2511+
([1, 1], torch.float32, True),
2512+
]
2513+
)
2514+
def forward(self, input, target):
2515+
return torch.ops.aten.hinge_embedding_loss(input, target, reduction=2)
2516+
2517+
2518+
@register_test_case(module_factory=lambda: HingeEmbeddingLossReductionSumModule())
2519+
def HingeEmbeddingLossReductionSumModule_basic(module, tu: TestUtils):
2520+
module.forward(tu.rand(2, 5), tu.rand(1, 1))
2521+
2522+
2523+
class HingeEmbeddingLossWithoutReductionModule(torch.nn.Module):
2524+
def __init__(self):
2525+
super().__init__()
2526+
2527+
@export
2528+
@annotate_args(
2529+
[
2530+
None,
2531+
([8, 5], torch.float32, True),
2532+
([1], torch.float32, True),
2533+
]
2534+
)
2535+
def forward(self, input, target):
2536+
return torch.ops.aten.hinge_embedding_loss(input, target, margin=1.0)
2537+
2538+
2539+
@register_test_case(module_factory=lambda: HingeEmbeddingLossWithoutReductionModule())
2540+
def HingeEmbeddingLossWithoutReductionModule_basic(module, tu: TestUtils):
2541+
module.forward(tu.rand(8, 5), tu.rand(1))
2542+
2543+
2544+
# ==============================================================================
2545+
2546+
24582547
class TraceModule(torch.nn.Module):
24592548
def __init__(self) -> None:
24602549
super().__init__()

0 commit comments

Comments
 (0)