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 import Tensor
from torch import nn
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_add_mul_sub_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
    .constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x1 = xindex // 4
    x0 = xindex % 4
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
    tmp2 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp11 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
    tmp13 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp16 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp19 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp23 = tl.load(in_out_ptr0 + x2, xmask)
    tmp1 = tmp0 * tmp0
    tmp3 = tmp2 * tmp2
    tmp4 = tmp1 + tmp3
    tmp6 = tmp5 * tmp5
    tmp7 = tmp4 + tmp6
    tmp9 = tmp8 * tmp8
    tmp10 = tmp7 + tmp9
    tmp12 = tmp11 * tmp11
    tmp14 = tmp13 * tmp13
    tmp15 = tmp12 + tmp14
    tmp17 = tmp16 * tmp16
    tmp18 = tmp15 + tmp17
    tmp20 = tmp19 * tmp19
    tmp21 = tmp18 + tmp20
    tmp22 = tmp10 + tmp21
    tmp24 = 2.0
    tmp25 = tmp23 * tmp24
    tmp26 = tmp22 - tmp25
    tl.store(in_out_ptr0 + x2, tmp26, xmask)


@triton.jit
def triton_per_fused_add_bitwise_not_clamp_min_eq_max_mean_min_mul_neg_sub_1(
    in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
    RBLOCK: tl.constexpr = 16
    xoffset = tl.program_id(0) * XBLOCK
    xoffset + tl.arange(0, XBLOCK)[:, None]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    rindex = tl.arange(0, RBLOCK)[None, :]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    r0 = rindex % 4
    r2 = rindex
    tmp0 = tl.load(in_ptr0 + r0, None, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr1 + r0, None, eviction_policy='evict_last')
    tmp2 = tl.load(in_ptr1 + r2, None)
    tmp6 = tl.load(in_ptr0 + (4 + r0), None, eviction_policy='evict_last')
    tmp7 = tl.load(in_ptr1 + (4 + r0), None, eviction_policy='evict_last')
    tmp12 = tl.load(in_ptr0 + (8 + r0), None, eviction_policy='evict_last')
    tmp13 = tl.load(in_ptr1 + (8 + r0), None, eviction_policy='evict_last')
    tmp18 = tl.load(in_ptr0 + (12 + r0), None, eviction_policy='evict_last')
    tmp19 = tl.load(in_ptr1 + (12 + r0), None, eviction_policy='evict_last')
    tmp3 = tmp1 == tmp2
    tmp4 = tmp3.to(tl.float32)
    tmp5 = tmp0 * tmp4
    tmp8 = tmp7 == tmp2
    tmp9 = tmp8.to(tl.float32)
    tmp10 = tmp6 * tmp9
    tmp11 = triton_helpers.maximum(tmp5, tmp10)
    tmp14 = tmp13 == tmp2
    tmp15 = tmp14.to(tl.float32)
    tmp16 = tmp12 * tmp15
    tmp17 = triton_helpers.maximum(tmp11, tmp16)
    tmp20 = tmp19 == tmp2
    tmp21 = tmp20.to(tl.float32)
    tmp22 = tmp18 * tmp21
    tmp23 = triton_helpers.maximum(tmp17, tmp22)
    tmp24 = tmp3 == 0
    tmp25 = tmp24.to(tl.float32)
    tmp26 = tmp0 * tmp25
    tmp27 = 1000000000.0
    tmp28 = tmp4 * tmp27
    tmp29 = tmp26 + tmp28
    tmp30 = tmp8 == 0
    tmp31 = tmp30.to(tl.float32)
    tmp32 = tmp6 * tmp31
    tmp33 = tmp9 * tmp27
    tmp34 = tmp32 + tmp33
    tmp35 = triton_helpers.minimum(tmp29, tmp34)
    tmp36 = tmp14 == 0
    tmp37 = tmp36.to(tl.float32)
    tmp38 = tmp12 * tmp37
    tmp39 = tmp15 * tmp27
    tmp40 = tmp38 + tmp39
    tmp41 = triton_helpers.minimum(tmp35, tmp40)
    tmp42 = tmp20 == 0
    tmp43 = tmp42.to(tl.float32)
    tmp44 = tmp18 * tmp43
    tmp45 = tmp21 * tmp27
    tmp46 = tmp44 + tmp45
    tmp47 = triton_helpers.minimum(tmp41, tmp46)
    tmp48 = tmp47 - tmp23
    tmp49 = -1.0
    tmp50 = tmp49 * tmp48
    tmp51 = 0.3
    tmp52 = tmp50 + tmp51
    tmp53 = 0.0
    tmp54 = triton_helpers.maximum(tmp52, tmp53)
    tmp55 = tl.broadcast_to(tmp54, [XBLOCK, RBLOCK])
    tmp57 = tl.sum(tmp55, 1)[:, None]
    tmp58 = 16.0
    tmp59 = tmp57 / tmp58
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp59, 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, 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)
        buf1 = buf0
        del buf0
        get_raw_stream(0)
        triton_poi_fused_add_mul_sub_0[grid(16)](buf1, arg0_1, 16, XBLOCK=
            16, num_warps=1, num_stages=1)
        del arg0_1
        buf4 = empty_strided_cuda((), (), torch.float32)
        buf5 = buf4
        del buf4
        triton_per_fused_add_bitwise_not_clamp_min_eq_max_mean_min_mul_neg_sub_1[
            grid(1)](buf5, buf1, arg1_1, 1, 16, XBLOCK=1, num_warps=2,
            num_stages=1)
        del arg1_1
        del buf1
    return buf5,


def euclidean_dist(x: 'Tensor', y: 'Tensor') ->Tensor:
    xx, yy = torch.meshgrid((x ** 2).sum(1), (y ** 2).sum(1))
    return xx + yy - 2 * (x @ y.t())


class TripletLossNew(nn.Module):
    """
    Modified from Tong Xiao's open-reid (https://github.com/Cysu/open-reid).
    Related Triplet Loss theory can be found in paper 'In Defense of the Triplet
    Loss for Person Re-Identification'
    """

    def __init__(self, margin: 'float'=0.3) ->None:
        super().__init__()
        self.margin = margin

    def hard_example_mining(self, dist, is_pos, is_neg):
        """For each anchor, find the hardest positive and negative sample.
        Args:
            dist_mat: pair wise distance between samples, shape [N, M]
            is_pos: positive index with shape [N, M]
            is_neg: negative index with shape [N, M]
        Returns:
            dist_ap: Tensor, distance(anchor, positive); shape [N]
            dist_an: Tensor, distance(anchor, negative); shape [N]
        NOTE: Only consider the case in which all labels have same num of samples,
        thus we can cope with all anchors in parallel.
        """
        assert len(dist.size()) == 2
        dist_ap = torch.max(dist * is_pos, dim=1)[0]
        dist_an = torch.min(dist * is_neg + is_pos * 1000000000.0, dim=1)[0]
        return dist_ap, dist_an

    def weighted_example_mining(self, dist, is_pos, is_neg):
        """For each anchor, find the weighted positive and negative sample.
        """
        assert len(dist.size()) == 2
        dist_ap = dist * is_pos
        dist_an = dist * is_neg
        weights_ap = self.softmax_weights(dist_ap, is_pos)
        weights_an = self.softmax_weights(-dist_an, is_neg)
        dist_ap = torch.sum(dist_ap * weights_ap, dim=1)
        dist_an = torch.sum(dist_an * weights_an, dim=1)
        return dist_ap, dist_an

    def softmax_weights(self, dist, mask):
        max_v = torch.max(dist * mask, dim=1, keepdim=True)[0]
        diff = dist - max_v
        Z = torch.sum(torch.exp(diff) * mask, dim=1, keepdim=True) + 1e-06
        W = torch.exp(diff) * mask / Z
        return W

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


Measured latency_ms: 0.033508