import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F


class NTXent(nn.Module):
    """
    Contrastive loss with distributed data parallel support
    code: https://github.com/AndrewAtanov/simclr-pytorch/blob/master/models/losses.py
    """
    LARGE_NUMBER = 1000000000.0

    def __init__(self, tau=1.0, gpu=None, multiplier=2, distributed=False):
        super().__init__()
        self.tau = tau
        self.multiplier = multiplier
        self.distributed = distributed
        self.norm = 1.0

    def forward(self, batch_sample_one, batch_sample_two):
        z = torch.cat([batch_sample_one, batch_sample_two], dim=0)
        n = z.shape[0]
        assert n % self.multiplier == 0
        z = F.normalize(z, p=2, dim=1) / np.sqrt(self.tau)
        logits = z @ z.t()
        logits[np.arange(n), np.arange(n)] = -self.LARGE_NUMBER
        logprob = F.log_softmax(logits, dim=1)
        m = self.multiplier
        labels = (np.repeat(np.arange(n), m) + np.tile(np.arange(m) * n //
            m, n)) % n
        labels = labels.reshape(n, m)[:, 1:].reshape(-1)
        loss = -logprob[np.repeat(np.arange(n), m - 1), labels].sum() / n / (m
             - 1) / self.norm
        return loss


def get_inputs():
    return [torch.rand([4, 4]), torch.rand([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, math as tl_math
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_cat_linalg_vector_norm_0(in_ptr0, in_ptr1, out_ptr0,
    xnumel, XBLOCK: tl.constexpr):
    xnumel = 8
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = x0
    tl.full([1], 0, tl.int64)
    tmp3 = tl.full([1], 4, tl.int64)
    tmp4 = tmp0 < tmp3
    tmp5 = tl.load(in_ptr0 + 4 * x0, tmp4 & xmask, eviction_policy=
        'evict_last', other=0.0)
    tmp6 = tmp0 >= tmp3
    tl.full([1], 8, tl.int64)
    tmp9 = tl.load(in_ptr1 + 4 * (-4 + x0), tmp6 & xmask, eviction_policy=
        'evict_last', other=0.0)
    tmp10 = tl.where(tmp4, tmp5, tmp9)
    tmp11 = tmp10 * tmp10
    tmp12 = tl.load(in_ptr0 + (1 + 4 * x0), tmp4 & xmask, eviction_policy=
        'evict_last', other=0.0)
    tmp13 = tl.load(in_ptr1 + (1 + 4 * (-4 + x0)), tmp6 & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp14 = tl.where(tmp4, tmp12, tmp13)
    tmp15 = tmp14 * tmp14
    tmp16 = tmp11 + tmp15
    tmp17 = tl.load(in_ptr0 + (2 + 4 * x0), tmp4 & xmask, eviction_policy=
        'evict_last', other=0.0)
    tmp18 = tl.load(in_ptr1 + (2 + 4 * (-4 + x0)), tmp6 & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp19 = tl.where(tmp4, tmp17, tmp18)
    tmp20 = tmp19 * tmp19
    tmp21 = tmp16 + tmp20
    tmp22 = tl.load(in_ptr0 + (3 + 4 * x0), tmp4 & xmask, eviction_policy=
        'evict_last', other=0.0)
    tmp23 = tl.load(in_ptr1 + (3 + 4 * (-4 + x0)), tmp6 & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp24 = tl.where(tmp4, tmp22, tmp23)
    tmp25 = tmp24 * tmp24
    tmp26 = tmp21 + tmp25
    tl.store(out_ptr0 + x0, tmp26, xmask)


@triton.jit
def triton_poi_fused_cat_div_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel,
    XBLOCK: tl.constexpr):
    xnumel = 32
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x1 = xindex // 4
    x0 = xindex % 4
    x2 = xindex
    tmp11 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
    tmp0 = x1
    tl.full([1], 0, tl.int64)
    tmp3 = tl.full([1], 4, tl.int64)
    tmp4 = tmp0 < tmp3
    tmp5 = tl.load(in_ptr0 + (x0 + 4 * x1), tmp4 & xmask, other=0.0)
    tmp6 = tmp0 >= tmp3
    tl.full([1], 8, tl.int64)
    tmp9 = tl.load(in_ptr1 + (x0 + 4 * (-4 + x1)), tmp6 & xmask, other=0.0)
    tmp10 = tl.where(tmp4, tmp5, tmp9)
    tmp12 = libdevice.sqrt(tmp11)
    tmp13 = 1e-12
    tmp14 = triton_helpers.maximum(tmp12, tmp13)
    tmp15 = tmp10 / tmp14
    tl.store(out_ptr0 + x2, tmp15, xmask)


@triton.jit
def triton_poi_fused_index_put_lift_fresh_2(out_ptr0, xnumel, XBLOCK: tl.
    constexpr):
    xnumel = 8
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = -1000000000.0
    tl.store(out_ptr0 + 9 * x0, tmp0, xmask)


@triton.jit
def triton_per_fused__log_softmax_3(in_ptr0, out_ptr0, out_ptr1, xnumel,
    rnumel, XBLOCK: tl.constexpr):
    xnumel = 8
    RBLOCK: tl.constexpr = 8
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    rindex = tl.arange(0, RBLOCK)[None, :]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    r1 = rindex
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (r1 + 8 * x0), xmask, other=0.0)
    tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
    tmp3 = tl.where(xmask, tmp1, float('-inf'))
    tmp4 = triton_helpers.max2(tmp3, 1)[:, None]
    tmp5 = tmp0 - tmp4
    tmp6 = tl_math.exp(tmp5)
    tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
    tmp9 = tl.where(xmask, tmp7, 0)
    tmp10 = tl.sum(tmp9, 1)[:, None]
    tl.store(out_ptr0 + x0, tmp4, xmask)
    tl.store(out_ptr1 + x0, tmp10, xmask)


@triton.jit
def triton_per_fused__log_softmax_div_index_neg_sum_4(in_out_ptr0, in_ptr0,
    in_ptr1, in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
    RBLOCK: tl.constexpr = 8
    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 + (8 * r0 + (4 + r0) % 8), None, eviction_policy
        ='evict_last')
    tmp1 = tl.load(in_ptr1 + r0, None)
    tmp3 = tl.load(in_ptr2 + r0, None)
    tmp2 = tmp0 - tmp1
    tmp4 = tl_math.log(tmp3)
    tmp5 = tmp2 - tmp4
    tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
    tmp8 = tl.sum(tmp6, 1)[:, None]
    tmp9 = -tmp8
    tmp10 = 0.125
    tmp11 = tmp9 * tmp10
    tmp12 = 1.0
    tmp13 = tmp11 * tmp12
    tmp14 = tmp13 * tmp12
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp14, 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((8, 1), (1, 8), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_cat_linalg_vector_norm_0[grid(8)](arg0_1, arg1_1,
            buf0, 8, XBLOCK=8, num_warps=1, num_stages=1)
        buf1 = empty_strided_cuda((8, 4), (4, 1), torch.float32)
        triton_poi_fused_cat_div_1[grid(32)](arg0_1, arg1_1, buf0, buf1, 32,
            XBLOCK=32, num_warps=1, num_stages=1)
        del arg0_1
        del arg1_1
        buf2 = empty_strided_cuda((8, 8), (8, 1), torch.float32)
        extern_kernels.mm(buf1, reinterpret_tensor(buf1, (4, 8), (1, 4), 0),
            out=buf2)
        del buf1
        triton_poi_fused_index_put_lift_fresh_2[grid(8)](buf2, 8, XBLOCK=8,
            num_warps=1, num_stages=1)
        buf4 = buf0
        del buf0
        buf5 = empty_strided_cuda((8, 1), (1, 8), torch.float32)
        triton_per_fused__log_softmax_3[grid(8)](buf2, buf4, buf5, 8, 8,
            XBLOCK=1, num_warps=2, num_stages=1)
        buf6 = empty_strided_cuda((), (), torch.float32)
        buf7 = buf6
        del buf6
        triton_per_fused__log_softmax_div_index_neg_sum_4[grid(1)](buf7,
            buf2, buf4, buf5, 1, 8, XBLOCK=1, num_warps=2, num_stages=1)
        del buf2
        del buf4
        del buf5
    return buf7,


class NTXentNew(nn.Module):
    """
    Contrastive loss with distributed data parallel support
    code: https://github.com/AndrewAtanov/simclr-pytorch/blob/master/models/losses.py
    """
    LARGE_NUMBER = 1000000000.0

    def __init__(self, tau=1.0, gpu=None, multiplier=2, distributed=False):
        super().__init__()
        self.tau = tau
        self.multiplier = multiplier
        self.distributed = distributed
        self.norm = 1.0

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