# AOT ID: ['0_inference']
from ctypes import c_void_p, c_long, c_int
import torch
import math
import random
import os
import tempfile
from math import inf, nan
from torch._inductor.hooks import run_intermediate_hooks
from torch._inductor.utils import maybe_profile
from torch._inductor.codegen.memory_planning import _align as align
from torch import device, empty_strided
from torch._inductor.async_compile import AsyncCompile
from torch._inductor.select_algorithm import extern_kernels
from torch._inductor.codegen.multi_kernel import MultiKernelCall
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid, split_scan_grid, grid_combo_kernels, start_graph, end_graph
from torch._C import _cuda_getCurrentRawStream as get_raw_stream

aten = torch.ops.aten
inductor_ops = torch.ops.inductor
_quantized = torch.ops._quantized
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cpu = torch._C._dynamo.guards._empty_strided_cpu
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
empty_strided_xpu = torch._C._dynamo.guards._empty_strided_xpu
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
alloc_from_pool = torch.ops.inductor._alloc_from_pool
async_compile = AsyncCompile()


# kernel path: runs/run_shard_8/inductor_cache/x3/cx3gpf4n2y7fkf422onmjcy6b22ij4znd7tgyoi6rxib7scpat3y.py
# Topologically Sorted Source Nodes: [sub_2], Original ATen: [aten.sub]
# Source node to ATen node mapping:
#   sub_2 => sub_2
# Graph fragment:
#   %sub_2 : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%unsqueeze_2, %unsqueeze_3), kwargs = {})
triton_poi_fused_sub_0 = async_compile.triton('triton_poi_fused_sub_0', '''
import triton
import triton.language as tl
from triton.compiler.compiler import AttrsDescriptor

from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, instance_descriptor, DeviceProperties

@triton_heuristics.pointwise(
    size_hints=[64], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_sub_0', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 5, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False},
    min_elem_per_thread=0
)
@triton.jit
def triton_poi_fused_sub_0(in_ptr0, out_ptr0, xnumel, XBLOCK : tl.constexpr):
    xnumel = 64
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = (xindex // 16)
    x4 = (xindex // 4)
    x1 = (xindex // 4) % 4
    x0 = xindex % 4
    x5 = xindex
    tmp0 = tl.load(in_ptr0 + (5*x2), xmask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr0 + (x4), xmask, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr0 + (5*x1), xmask, eviction_policy='evict_last')
    tmp19 = tl.load(in_ptr0 + (x0 + (4*x2)), xmask, eviction_policy='evict_last')
    tmp22 = tl.load(in_ptr0 + (5*x0), xmask, eviction_policy='evict_last')
    tmp2 = 2.0
    tmp3 = tmp1 * tmp2
    tmp4 = tmp0 - tmp3
    tmp6 = tmp4 + tmp5
    tmp7 = tl.full([1], 0, tl.int32)
    tmp8 = triton_helpers.maximum(tmp7, tmp6)
    tmp9 = 0.0
    tmp10 = tmp8 == tmp9
    tmp11 = tmp10.to(tl.float32)
    tmp12 = 1e-16
    tmp13 = tmp11 * tmp12
    tmp14 = tmp8 + tmp13
    tmp15 = libdevice.sqrt(tmp14)
    tmp16 = 1.0
    tmp17 = tmp16 - tmp11
    tmp18 = tmp15 * tmp17
    tmp20 = tmp19 * tmp2
    tmp21 = tmp0 - tmp20
    tmp23 = tmp21 + tmp22
    tmp24 = triton_helpers.maximum(tmp7, tmp23)
    tmp25 = tmp24 == tmp9
    tmp26 = tmp25.to(tl.float32)
    tmp27 = tmp26 * tmp12
    tmp28 = tmp24 + tmp27
    tmp29 = libdevice.sqrt(tmp28)
    tmp30 = tmp16 - tmp26
    tmp31 = tmp29 * tmp30
    tmp32 = tmp18 - tmp31
    tl.store(out_ptr0 + (x5), tmp32, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_8/inductor_cache/kn/cknxwlymcfxaj22jim2nvfsq5i5wmsnbruoogncdylbu5mpppkzk.py
# Topologically Sorted Source Nodes: [loss, invert_1, valid_labels, and_, distinct_indices, mask_1, mask_2, triplet_loss, triplet_loss_1, sum_2, gt, hard_triplets, num_hard_triplets, add_3, triplet_loss_2], Original ATen: [aten.add, aten.bitwise_not, aten.bitwise_and, aten._to_copy, aten.mul, aten.relu, aten.sum, aten.gt, aten.div]
# Source node to ATen node mapping:
#   add_3 => add_3
#   and_ => bitwise_and
#   distinct_indices => bitwise_and_1
#   gt => gt
#   hard_triplets => convert_element_type_2
#   invert_1 => bitwise_not_1
#   loss => add_2
#   mask_1 => bitwise_and_3
#   mask_2 => convert_element_type_1
#   num_hard_triplets => sum_1
#   sum_2 => sum_2
#   triplet_loss => mul_3
#   triplet_loss_1 => relu_1
#   triplet_loss_2 => div
#   valid_labels => bitwise_and_2
# Graph fragment:
#   %add_2 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%sub_2, 0.1), kwargs = {})
#   %bitwise_not_1 : [num_users=1] = call_function[target=torch.ops.aten.bitwise_not.default](args = (%unsqueeze_11,), kwargs = {})
#   %bitwise_and_2 : [num_users=1] = call_function[target=torch.ops.aten.bitwise_and.Tensor](args = (%bitwise_not_1, %unsqueeze_10), kwargs = {})
#   %bitwise_and : [num_users=1] = call_function[target=torch.ops.aten.bitwise_and.Tensor](args = (%unsqueeze_5, %unsqueeze_6), kwargs = {})
#   %bitwise_and_1 : [num_users=1] = call_function[target=torch.ops.aten.bitwise_and.Tensor](args = (%bitwise_and, %unsqueeze_7), kwargs = {})
#   %bitwise_and_3 : [num_users=1] = call_function[target=torch.ops.aten.bitwise_and.Tensor](args = (%bitwise_and_2, %bitwise_and_1), kwargs = {})
#   %convert_element_type_1 : [num_users=1] = call_function[target=torch.ops.prims.convert_element_type.default](args = (%bitwise_and_3, torch.float32), kwargs = {})
#   %mul_3 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%add_2, %convert_element_type_1), kwargs = {})
#   %relu_1 : [num_users=2] = call_function[target=torch.ops.aten.relu.default](args = (%mul_3,), kwargs = {})
#   %sum_2 : [num_users=1] = call_function[target=torch.ops.aten.sum.default](args = (%relu_1,), kwargs = {})
#   %gt : [num_users=1] = call_function[target=torch.ops.aten.gt.Scalar](args = (%relu_1, 1e-16), kwargs = {})
#   %convert_element_type_2 : [num_users=1] = call_function[target=torch.ops.prims.convert_element_type.default](args = (%gt, torch.float32), kwargs = {})
#   %sum_1 : [num_users=1] = call_function[target=torch.ops.aten.sum.default](args = (%convert_element_type_2,), kwargs = {})
#   %add_3 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%sum_1, 1e-16), kwargs = {})
#   %div : [num_users=1] = call_function[target=torch.ops.aten.div.Tensor](args = (%sum_2, %add_3), kwargs = {})
triton_red_fused__to_copy_add_bitwise_and_bitwise_not_div_gt_mul_relu_sum_1 = async_compile.triton('triton_red_fused__to_copy_add_bitwise_and_bitwise_not_div_gt_mul_relu_sum_1', '''
import triton
import triton.language as tl
from triton.compiler.compiler import AttrsDescriptor

from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, instance_descriptor, DeviceProperties

@triton_heuristics.reduction(
    size_hints=[1, 4096],
    reduction_hint=ReductionHint.INNER,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: 'i32', 4: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {3: 1}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 4), equal_to_1=(3,))]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_red_fused__to_copy_add_bitwise_and_bitwise_not_div_gt_mul_relu_sum_1', 'mutated_arg_names': ['in_out_ptr0'], 'no_x_dim': False, 'num_load': 4, 'num_reduction': 2, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False}
)
@triton.jit
def triton_red_fused__to_copy_add_bitwise_and_bitwise_not_div_gt_mul_relu_sum_1(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK : tl.constexpr, RBLOCK : tl.constexpr):
    xnumel = 1
    rnumel = 4096
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = tl.full([XBLOCK, RBLOCK], True, tl.int1)
    rbase = tl.arange(0, RBLOCK)[None, :]
    _tmp27 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
    _tmp33 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
    for roffset in range(0, rnumel, RBLOCK):
        rindex = roffset + rbase
        rmask = rindex < rnumel
        r7 = rindex % 64
        r9 = rindex % 256
        r5 = (rindex // 1024)
        r4 = (rindex // 256) % 4
        r2 = (rindex // 16) % 4
        r1 = (rindex // 4) % 4
        r0 = rindex % 4
        tmp0 = tl.load(in_ptr0 + (r7), rmask, eviction_policy='evict_last', other=0.0)
        tmp3 = tl.load(in_ptr1 + (r9), rmask, eviction_policy='evict_last', other=0.0)
        tmp4 = tl.load(in_ptr1 + (r7 + (64*r5)), rmask, eviction_policy='evict_last', other=0.0)
        tmp7 = tl.load(in_ptr1 + (r7 + (64*r4)), rmask, eviction_policy='evict_last', other=0.0)
        tmp1 = 0.1
        tmp2 = tmp0 + tmp1
        tmp5 = tmp3 == tmp4
        tmp6 = tmp5 == 0
        tmp8 = tmp7 == tmp4
        tmp9 = tmp6 & tmp8
        tmp10 = r2
        tmp11 = r1
        tmp12 = tmp10 == tmp11
        tmp13 = tmp12 == 0
        tmp14 = r0
        tmp15 = tmp10 == tmp14
        tmp16 = tmp15 == 0
        tmp17 = tmp13 & tmp16
        tmp18 = tmp11 == tmp14
        tmp19 = tmp18 == 0
        tmp20 = tmp17 & tmp19
        tmp21 = tmp9 & tmp20
        tmp22 = tmp21.to(tl.float32)
        tmp23 = tmp2 * tmp22
        tmp24 = tl.full([1, 1], 0, tl.int32)
        tmp25 = triton_helpers.maximum(tmp24, tmp23)
        tmp26 = tl.broadcast_to(tmp25, [XBLOCK, RBLOCK])
        tmp28 = _tmp27 + tmp26
        _tmp27 = tl.where(rmask, tmp28, _tmp27)
        tmp29 = 1e-16
        tmp30 = tmp25 > tmp29
        tmp31 = tmp30.to(tl.float32)
        tmp32 = tl.broadcast_to(tmp31, [XBLOCK, RBLOCK])
        tmp34 = _tmp33 + tmp32
        _tmp33 = tl.where(rmask, tmp34, _tmp33)
    tmp27 = tl.sum(_tmp27, 1)[:, None]
    tmp33 = tl.sum(_tmp33, 1)[:, None]
    tmp35 = 1e-16
    tmp36 = tmp33 + tmp35
    tmp37 = tmp27 / tmp36
    tl.debug_barrier()
    tl.store(in_out_ptr0 + (tl.full([XBLOCK, 1], 0, tl.int32)), tmp37, None)
''', device_str='cuda')


async_compile.wait(globals())
del async_compile

def call(args):
    arg0_1, arg1_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4), (4, 1))
    assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [cor_mat], Original ATen: [aten.mm]
        extern_kernels.mm(arg0_1, reinterpret_tensor(arg0_1, (4, 4), (1, 4), 0), out=buf0)
        del arg0_1
        buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [sub_2], Original ATen: [aten.sub]
        stream0 = get_raw_stream(0)
        triton_poi_fused_sub_0.run(buf0, buf1, 64, grid=grid(64), stream=stream0)
        del buf0
        buf2 = empty_strided_cuda((), (), torch.float32)
        buf4 = buf2; del buf2  # reuse
        # Topologically Sorted Source Nodes: [loss, invert_1, valid_labels, and_, distinct_indices, mask_1, mask_2, triplet_loss, triplet_loss_1, sum_2, gt, hard_triplets, num_hard_triplets, add_3, triplet_loss_2], Original ATen: [aten.add, aten.bitwise_not, aten.bitwise_and, aten._to_copy, aten.mul, aten.relu, aten.sum, aten.gt, aten.div]
        triton_red_fused__to_copy_add_bitwise_and_bitwise_not_div_gt_mul_relu_sum_1.run(buf4, buf1, arg1_1, 1, 4096, grid=grid(1), stream=stream0)
        del arg1_1
        del buf1
    return (buf4, )


def benchmark_compiled_module(times=10, repeat=10):
    from torch._dynamo.testing import rand_strided
    from torch._inductor.utils import print_performance
    arg0_1 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    arg1_1 = rand_strided((4, 4, 4, 4), (64, 16, 4, 1), device='cuda:0', dtype=torch.float32)
    fn = lambda: call([arg0_1, arg1_1])
    return print_performance(fn, times=times, repeat=repeat)


if __name__ == "__main__":
    from torch._inductor.wrapper_benchmark import compiled_module_main
    compiled_module_main('None', benchmark_compiled_module)

import torch
import torch.nn as nn
import torch.nn.functional as F


def _get_anchor_negative_triplet_mask(labels):
    labels_equal = torch.unsqueeze(labels, 0) == torch.unsqueeze(labels, 1)
    mask = labels_equal ^ 1
    return mask


def _get_anchor_positive_triplet_mask(labels):
    torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
    indices_not_equal = torch.eye(labels.shape[0]).byte() ^ 1
    labels_equal = torch.unsqueeze(labels, 0) == torch.unsqueeze(labels, 1)
    mask = indices_not_equal * labels_equal
    return mask


def _get_triplet_mask(labels):
    torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
    indices_equal = torch.eye(labels.size(0), dtype=torch.bool, device=
        labels.device)
    indices_not_equal = ~indices_equal
    i_not_equal_j = indices_not_equal.unsqueeze(2)
    i_not_equal_k = indices_not_equal.unsqueeze(1)
    j_not_equal_k = indices_not_equal.unsqueeze(0)
    distinct_indices = i_not_equal_j & i_not_equal_k & j_not_equal_k
    label_equal = labels.unsqueeze(0) == labels.unsqueeze(1)
    i_equal_j = label_equal.unsqueeze(2)
    i_equal_k = label_equal.unsqueeze(1)
    valid_labels = ~i_equal_k & i_equal_j
    mask = valid_labels & distinct_indices
    return mask


def _pairwise_distance(x, squared=False, eps=1e-16):
    cor_mat = torch.matmul(x, x.t())
    norm_mat = cor_mat.diag()
    distances = norm_mat.unsqueeze(1) - 2 * cor_mat + norm_mat.unsqueeze(0)
    distances = F.relu(distances)
    if not squared:
        mask = torch.eq(distances, 0.0).float()
        distances = distances + mask * eps
        distances = torch.sqrt(distances)
        distances = distances * (1.0 - mask)
    return distances


class HardTripletLoss(nn.Module):
    """Hard/Hardest Triplet Loss
    (pytorch implementation of https://omoindrot.github.io/triplet-loss)

    For each anchor, we get the hardest positive and hardest negative to form a triplet.
    """

    def __init__(self, margin=0.1, hardest=False, squared=False):
        """
        Args:
            margin: margin for triplet loss
            hardest: If true, loss is considered only hardest triplets.
            squared: If true, output is the pairwise squared euclidean distance matrix.
                If false, output is the pairwise euclidean distance matrix.
        """
        super(HardTripletLoss, self).__init__()
        self.margin = margin
        self.hardest = hardest
        self.squared = squared

    def forward(self, embeddings, labels):
        """
        Args:
            labels: labels of the batch, of size (batch_size,)
            embeddings: tensor of shape (batch_size, embed_dim)

        Returns:
            triplet_loss: scalar tensor containing the triplet loss
        """
        pairwise_dist = _pairwise_distance(embeddings, squared=self.squared)
        if self.hardest:
            mask_anchor_positive = _get_anchor_positive_triplet_mask(labels
                ).float()
            valid_positive_dist = pairwise_dist * mask_anchor_positive
            hardest_positive_dist, _ = torch.max(valid_positive_dist, dim=1,
                keepdim=True)
            mask_anchor_negative = _get_anchor_negative_triplet_mask(labels
                ).float()
            max_anchor_negative_dist, _ = torch.max(pairwise_dist, dim=1,
                keepdim=True)
            anchor_negative_dist = pairwise_dist + max_anchor_negative_dist * (
                1.0 - mask_anchor_negative)
            hardest_negative_dist, _ = torch.min(anchor_negative_dist, dim=
                1, keepdim=True)
            triplet_loss = F.relu(hardest_positive_dist -
                hardest_negative_dist + 0.1)
            triplet_loss = torch.mean(triplet_loss)
        else:
            anc_pos_dist = pairwise_dist.unsqueeze(dim=2)
            anc_neg_dist = pairwise_dist.unsqueeze(dim=1)
            loss = anc_pos_dist - anc_neg_dist + self.margin
            mask = _get_triplet_mask(labels).float()
            triplet_loss = loss * mask
            triplet_loss = F.relu(triplet_loss)
            hard_triplets = torch.gt(triplet_loss, 1e-16).float()
            num_hard_triplets = torch.sum(hard_triplets)
            triplet_loss = torch.sum(triplet_loss) / (num_hard_triplets + 1e-16
                )
        return triplet_loss


def get_inputs():
    return [torch.rand([4, 4]), torch.rand([4, 4, 4, 4])]


def get_init_inputs():
    return [[], {}]

import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
import torch.nn as nn
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor


@triton.jit
def triton_poi_fused_sub_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 64
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex // 16
    x4 = xindex // 4
    x1 = xindex // 4 % 4
    x0 = xindex % 4
    x5 = xindex
    tmp0 = tl.load(in_ptr0 + 5 * x2, xmask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr0 + x4, xmask, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr0 + 5 * x1, xmask, eviction_policy='evict_last')
    tmp19 = tl.load(in_ptr0 + (x0 + 4 * x2), xmask, eviction_policy=
        'evict_last')
    tmp22 = tl.load(in_ptr0 + 5 * x0, xmask, eviction_policy='evict_last')
    tmp2 = 2.0
    tmp3 = tmp1 * tmp2
    tmp4 = tmp0 - tmp3
    tmp6 = tmp4 + tmp5
    tmp7 = tl.full([1], 0, tl.int32)
    tmp8 = triton_helpers.maximum(tmp7, tmp6)
    tmp9 = 0.0
    tmp10 = tmp8 == tmp9
    tmp11 = tmp10.to(tl.float32)
    tmp12 = 1e-16
    tmp13 = tmp11 * tmp12
    tmp14 = tmp8 + tmp13
    tmp15 = libdevice.sqrt(tmp14)
    tmp16 = 1.0
    tmp17 = tmp16 - tmp11
    tmp18 = tmp15 * tmp17
    tmp20 = tmp19 * tmp2
    tmp21 = tmp0 - tmp20
    tmp23 = tmp21 + tmp22
    tmp24 = triton_helpers.maximum(tmp7, tmp23)
    tmp25 = tmp24 == tmp9
    tmp26 = tmp25.to(tl.float32)
    tmp27 = tmp26 * tmp12
    tmp28 = tmp24 + tmp27
    tmp29 = libdevice.sqrt(tmp28)
    tmp30 = tmp16 - tmp26
    tmp31 = tmp29 * tmp30
    tmp32 = tmp18 - tmp31
    tl.store(out_ptr0 + x5, tmp32, xmask)


@triton.jit
def triton_red_fused__to_copy_add_bitwise_and_bitwise_not_div_gt_mul_relu_sum_1(
    in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr,
    RBLOCK: tl.constexpr):
    rnumel = 4096
    xoffset = tl.program_id(0) * XBLOCK
    xoffset + tl.arange(0, XBLOCK)[:, None]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    rbase = tl.arange(0, RBLOCK)[None, :]
    _tmp27 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
    _tmp33 = tl.full([XBLOCK, RBLOCK], 0, tl.float32)
    for roffset in range(0, rnumel, RBLOCK):
        rindex = roffset + rbase
        rmask = rindex < rnumel
        r7 = rindex % 64
        r9 = rindex % 256
        r5 = rindex // 1024
        r4 = rindex // 256 % 4
        r2 = rindex // 16 % 4
        r1 = rindex // 4 % 4
        r0 = rindex % 4
        tmp0 = tl.load(in_ptr0 + r7, rmask, eviction_policy='evict_last',
            other=0.0)
        tmp3 = tl.load(in_ptr1 + r9, rmask, eviction_policy='evict_last',
            other=0.0)
        tmp4 = tl.load(in_ptr1 + (r7 + 64 * r5), rmask, eviction_policy=
            'evict_last', other=0.0)
        tmp7 = tl.load(in_ptr1 + (r7 + 64 * r4), rmask, eviction_policy=
            'evict_last', other=0.0)
        tmp1 = 0.1
        tmp2 = tmp0 + tmp1
        tmp5 = tmp3 == tmp4
        tmp6 = tmp5 == 0
        tmp8 = tmp7 == tmp4
        tmp9 = tmp6 & tmp8
        tmp10 = r2
        tmp11 = r1
        tmp12 = tmp10 == tmp11
        tmp13 = tmp12 == 0
        tmp14 = r0
        tmp15 = tmp10 == tmp14
        tmp16 = tmp15 == 0
        tmp17 = tmp13 & tmp16
        tmp18 = tmp11 == tmp14
        tmp19 = tmp18 == 0
        tmp20 = tmp17 & tmp19
        tmp21 = tmp9 & tmp20
        tmp22 = tmp21.to(tl.float32)
        tmp23 = tmp2 * tmp22
        tmp24 = tl.full([1, 1], 0, tl.int32)
        tmp25 = triton_helpers.maximum(tmp24, tmp23)
        tmp26 = tl.broadcast_to(tmp25, [XBLOCK, RBLOCK])
        tmp28 = _tmp27 + tmp26
        _tmp27 = tl.where(rmask, tmp28, _tmp27)
        tmp29 = 1e-16
        tmp30 = tmp25 > tmp29
        tmp31 = tmp30.to(tl.float32)
        tmp32 = tl.broadcast_to(tmp31, [XBLOCK, RBLOCK])
        tmp34 = _tmp33 + tmp32
        _tmp33 = tl.where(rmask, tmp34, _tmp33)
    tmp27 = tl.sum(_tmp27, 1)[:, None]
    tmp33 = tl.sum(_tmp33, 1)[:, None]
    tmp35 = 1e-16
    tmp36 = tmp33 + tmp35
    tmp37 = tmp27 / tmp36
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp37, None)


def call(args):
    arg0_1, arg1_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4), (4, 1))
    assert_size_stride(arg1_1, (4, 4, 4, 4), (64, 16, 4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        extern_kernels.mm(arg0_1, reinterpret_tensor(arg0_1, (4, 4), (1, 4),
            0), out=buf0)
        del arg0_1
        buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_sub_0[grid(64)](buf0, buf1, 64, XBLOCK=64,
            num_warps=1, num_stages=1)
        del buf0
        buf2 = empty_strided_cuda((), (), torch.float32)
        buf4 = buf2
        del buf2
        triton_red_fused__to_copy_add_bitwise_and_bitwise_not_div_gt_mul_relu_sum_1[
            grid(1)](buf4, buf1, arg1_1, 1, 4096, XBLOCK=1, RBLOCK=2048,
            num_warps=16, num_stages=1)
        del arg1_1
        del buf1
    return buf4,


def _get_anchor_negative_triplet_mask(labels):
    labels_equal = torch.unsqueeze(labels, 0) == torch.unsqueeze(labels, 1)
    mask = labels_equal ^ 1
    return mask


def _get_anchor_positive_triplet_mask(labels):
    torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
    indices_not_equal = torch.eye(labels.shape[0]).byte() ^ 1
    labels_equal = torch.unsqueeze(labels, 0) == torch.unsqueeze(labels, 1)
    mask = indices_not_equal * labels_equal
    return mask


def _get_triplet_mask(labels):
    torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
    indices_equal = torch.eye(labels.size(0), dtype=torch.bool, device=
        labels.device)
    indices_not_equal = ~indices_equal
    i_not_equal_j = indices_not_equal.unsqueeze(2)
    i_not_equal_k = indices_not_equal.unsqueeze(1)
    j_not_equal_k = indices_not_equal.unsqueeze(0)
    distinct_indices = i_not_equal_j & i_not_equal_k & j_not_equal_k
    label_equal = labels.unsqueeze(0) == labels.unsqueeze(1)
    i_equal_j = label_equal.unsqueeze(2)
    i_equal_k = label_equal.unsqueeze(1)
    valid_labels = ~i_equal_k & i_equal_j
    mask = valid_labels & distinct_indices
    return mask


def _pairwise_distance(x, squared=False, eps=1e-16):
    cor_mat = torch.matmul(x, x.t())
    norm_mat = cor_mat.diag()
    distances = norm_mat.unsqueeze(1) - 2 * cor_mat + norm_mat.unsqueeze(0)
    distances = F.relu(distances)
    if not squared:
        mask = torch.eq(distances, 0.0).float()
        distances = distances + mask * eps
        distances = torch.sqrt(distances)
        distances = distances * (1.0 - mask)
    return distances


class HardTripletLossNew(nn.Module):
    """Hard/Hardest Triplet Loss
    (pytorch implementation of https://omoindrot.github.io/triplet-loss)

    For each anchor, we get the hardest positive and hardest negative to form a triplet.
    """

    def __init__(self, margin=0.1, hardest=False, squared=False):
        """
        Args:
            margin: margin for triplet loss
            hardest: If true, loss is considered only hardest triplets.
            squared: If true, output is the pairwise squared euclidean distance matrix.
                If false, output is the pairwise euclidean distance matrix.
        """
        super(HardTripletLossNew, self).__init__()
        self.margin = margin
        self.hardest = hardest
        self.squared = squared

    def forward(self, input_0, input_1):
        arg0_1 = input_0
        arg1_1 = input_1
        output = call([arg0_1, arg1_1])
        return output[0]
