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 numpy as np
import torch.nn as 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_mul_rsub_sqrt_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
    tmp0 = tl.load(in_ptr0 + x0, xmask)
    tmp1 = 2.0
    tmp2 = tmp0 * tmp1
    tmp3 = 2.001
    tmp4 = tmp3 - tmp2
    tmp5 = libdevice.sqrt(tmp4)
    tmp6 = 1.0
    tmp7 = tmp6 - tmp5
    tl.store(out_ptr0 + x0, tmp7, xmask)


@triton.jit
def _triton_helper_fn_add0(arg0_0, arg1_0):
    tmp0 = arg0_0 + arg1_0
    return tmp0


@triton.jit
def triton_per_fused_add_clamp_cumsum_div_minimum_mul_sum_1(in_out_ptr1,
    in_ptr0, in_ptr1, in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
    xnumel = 4
    rnumel = 25
    RBLOCK: tl.constexpr = 32
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    rindex = tl.arange(0, RBLOCK)[None, :]
    rmask = rindex < rnumel
    r1 = rindex
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (4 * r1 + 200 * x0), rmask & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp1 = tl.load(in_ptr1 + r1, rmask, eviction_policy='evict_last', other=0.0
        )
    tmp3 = tl.load(in_ptr0 + (100 + 4 * r1 + 200 * x0), rmask & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp4 = tl.load(in_ptr1 + (25 + r1), rmask, eviction_policy='evict_last',
        other=0.0)
    tmp9 = tl.load(in_ptr2 + 4 * x0, xmask, eviction_policy='evict_last')
    tmp11 = tl.load(in_ptr0 + (1 + 4 * r1 + 200 * x0), rmask & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp13 = tl.load(in_ptr0 + (101 + 4 * r1 + 200 * x0), rmask & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp17 = tl.load(in_ptr2 + (1 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp20 = tl.load(in_ptr0 + (2 + 4 * r1 + 200 * x0), rmask & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp22 = tl.load(in_ptr0 + (102 + 4 * r1 + 200 * x0), rmask & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp26 = tl.load(in_ptr2 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp29 = tl.load(in_ptr0 + (3 + 4 * r1 + 200 * x0), rmask & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp31 = tl.load(in_ptr0 + (103 + 4 * r1 + 200 * x0), rmask & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp35 = tl.load(in_ptr2 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp2 = tmp0 + tmp1
    tmp5 = tmp3 + tmp4
    tmp6 = triton_helpers.minimum(tmp2, tmp5)
    tmp7 = 0.0
    tmp8 = triton_helpers.maximum(tmp6, tmp7)
    tmp10 = tmp8 * tmp9
    tmp12 = tmp11 + tmp1
    tmp14 = tmp13 + tmp4
    tmp15 = triton_helpers.minimum(tmp12, tmp14)
    tmp16 = triton_helpers.maximum(tmp15, tmp7)
    tmp18 = tmp16 * tmp17
    tmp19 = tmp10 + tmp18
    tmp21 = tmp20 + tmp1
    tmp23 = tmp22 + tmp4
    tmp24 = triton_helpers.minimum(tmp21, tmp23)
    tmp25 = triton_helpers.maximum(tmp24, tmp7)
    tmp27 = tmp25 * tmp26
    tmp28 = tmp19 + tmp27
    tmp30 = tmp29 + tmp1
    tmp32 = tmp31 + tmp4
    tmp33 = triton_helpers.minimum(tmp30, tmp32)
    tmp34 = triton_helpers.maximum(tmp33, tmp7)
    tmp36 = tmp34 * tmp35
    tmp37 = tmp28 + tmp36
    tmp38 = tmp8 + tmp16
    tmp39 = tmp38 + tmp25
    tmp40 = tmp39 + tmp34
    tmp41 = tmp40.to(tl.float32)
    tmp42 = tl.broadcast_to(tmp41, [XBLOCK, RBLOCK])
    tmp43, = tl.associative_scan((tmp42,), 1, _triton_helper_fn_add0)
    tmp44 = tl.broadcast_to(tmp37, [XBLOCK, RBLOCK])
    tmp46 = tl.where(rmask & xmask, tmp44, 0)
    tmp47 = tl.sum(tmp46, 1)[:, None]
    tmp48 = tmp37.to(tl.float32)
    tmp49 = tl.broadcast_to(tmp48, [XBLOCK, RBLOCK])
    tmp50, = tl.associative_scan((tmp49,), 1, _triton_helper_fn_add0)
    tmp51 = 1e-16
    tmp52 = tmp43 + tmp51
    tmp53 = tmp50 / tmp52
    tmp54 = tmp37 / tmp47
    tmp55 = tmp53 * tmp54
    tmp56 = tl.broadcast_to(tmp55, [XBLOCK, RBLOCK])
    tmp58 = tl.where(rmask & xmask, tmp56, 0)
    tmp59 = tl.sum(tmp58, 1)[:, None]
    tl.store(in_out_ptr1 + x0, tmp59, xmask)


@triton.jit
def triton_per_fused_mean_rsub_2(in_out_ptr0, in_ptr0, xnumel, rnumel,
    XBLOCK: tl.constexpr):
    RBLOCK: tl.constexpr = 4
    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
    tmp0 = tl.load(in_ptr0 + r0, None)
    tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
    tmp3 = tl.sum(tmp1, 1)[:, None]
    tmp4 = 4.0
    tmp5 = tmp3 / tmp4
    tmp6 = 1.0
    tmp7 = tmp6 - tmp5
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp7, None)


def call(args):
    arg0_1, arg1_1, arg2_1, arg3_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4), (4, 1))
    assert_size_stride(arg1_1, (4, 4), (4, 1))
    assert_size_stride(arg2_1, (50, 1, 1), (1, 1, 1))
    assert_size_stride(arg3_1, (50,), (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_mul_rsub_sqrt_0[grid(16)](arg0_1, buf0, 16, XBLOCK
            =16, num_warps=1, num_stages=1)
        del arg0_1
        buf1 = extern_kernels.convolution(reinterpret_tensor(buf0, (4, 1, 4
            ), (4, 0, 1), 0), arg2_1, stride=(1,), padding=(0,), dilation=(
            1,), transposed=False, output_padding=(0,), groups=1, bias=None)
        assert_size_stride(buf1, (4, 50, 4), (200, 4, 1))
        del arg2_1
        del buf0
        buf6 = empty_strided_cuda((4,), (1,), torch.float32)
        buf7 = buf6
        del buf6
        triton_per_fused_add_clamp_cumsum_div_minimum_mul_sum_1[grid(4)](buf7,
            buf1, arg3_1, arg1_1, 4, 25, XBLOCK=1, num_warps=2, num_stages=1)
        del arg1_1
        del arg3_1
        del buf1
        buf8 = empty_strided_cuda((), (), torch.float32)
        buf9 = buf8
        del buf8
        triton_per_fused_mean_rsub_2[grid(1)](buf9, buf7, 1, 4, XBLOCK=1,
            num_warps=2, num_stages=1)
        del buf7
    return buf9,


def sim_to_dist(scores):
    return 1 - torch.sqrt(2.001 - 2 * scores)


class APLoss(nn.Module):
    """ Differentiable AP loss, through quantization. From the paper:

        Learning with Average Precision: Training Image Retrieval with a Listwise Loss
        Jerome Revaud, Jon Almazan, Rafael Sampaio de Rezende, Cesar de Souza
        https://arxiv.org/abs/1906.07589

        Input: (N, M)   values in [min, max]
        label: (N, M)   values in {0, 1}

        Returns: 1 - mAP (mean AP for each n in {1..N})
                 Note: typically, this is what you wanna minimize
    """

    def __init__(self, nq=25, min=0, max=1):
        nn.Module.__init__(self)
        assert isinstance(nq, int) and 2 <= nq <= 100
        self.nq = nq
        self.min = min
        self.max = max
        gap = max - min
        assert gap > 0
        self.quantizer = q = nn.Conv1d(1, 2 * nq, kernel_size=1, bias=True)
        q.weight = nn.Parameter(q.weight.detach(), requires_grad=False)
        q.bias = nn.Parameter(q.bias.detach(), requires_grad=False)
        a = (nq - 1) / gap
        q.weight[:nq] = -a
        q.bias[:nq] = torch.from_numpy(a * min + np.arange(nq, 0, -1))
        q.weight[nq:] = a
        q.bias[nq:] = torch.from_numpy(np.arange(2 - nq, 2, 1) - a * min)
        q.weight[0] = q.weight[-1] = 0
        q.bias[0] = q.bias[-1] = 1

    def forward(self, x, label, qw=None, ret='1-mAP'):
        assert x.shape == label.shape
        N, M = x.shape
        q = self.quantizer(x.unsqueeze(1))
        q = torch.min(q[:, :self.nq], q[:, self.nq:]).clamp(min=0)
        nbs = q.sum(dim=-1)
        rec = (q * label.view(N, 1, M).float()).sum(dim=-1)
        prec = rec.cumsum(dim=-1) / (1e-16 + nbs.cumsum(dim=-1))
        rec /= rec.sum(dim=-1).unsqueeze(1)
        ap = (prec * rec).sum(dim=-1)
        if ret == '1-mAP':
            if qw is not None:
                ap *= qw
            return 1 - ap.mean()
        elif ret == 'AP':
            assert qw is None
            return ap
        else:
            raise ValueError('Bad return type for APLoss(): %s' % str(ret))

    def measures(self, x, gt, loss=None):
        if loss is None:
            loss = self.forward(x, gt)
        return {'loss_ap': float(loss)}


class APLoss_distNew(APLoss):

    def forward(self, input_0, input_1):
        arg2_1 = self.quantizer.weight
        arg3_1 = self.quantizer.bias
        arg0_1 = input_0
        arg1_1 = input_1
        output = call([arg0_1, arg1_1, arg2_1, arg3_1])
        return output[0]


Measured latency_ms: 0.015011