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.triton_helpers import 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


@triton.jit
def triton_poi_fused_abs_exp_mean_neg_sub_0(in_ptr0, out_ptr0, xnumel,
    XBLOCK: tl.constexpr):
    xnumel = 48
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 3
    x1 = xindex // 3 % 4
    x2 = xindex // 12
    x3 = xindex
    tmp0 = tl.load(in_ptr0 + (x0 + 4 * x1 + 64 * x2), xmask)
    tmp1 = tl.load(in_ptr0 + (1 + x0 + 4 * x1 + 64 * x2), xmask)
    tmp4 = tl.load(in_ptr0 + (16 + x0 + 4 * x1 + 64 * x2), xmask)
    tmp5 = tl.load(in_ptr0 + (17 + x0 + 4 * x1 + 64 * x2), xmask)
    tmp9 = tl.load(in_ptr0 + (32 + x0 + 4 * x1 + 64 * x2), xmask)
    tmp10 = tl.load(in_ptr0 + (33 + x0 + 4 * x1 + 64 * x2), xmask)
    tmp14 = tl.load(in_ptr0 + (48 + x0 + 4 * x1 + 64 * x2), xmask)
    tmp15 = tl.load(in_ptr0 + (49 + x0 + 4 * x1 + 64 * x2), xmask)
    tmp2 = tmp0 - tmp1
    tmp3 = tl_math.abs(tmp2)
    tmp6 = tmp4 - tmp5
    tmp7 = tl_math.abs(tmp6)
    tmp8 = tmp3 + tmp7
    tmp11 = tmp9 - tmp10
    tmp12 = tl_math.abs(tmp11)
    tmp13 = tmp8 + tmp12
    tmp16 = tmp14 - tmp15
    tmp17 = tl_math.abs(tmp16)
    tmp18 = tmp13 + tmp17
    tmp19 = 4.0
    tmp20 = tmp18 / tmp19
    tmp21 = -tmp20
    tmp22 = tl_math.exp(tmp21)
    tl.store(out_ptr0 + x3, tmp22, xmask)


@triton.jit
def triton_poi_fused_abs_exp_mean_neg_sub_1(in_ptr0, out_ptr0, xnumel,
    XBLOCK: tl.constexpr):
    xnumel = 48
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 12
    x1 = xindex // 12
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
    tmp1 = tl.load(in_ptr0 + (4 + x0 + 64 * x1), xmask)
    tmp4 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
    tmp5 = tl.load(in_ptr0 + (20 + x0 + 64 * x1), xmask)
    tmp9 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
    tmp10 = tl.load(in_ptr0 + (36 + x0 + 64 * x1), xmask)
    tmp14 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
    tmp15 = tl.load(in_ptr0 + (52 + x0 + 64 * x1), xmask)
    tmp2 = tmp0 - tmp1
    tmp3 = tl_math.abs(tmp2)
    tmp6 = tmp4 - tmp5
    tmp7 = tl_math.abs(tmp6)
    tmp8 = tmp3 + tmp7
    tmp11 = tmp9 - tmp10
    tmp12 = tl_math.abs(tmp11)
    tmp13 = tmp8 + tmp12
    tmp16 = tmp14 - tmp15
    tmp17 = tl_math.abs(tmp16)
    tmp18 = tmp13 + tmp17
    tmp19 = 4.0
    tmp20 = tmp18 / tmp19
    tmp21 = -tmp20
    tmp22 = tl_math.exp(tmp21)
    tl.store(out_ptr0 + x2, tmp22, xmask)


@triton.jit
def triton_per_fused_abs_add_exp_mean_mul_neg_sub_2(in_out_ptr0, in_ptr0,
    in_ptr1, in_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
    rnumel = 192
    RBLOCK: tl.constexpr = 256
    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, :]
    rmask = rindex < rnumel
    r0 = rindex % 3
    r5 = rindex // 3
    r3 = rindex // 48
    r4 = rindex % 12
    r6 = rindex // 12
    tmp0 = tl.load(in_ptr0 + (r0 + 4 * r5), rmask, other=0.0)
    tmp1 = tl.load(in_ptr0 + (1 + r0 + 4 * r5), rmask, other=0.0)
    tmp3 = tl.load(in_ptr1 + (r4 + 12 * r3), rmask, eviction_policy=
        'evict_last', other=0.0)
    tmp10 = tl.load(in_ptr0 + (r4 + 16 * r6), rmask, other=0.0)
    tmp11 = tl.load(in_ptr0 + (4 + r4 + 16 * r6), rmask, other=0.0)
    tmp13 = tl.load(in_ptr2 + (r4 + 12 * r3), rmask, eviction_policy=
        'evict_last', other=0.0)
    tmp2 = tmp0 - tmp1
    tmp4 = tmp2 * tmp3
    tmp5 = tl_math.abs(tmp4)
    tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
    tmp8 = tl.where(rmask, tmp6, 0)
    tmp9 = tl.sum(tmp8, 1)[:, None]
    tmp12 = tmp10 - tmp11
    tmp14 = tmp12 * tmp13
    tmp15 = tl_math.abs(tmp14)
    tmp16 = tl.broadcast_to(tmp15, [XBLOCK, RBLOCK])
    tmp18 = tl.where(rmask, tmp16, 0)
    tmp19 = tl.sum(tmp18, 1)[:, None]
    tmp20 = 192.0
    tmp21 = tmp9 / tmp20
    tmp22 = tmp19 / tmp20
    tmp23 = tmp21 + tmp22
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp23, 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((4, 1, 4, 3), (12, 48, 3, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_abs_exp_mean_neg_sub_0[grid(48)](arg1_1, buf0, 48,
            XBLOCK=64, num_warps=1, num_stages=1)
        buf2 = empty_strided_cuda((4, 1, 3, 4), (12, 48, 4, 1), torch.float32)
        triton_poi_fused_abs_exp_mean_neg_sub_1[grid(48)](arg1_1, buf2, 48,
            XBLOCK=64, num_warps=1, num_stages=1)
        del arg1_1
        buf1 = empty_strided_cuda((), (), torch.float32)
        buf4 = buf1
        del buf1
        triton_per_fused_abs_add_exp_mean_mul_neg_sub_2[grid(1)](buf4,
            arg0_1, buf0, buf2, 1, 192, XBLOCK=1, num_warps=2, num_stages=1)
        del arg0_1
        del buf0
        del buf2
    return buf4,


def _gradient_x(img: 'torch.Tensor') ->torch.Tensor:
    assert len(img.shape) == 4, img.shape
    return img[:, :, :, :-1] - img[:, :, :, 1:]


def _gradient_y(img: 'torch.Tensor') ->torch.Tensor:
    assert len(img.shape) == 4, img.shape
    return img[:, :, :-1, :] - img[:, :, 1:, :]


def inverse_depth_smoothness_loss(idepth: 'torch.Tensor', image: 'torch.Tensor'
    ) ->torch.Tensor:
    """Computes image-aware inverse depth smoothness loss.

    See :class:`~kornia.losses.InvDepthSmoothnessLoss` for details.
    """
    if not torch.is_tensor(idepth):
        raise TypeError('Input idepth type is not a torch.Tensor. Got {}'.
            format(type(idepth)))
    if not torch.is_tensor(image):
        raise TypeError('Input image type is not a torch.Tensor. Got {}'.
            format(type(image)))
    if not len(idepth.shape) == 4:
        raise ValueError('Invalid idepth shape, we expect BxCxHxW. Got: {}'
            .format(idepth.shape))
    if not len(image.shape) == 4:
        raise ValueError('Invalid image shape, we expect BxCxHxW. Got: {}'.
            format(image.shape))
    if not idepth.shape[-2:] == image.shape[-2:]:
        raise ValueError('idepth and image shapes must be the same. Got: {}'
            .format(idepth.shape))
    if not idepth.device == image.device:
        raise ValueError('idepth and image must be in the same device. Got: {}'
            .format(idepth.device))
    if not idepth.dtype == image.dtype:
        raise ValueError('idepth and image must be in the same dtype. Got: {}'
            .format(idepth.dtype))
    idepth_dx: 'torch.Tensor' = _gradient_x(idepth)
    idepth_dy: 'torch.Tensor' = _gradient_y(idepth)
    image_dx: 'torch.Tensor' = _gradient_x(image)
    image_dy: 'torch.Tensor' = _gradient_y(image)
    weights_x: 'torch.Tensor' = torch.exp(-torch.mean(torch.abs(image_dx),
        dim=1, keepdim=True))
    weights_y: 'torch.Tensor' = torch.exp(-torch.mean(torch.abs(image_dy),
        dim=1, keepdim=True))
    smoothness_x: 'torch.Tensor' = torch.abs(idepth_dx * weights_x)
    smoothness_y: 'torch.Tensor' = torch.abs(idepth_dy * weights_y)
    return torch.mean(smoothness_x) + torch.mean(smoothness_y)


class InverseDepthSmoothnessLossNew(nn.Module):
    """Criterion that computes image-aware inverse depth smoothness loss.

    .. math::

        \\text{loss} = \\left | \\partial_x d_{ij} \\right | e^{-\\left \\|
        \\partial_x I_{ij} \\right \\|} + \\left |
        \\partial_y d_{ij} \\right | e^{-\\left \\| \\partial_y I_{ij} \\right \\|}


    Shape:
        - Inverse Depth: :math:`(N, 1, H, W)`
        - Image: :math:`(N, 3, H, W)`
        - Output: scalar

    Examples::

        >>> idepth = torch.rand(1, 1, 4, 5)
        >>> image = torch.rand(1, 3, 4, 5)
        >>> smooth = kornia.losses.DepthSmoothnessLoss()
        >>> loss = smooth(idepth, image)
    """

    def __init__(self) ->None:
        super(InverseDepthSmoothnessLossNew, self).__init__()

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