# 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_1/inductor_cache/5m/c5msm2swedganbgicpwv7z6bxnojfd4zpoz7zdoyyr7c54v4kppa.py
# Topologically Sorted Source Nodes: [eq, type_as, eye, type_as_1, pos], Original ATen: [aten.eq, aten._to_copy, aten.eye, aten.sub]
# Source node to ATen node mapping:
#   eq => eq
#   eye => eq_1, full_default, full_default_1, iota_1, where
#   pos => sub_1
#   type_as => convert_element_type
#   type_as_1 => device_put
# Graph fragment:
#   %eq : [num_users=1] = call_function[target=torch.ops.aten.eq.Tensor](args = (%expand_1, %expand_2), kwargs = {})
#   %convert_element_type : [num_users=1] = call_function[target=torch.ops.prims.convert_element_type.default](args = (%eq, torch.float32), kwargs = {})
#   %iota_1 : [num_users=1] = call_function[target=torch.ops.prims.iota.default](args = (4,), kwargs = {start: 0, step: 1, dtype: torch.int64, device: cpu, requires_grad: False})
#   %eq_1 : [num_users=1] = call_function[target=torch.ops.aten.eq.Tensor](args = (%unsqueeze_3, %iota_1), kwargs = {})
#   %full_default : [num_users=1] = call_function[target=torch.ops.aten.full.default](args = ([1], 1), kwargs = {dtype: torch.float32, layout: torch.strided, device: cpu, pin_memory: False})
#   %full_default_1 : [num_users=1] = call_function[target=torch.ops.aten.full.default](args = ([], 0.0), kwargs = {dtype: torch.float32, layout: torch.strided, device: cpu, pin_memory: False})
#   %where : [num_users=1] = call_function[target=torch.ops.aten.where.self](args = (%eq_1, %full_default, %full_default_1), kwargs = {})
#   %device_put : [num_users=1] = call_function[target=torch.ops.prims.device_put.default](args = (%where, cuda:0), kwargs = {})
#   %sub_1 : [num_users=3] = call_function[target=torch.ops.aten.sub.Tensor](args = (%convert_element_type, %device_put), kwargs = {})
triton_poi_fused__to_copy_eq_eye_sub_0 = async_compile.triton('triton_poi_fused__to_copy_eq_eye_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=[16], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=90, major=9, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=132), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused__to_copy_eq_eye_sub_0', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 2, 'num_reduction': 0, 'backend_hash': 'B098E03CDA7B8ADC90DAFFDF24A2956451D1B13F297756A5DCC209498AA53705', '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__to_copy_eq_eye_sub_0(in_ptr0, out_ptr0, xnumel, XBLOCK : tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 4
    x1 = (xindex // 4)
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + (x0), xmask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr0 + (x1), xmask, eviction_policy='evict_last')
    tmp2 = tmp0 == tmp1
    tmp3 = tmp2.to(tl.float32)
    tmp4 = x1
    tmp5 = x0
    tmp6 = tmp4 == tmp5
    tmp7 = 1.0
    tmp8 = 0.0
    tmp9 = tl.where(tmp6, tmp7, tmp8)
    tmp10 = tmp3 - tmp9
    tl.store(out_ptr0 + (x2), tmp10, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_1/inductor_cache/mt/cmtcrf4vhqnkl4r7fcq3i54oe5rrchhvsrm2blx7bs5cw25yxwxg.py
# Topologically Sorted Source Nodes: [sub_2, M, dist_diff, lt, type_as_2, mask], Original ATen: [aten.rsub, aten.mul, aten.sub, aten.lt, aten._to_copy]
# Source node to ATen node mapping:
#   M => mul_1
#   dist_diff => sub_3
#   lt => lt
#   mask => mul_2
#   sub_2 => sub_2
#   type_as_2 => convert_element_type_2
# Graph fragment:
#   %sub_2 : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (1, %expand_5), kwargs = {})
#   %mul_1 : [num_users=3] = call_function[target=torch.ops.aten.mul.Tensor](args = (%expand_4, %sub_2), kwargs = {})
#   %sub_3 : [num_users=3] = call_function[target=torch.ops.aten.sub.Tensor](args = (%expand_3, %permute_2), kwargs = {})
#   %lt : [num_users=1] = call_function[target=torch.ops.aten.lt.Scalar](args = (%sub_3, 0), kwargs = {})
#   %convert_element_type_2 : [num_users=1] = call_function[target=torch.ops.prims.convert_element_type.default](args = (%lt, torch.float32), kwargs = {})
#   %mul_2 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%mul_1, %convert_element_type_2), kwargs = {})
triton_poi_fused__to_copy_lt_mul_rsub_sub_1 = async_compile.triton('triton_poi_fused__to_copy_lt_mul_rsub_sub_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.pointwise(
    size_hints=[64], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: '*fp32', 5: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=90, major=9, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=132), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3, 4, 5), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused__to_copy_lt_mul_rsub_sub_1', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 7, 'num_reduction': 0, 'backend_hash': 'B098E03CDA7B8ADC90DAFFDF24A2956451D1B13F297756A5DCC209498AA53705', '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__to_copy_lt_mul_rsub_sub_1(in_ptr0, in_ptr1, out_ptr0, out_ptr1, out_ptr2, xnumel, XBLOCK : tl.constexpr):
    xnumel = 64
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 4
    x2 = (xindex // 16)
    x4 = (xindex // 4)
    x3 = xindex
    x1 = (xindex // 4) % 4
    tmp0 = tl.load(in_ptr0 + (x0 + (4*x2)), xmask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr0 + (x4), xmask, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr1 + (5*x2), xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr1 + (5*x0), xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr1 + (x0 + (4*x2)), xmask, eviction_policy='evict_last')
    tmp17 = tl.load(in_ptr1 + (5*x1), xmask, eviction_policy='evict_last')
    tmp19 = tl.load(in_ptr1 + (x4), xmask, eviction_policy='evict_last')
    tmp2 = 1.0
    tmp3 = tmp2 - tmp1
    tmp4 = tmp0 * tmp3
    tmp7 = tmp5 + tmp6
    tmp9 = 2.0
    tmp10 = tmp8 * tmp9
    tmp11 = tmp7 - tmp10
    tmp12 = 0.0
    tmp13 = triton_helpers.maximum(tmp11, tmp12)
    tmp14 = 0.0001
    tmp15 = triton_helpers.maximum(tmp13, tmp14)
    tmp16 = libdevice.sqrt(tmp15)
    tmp18 = tmp5 + tmp17
    tmp20 = tmp19 * tmp9
    tmp21 = tmp18 - tmp20
    tmp22 = triton_helpers.maximum(tmp21, tmp12)
    tmp23 = triton_helpers.maximum(tmp22, tmp14)
    tmp24 = libdevice.sqrt(tmp23)
    tmp25 = tmp16 - tmp24
    tmp26 = tmp25 < tmp12
    tmp27 = tmp26.to(tl.float32)
    tmp28 = tmp4 * tmp27
    tl.store(out_ptr0 + (x3), tmp4, xmask)
    tl.store(out_ptr1 + (x3), tmp25, xmask)
    tl.store(out_ptr2 + (x3), tmp28, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_1/inductor_cache/4s/c4szmh55bascmq3yoquvdbwh2ngiqzyyqps6uo54bbb2gdafugky.py
# Topologically Sorted Source Nodes: [lt_1, type_as_3, mul_3, mask_final, mask_final_1], Original ATen: [aten.lt, aten._to_copy, aten.mul, aten.sum, aten.gt]
# Source node to ATen node mapping:
#   lt_1 => lt_1
#   mask_final => sum_1
#   mask_final_1 => gt
#   mul_3 => mul_3
#   type_as_3 => convert_element_type_3
# Graph fragment:
#   %lt_1 : [num_users=1] = call_function[target=torch.ops.aten.lt.Scalar](args = (%sub_3, 0), kwargs = {})
#   %convert_element_type_3 : [num_users=1] = call_function[target=torch.ops.prims.convert_element_type.default](args = (%lt_1, torch.float32), kwargs = {})
#   %mul_3 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%mul_1, %convert_element_type_3), kwargs = {})
#   %sum_1 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%mul_3, [1], True), kwargs = {})
#   %gt : [num_users=1] = call_function[target=torch.ops.aten.gt.Scalar](args = (%sum_1, 0), kwargs = {})
triton_poi_fused__to_copy_gt_lt_mul_sum_2 = async_compile.triton('triton_poi_fused__to_copy_gt_lt_mul_sum_2', '''
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=[16], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*i1', 3: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=90, major=9, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=132), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused__to_copy_gt_lt_mul_sum_2', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 8, 'num_reduction': 0, 'backend_hash': 'B098E03CDA7B8ADC90DAFFDF24A2956451D1B13F297756A5DCC209498AA53705', '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__to_copy_gt_lt_mul_sum_2(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK : tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 4
    x1 = (xindex // 4)
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + (x0 + (16*x1)), xmask)
    tmp1 = tl.load(in_ptr1 + (x0 + (16*x1)), xmask)
    tmp6 = tl.load(in_ptr0 + (4 + x0 + (16*x1)), xmask)
    tmp7 = tl.load(in_ptr1 + (4 + x0 + (16*x1)), xmask)
    tmp12 = tl.load(in_ptr0 + (8 + x0 + (16*x1)), xmask)
    tmp13 = tl.load(in_ptr1 + (8 + x0 + (16*x1)), xmask)
    tmp18 = tl.load(in_ptr0 + (12 + x0 + (16*x1)), xmask)
    tmp19 = tl.load(in_ptr1 + (12 + x0 + (16*x1)), xmask)
    tmp2 = 0.0
    tmp3 = tmp1 < tmp2
    tmp4 = tmp3.to(tl.float32)
    tmp5 = tmp0 * tmp4
    tmp8 = tmp7 < tmp2
    tmp9 = tmp8.to(tl.float32)
    tmp10 = tmp6 * tmp9
    tmp11 = tmp5 + tmp10
    tmp14 = tmp13 < tmp2
    tmp15 = tmp14.to(tl.float32)
    tmp16 = tmp12 * tmp15
    tmp17 = tmp11 + tmp16
    tmp20 = tmp19 < tmp2
    tmp21 = tmp20.to(tl.float32)
    tmp22 = tmp18 * tmp21
    tmp23 = tmp17 + tmp22
    tmp24 = tmp23 > tmp2
    tl.store(out_ptr0 + (x2), tmp24, xmask)
''', 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, ), (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: [eq, type_as, eye, type_as_1, pos], Original ATen: [aten.eq, aten._to_copy, aten.eye, aten.sub]
        stream0 = get_raw_stream(0)
        triton_poi_fused__to_copy_eq_eye_sub_0.run(arg1_1, buf0, 16, grid=grid(16), stream=stream0)
        del arg1_1
        buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [prod], Original ATen: [aten.mm]
        extern_kernels.mm(arg0_1, reinterpret_tensor(arg0_1, (4, 4), (1, 4), 0), out=buf2)
        del arg0_1
        buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
        buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
        buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [sub_2, M, dist_diff, lt, type_as_2, mask], Original ATen: [aten.rsub, aten.mul, aten.sub, aten.lt, aten._to_copy]
        triton_poi_fused__to_copy_lt_mul_rsub_sub_1.run(buf0, buf2, buf1, buf3, buf4, 64, grid=grid(64), stream=stream0)
        del buf2
        buf5 = empty_strided_cuda((4, 1, 4), (4, 4, 1), torch.bool)
        # Topologically Sorted Source Nodes: [lt_1, type_as_3, mul_3, mask_final, mask_final_1], Original ATen: [aten.lt, aten._to_copy, aten.mul, aten.sum, aten.gt]
        triton_poi_fused__to_copy_gt_lt_mul_sum_2.run(buf1, buf3, buf5, 16, grid=grid(16), stream=stream0)
    return (buf0, buf1, buf3, buf4, reinterpret_tensor(buf5, (4, 4), (4, 1), 0), )


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, ), (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 torchvision.transforms.functional as F
import torch.nn.functional as F
import torch.utils.model_zoo


def pdist(A, squared=False, eps=0.0001):
    prod = torch.mm(A, A.t())
    norm = prod.diag().unsqueeze(1).expand_as(prod)
    res = (norm + norm.t() - 2 * prod).clamp(min=0)
    if squared:
        return res
    else:
        return res.clamp(min=eps).sqrt()


def masked_maximum(data, mask, dim=1):
    """Computes the axis wise maximum over chosen elements.
    Args:
    data: 2-D float `Tensor` of size [n, m].
    mask: 2-D Boolean `Tensor` of size [n, m].
    dim: The dimension over which to compute the maximum.
    Returns:
    masked_maximums: N-D `Tensor`.
      The maximized dimension is of size 1 after the operation.
    """
    axis_minimums = data.min(dim, keepdim=True)[0]
    masked_maximums = torch.max(torch.mul(data - axis_minimums, mask), dim=
        dim, keepdim=True)[0] + axis_minimums
    return masked_maximums


def masked_minimum(data, mask, dim=1):
    """Computes the axis wise minimum over chosen elements.
    Args:
    data: 2-D float `Tensor` of size [n, m].
    mask: 2-D Boolean `Tensor` of size [n, m].
    dim: The dimension over which to compute the minimum.
    Returns:
    masked_minimums: N-D `Tensor`.
      The minimized dimension is of size 1 after the operation.
    """
    axis_maximums = data.max(dim, keepdim=True)[0]
    masked_minimums = torch.min(torch.mul(data - axis_maximums, mask), dim=
        dim, keepdim=True)[0] + axis_maximums
    return masked_minimums


class TripletSemihardLoss(torch.nn.Module):
    """
    Computes the triplet loss with semi-hard negative mining.
    For every positive pair find only *one* hardest semihard negative example.

    The loss encourages the positive distances (between a pair of embeddings with
    the same labels) to be smaller than the minimum negative distance - margin.
    The negative distance is selected among the neg pairsi
      which are at least greater than the positive distance (called semi-hard negatives),
      but withing the margin radius from anchor.
     If no such negative exists,
    uses the largest negative distance instead.
    See: https://arxiv.org/abs/1503.03832.
    Args:
        labels: 1-D int32 `Tensor` with shape [batch_size] of
          multiclass integer labels.
        embeddings: 2-D float `Tensor` of embedding vectors. Embeddings should
          be l2 normalized.
        margin: Float, margin term in the loss definition.
    Returns:
        triplet_loss: float32 scalar.
    """

    def __init__(self, margin=1.0, soft=False, **kwargs):
        self.margin = margin
        self.soft = soft
        torch.nn.Module.__init__(self)

    def forward(self, embeddings, labels):
        d = pdist(embeddings)
        pos = torch.eq(*[labels.unsqueeze(dim).expand_as(d) for dim in [0, 1]]
            ).type_as(d) - torch.eye(len(d)).type_as(d)
        T = d.unsqueeze(1).expand(*((len(d),) * 3))
        M = pos.unsqueeze(1).expand_as(T) * (1 - pos.unsqueeze(2).expand_as(T))
        dist_diff = T - T.transpose(1, 2)
        mask = M * (dist_diff < 0).type_as(M)
        mask_final = (M * (dist_diff < 0).type_as(M)).sum(dim=1, keepdim=True)
        mask_final = mask_final > 0
        mask_final.squeeze_(dim=1)
        assert len(mask_final.shape) == 2
        dist_diff_negatives_outside = masked_maximum(dist_diff, mask, dim=1
            ).squeeze_(dim=1)
        dist_diff_negatives_inside = masked_minimum(dist_diff, M, dim=1
            ).squeeze_(dim=1)
        dist_diff_semi_hard_negatives = torch.where(mask_final,
            dist_diff_negatives_outside, dist_diff_negatives_inside)
        if self.soft:
            loss_mat = dist_diff_semi_hard_negatives.exp().log1p()
        else:
            loss_mat = dist_diff_semi_hard_negatives + self.margin
        assert len(loss_mat.shape) == 2
        assert len(pos.shape) == 2
        return F.relu(pos * loss_mat).sum() / pos.sum()


def get_inputs():
    return [torch.rand([4, 4]), torch.rand([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.utils.model_zoo
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__to_copy_eq_eye_sub_0(in_ptr0, out_ptr0, xnumel,
    XBLOCK: tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 4
    x1 = xindex // 4
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
    tmp2 = tmp0 == tmp1
    tmp3 = tmp2.to(tl.float32)
    tmp4 = x1
    tmp5 = x0
    tmp6 = tmp4 == tmp5
    tmp7 = 1.0
    tmp8 = 0.0
    tmp9 = tl.where(tmp6, tmp7, tmp8)
    tmp10 = tmp3 - tmp9
    tl.store(out_ptr0 + x2, tmp10, xmask)


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


@triton.jit
def triton_poi_fused__to_copy_gt_lt_mul_sum_2(in_ptr0, in_ptr1, out_ptr0,
    xnumel, XBLOCK: tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 4
    x1 = xindex // 4
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
    tmp1 = tl.load(in_ptr1 + (x0 + 16 * x1), xmask)
    tmp6 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
    tmp7 = tl.load(in_ptr1 + (4 + x0 + 16 * x1), xmask)
    tmp12 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
    tmp13 = tl.load(in_ptr1 + (8 + x0 + 16 * x1), xmask)
    tmp18 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
    tmp19 = tl.load(in_ptr1 + (12 + x0 + 16 * x1), xmask)
    tmp2 = 0.0
    tmp3 = tmp1 < tmp2
    tmp4 = tmp3.to(tl.float32)
    tmp5 = tmp0 * tmp4
    tmp8 = tmp7 < tmp2
    tmp9 = tmp8.to(tl.float32)
    tmp10 = tmp6 * tmp9
    tmp11 = tmp5 + tmp10
    tmp14 = tmp13 < tmp2
    tmp15 = tmp14.to(tl.float32)
    tmp16 = tmp12 * tmp15
    tmp17 = tmp11 + tmp16
    tmp20 = tmp19 < tmp2
    tmp21 = tmp20.to(tl.float32)
    tmp22 = tmp18 * tmp21
    tmp23 = tmp17 + tmp22
    tmp24 = tmp23 > tmp2
    tl.store(out_ptr0 + x2, tmp24, xmask)


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,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused__to_copy_eq_eye_sub_0[grid(16)](arg1_1, buf0, 16,
            XBLOCK=16, num_warps=1, num_stages=1)
        del arg1_1
        buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        extern_kernels.mm(arg0_1, reinterpret_tensor(arg0_1, (4, 4), (1, 4),
            0), out=buf2)
        del arg0_1
        buf1 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
        buf3 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
        buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
        triton_poi_fused__to_copy_lt_mul_rsub_sub_1[grid(64)](buf0, buf2,
            buf1, buf3, buf4, 64, XBLOCK=64, num_warps=1, num_stages=1)
        del buf2
        buf5 = empty_strided_cuda((4, 1, 4), (4, 4, 1), torch.bool)
        triton_poi_fused__to_copy_gt_lt_mul_sum_2[grid(16)](buf1, buf3,
            buf5, 16, XBLOCK=16, num_warps=1, num_stages=1)
    return buf0, buf1, buf3, buf4, reinterpret_tensor(buf5, (4, 4), (4, 1), 0)


def pdist(A, squared=False, eps=0.0001):
    prod = torch.mm(A, A.t())
    norm = prod.diag().unsqueeze(1).expand_as(prod)
    res = (norm + norm.t() - 2 * prod).clamp(min=0)
    if squared:
        return res
    else:
        return res.clamp(min=eps).sqrt()


def masked_maximum(data, mask, dim=1):
    """Computes the axis wise maximum over chosen elements.
    Args:
    data: 2-D float `Tensor` of size [n, m].
    mask: 2-D Boolean `Tensor` of size [n, m].
    dim: The dimension over which to compute the maximum.
    Returns:
    masked_maximums: N-D `Tensor`.
      The maximized dimension is of size 1 after the operation.
    """
    axis_minimums = data.min(dim, keepdim=True)[0]
    masked_maximums = torch.max(torch.mul(data - axis_minimums, mask), dim=
        dim, keepdim=True)[0] + axis_minimums
    return masked_maximums


def masked_minimum(data, mask, dim=1):
    """Computes the axis wise minimum over chosen elements.
    Args:
    data: 2-D float `Tensor` of size [n, m].
    mask: 2-D Boolean `Tensor` of size [n, m].
    dim: The dimension over which to compute the minimum.
    Returns:
    masked_minimums: N-D `Tensor`.
      The minimized dimension is of size 1 after the operation.
    """
    axis_maximums = data.max(dim, keepdim=True)[0]
    masked_minimums = torch.min(torch.mul(data - axis_maximums, mask), dim=
        dim, keepdim=True)[0] + axis_maximums
    return masked_minimums


class TripletSemihardLossNew(torch.nn.Module):
    """
    Computes the triplet loss with semi-hard negative mining.
    For every positive pair find only *one* hardest semihard negative example.

    The loss encourages the positive distances (between a pair of embeddings with
    the same labels) to be smaller than the minimum negative distance - margin.
    The negative distance is selected among the neg pairsi
      which are at least greater than the positive distance (called semi-hard negatives),
      but withing the margin radius from anchor.
     If no such negative exists,
    uses the largest negative distance instead.
    See: https://arxiv.org/abs/1503.03832.
    Args:
        labels: 1-D int32 `Tensor` with shape [batch_size] of
          multiclass integer labels.
        embeddings: 2-D float `Tensor` of embedding vectors. Embeddings should
          be l2 normalized.
        margin: Float, margin term in the loss definition.
    Returns:
        triplet_loss: float32 scalar.
    """

    def __init__(self, margin=1.0, soft=False, **kwargs):
        self.margin = margin
        self.soft = soft
        torch.nn.Module.__init__(self)

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