import torch
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


@triton.jit
def triton_per_fused_add_div_lift_fresh_maximum_mul_neg_pow_sqrt_sum_0(
    in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
    RBLOCK: tl.constexpr = 64
    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.load(in_ptr1 + r0, None)
    tmp10 = tl.load(in_ptr0 + (64 + r0), None)
    tmp11 = tl.load(in_ptr1 + (64 + r0), None)
    tmp20 = tl.load(in_ptr0 + (128 + r0), None)
    tmp21 = tl.load(in_ptr1 + (128 + r0), None)
    tmp30 = tl.load(in_ptr0 + (192 + r0), None)
    tmp31 = tl.load(in_ptr1 + (192 + r0), None)
    tmp2 = tmp0 * tmp1
    tmp3 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
    tmp5 = tl.sum(tmp3, 1)[:, None]
    tmp6 = tmp1 * tmp1
    tmp7 = tl.broadcast_to(tmp6, [XBLOCK, RBLOCK])
    tmp9 = tl.sum(tmp7, 1)[:, None]
    tmp12 = tmp10 * tmp11
    tmp13 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
    tmp15 = tl.sum(tmp13, 1)[:, None]
    tmp16 = tmp11 * tmp11
    tmp17 = tl.broadcast_to(tmp16, [XBLOCK, RBLOCK])
    tmp19 = tl.sum(tmp17, 1)[:, None]
    tmp22 = tmp20 * tmp21
    tmp23 = tl.broadcast_to(tmp22, [XBLOCK, RBLOCK])
    tmp25 = tl.sum(tmp23, 1)[:, None]
    tmp26 = tmp21 * tmp21
    tmp27 = tl.broadcast_to(tmp26, [XBLOCK, RBLOCK])
    tmp29 = tl.sum(tmp27, 1)[:, None]
    tmp32 = tmp30 * tmp31
    tmp33 = tl.broadcast_to(tmp32, [XBLOCK, RBLOCK])
    tmp35 = tl.sum(tmp33, 1)[:, None]
    tmp36 = tmp31 * tmp31
    tmp37 = tl.broadcast_to(tmp36, [XBLOCK, RBLOCK])
    tmp39 = tl.sum(tmp37, 1)[:, None]
    tmp40 = libdevice.sqrt(tmp9)
    tmp41 = 1e-06
    tmp42 = tmp40 + tmp41
    tmp43 = tmp5 / tmp42
    tmp44 = 0.10000000149011612
    tmp45 = triton_helpers.maximum(tmp44, tmp43)
    tmp46 = tmp45 * tmp5
    tmp47 = -tmp46
    tmp48 = 0.0
    tmp49 = tmp47 + tmp48
    tmp50 = libdevice.sqrt(tmp19)
    tmp51 = tmp50 + tmp41
    tmp52 = tmp15 / tmp51
    tmp53 = triton_helpers.maximum(tmp44, tmp52)
    tmp54 = tmp53 * tmp15
    tmp55 = -tmp54
    tmp56 = tmp49 + tmp55
    tmp57 = libdevice.sqrt(tmp29)
    tmp58 = tmp57 + tmp41
    tmp59 = tmp25 / tmp58
    tmp60 = triton_helpers.maximum(tmp44, tmp59)
    tmp61 = tmp60 * tmp25
    tmp62 = -tmp61
    tmp63 = tmp56 + tmp62
    tmp64 = libdevice.sqrt(tmp39)
    tmp65 = tmp64 + tmp41
    tmp66 = tmp35 / tmp65
    tmp67 = triton_helpers.maximum(tmp44, tmp66)
    tmp68 = tmp67 * tmp35
    tmp69 = -tmp68
    tmp70 = tmp63 + tmp69
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp70, None)


def call(args):
    arg0_1, arg1_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 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((), (), torch.float32)
        buf8 = buf0
        del buf0
        get_raw_stream(0)
        triton_per_fused_add_div_lift_fresh_maximum_mul_neg_pow_sqrt_sum_0[grid
            (1)](buf8, arg0_1, arg1_1, 1, 64, XBLOCK=1, num_warps=2,
            num_stages=1)
        del arg0_1
        del arg1_1
    return buf8,


def resize_4d_tensor_by_size(x, height, width):
    res = F.interpolate(x, size=(height, width), mode='bilinear')
    return res


class CaricatureLossNew(nn.Module):

    def __init__(self, power=1.0):
        super().__init__()
        self.power = power

    def cosine_dissimilarity(self, x, y, eps=1e-06):
        """
        tried my best to replicate: 
            https://github.com/tensorflow/lucid/blob/6dcc927e4ff4e7ef4d9c54d27b0352849dadd1bb/lucid/recipes/caricature.py#L21
            
        if I missed something out, please get in touch with me on Distill slack: @Mayukh 

        or email me: 
            mayukhmainak2000@gmail.com
        or find me on github: 
            github.com/mayukhdeb
        """
        if x.shape != y.shape:
            """
            if their shapes are not equal (likely due to using static caricatures), then resize the target accordingly
            """
            y = resize_4d_tensor_by_size(y.unsqueeze(0), height=x.shape[-2],
                width=x.shape[-1]).squeeze(0)
        y = y.detach()
        numerator = (x * y.detach()).sum()
        denominator = torch.sqrt((y ** 2).sum()) + eps
        cossim = numerator / denominator
        cossim = torch.maximum(torch.tensor(0.1), cossim)
        loss = -(cossim * numerator ** self.power)
        return loss

    def loss(self, x, y):
        loss = self.cosine_dissimilarity(x, y)
        return loss

    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.013869