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, math as tl_math
import functools
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_poi_fused__softmax_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
    ):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex
    x0 = xindex % 16
    x2 = xindex // 64
    tmp0 = tl.load(in_ptr0 + x3, xmask)
    tmp3 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp5 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp8 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp11 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp1 = 1.0
    tmp2 = tmp0 * tmp1
    tmp4 = tmp3 * tmp1
    tmp6 = tmp5 * tmp1
    tmp7 = triton_helpers.maximum(tmp4, tmp6)
    tmp9 = tmp8 * tmp1
    tmp10 = triton_helpers.maximum(tmp7, tmp9)
    tmp12 = tmp11 * tmp1
    tmp13 = triton_helpers.maximum(tmp10, tmp12)
    tmp14 = tmp2 - tmp13
    tmp15 = 0.1
    tmp16 = tmp14 * tmp15
    tmp17 = tl_math.exp(tmp16)
    tl.store(out_ptr0 + x3, tmp17, xmask)


@triton.jit
def triton_poi_fused__softmax_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
    ):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex
    x0 = xindex % 16
    x2 = xindex // 64
    tmp0 = tl.load(in_ptr0 + x3, xmask)
    tmp1 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp2 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp4 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp6 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp3 = tmp1 + tmp2
    tmp5 = tmp3 + tmp4
    tmp7 = tmp5 + tmp6
    tmp8 = tmp0 / tmp7
    tl.store(out_ptr0 + x3, tmp8, xmask)


@triton.jit
def triton_poi_fused_2(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex
    x0 = xindex % 16
    x2 = xindex // 64
    tmp0 = tl.load(in_ptr0 + x3, xmask)
    tmp3 = tl.load(in_ptr0 + (x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp5 = tl.load(in_ptr0 + (16 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp8 = tl.load(in_ptr0 + (32 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp11 = tl.load(in_ptr0 + (48 + x0 + 64 * x2), xmask, eviction_policy=
        'evict_last')
    tmp1 = 1.0
    tmp2 = tmp0 * tmp1
    tmp4 = tmp3 * tmp1
    tmp6 = tmp5 * tmp1
    tmp7 = triton_helpers.maximum(tmp4, tmp6)
    tmp9 = tmp8 * tmp1
    tmp10 = triton_helpers.maximum(tmp7, tmp9)
    tmp12 = tmp11 * tmp1
    tmp13 = triton_helpers.maximum(tmp10, tmp12)
    tmp14 = tmp2 - tmp13
    tmp15 = 0.1
    tmp16 = tmp14 * tmp15
    tl.store(out_ptr0 + x3, tmp16, xmask)


@triton.jit
def triton_per_fused__log_softmax_mean_mul_sub_xlogy_3(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 % 16
    r1 = rindex // 16
    tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None)
    tmp9 = tl.load(in_ptr1 + (r0 + 64 * r1), None)
    tmp11 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None)
    tmp14 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None)
    tmp17 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None)
    tmp24 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None)
    tmp35 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None)
    tmp46 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None)
    tmp1 = libdevice.isnan(tmp0).to(tl.int1)
    tmp2 = 0.0
    tmp3 = tmp0 == tmp2
    tmp4 = tl_math.log(tmp0)
    tmp5 = tmp0 * tmp4
    tmp6 = tl.where(tmp3, tmp2, tmp5)
    tmp7 = float('nan')
    tmp8 = tl.where(tmp1, tmp7, tmp6)
    tmp10 = tl_math.exp(tmp9)
    tmp12 = tl_math.exp(tmp11)
    tmp13 = tmp10 + tmp12
    tmp15 = tl_math.exp(tmp14)
    tmp16 = tmp13 + tmp15
    tmp18 = tl_math.exp(tmp17)
    tmp19 = tmp16 + tmp18
    tmp20 = tl_math.log(tmp19)
    tmp21 = tmp9 - tmp20
    tmp22 = tmp0 * tmp21
    tmp23 = tmp8 - tmp22
    tmp25 = libdevice.isnan(tmp24).to(tl.int1)
    tmp26 = tmp24 == tmp2
    tmp27 = tl_math.log(tmp24)
    tmp28 = tmp24 * tmp27
    tmp29 = tl.where(tmp26, tmp2, tmp28)
    tmp30 = tl.where(tmp25, tmp7, tmp29)
    tmp31 = tmp11 - tmp20
    tmp32 = tmp24 * tmp31
    tmp33 = tmp30 - tmp32
    tmp34 = tmp23 + tmp33
    tmp36 = libdevice.isnan(tmp35).to(tl.int1)
    tmp37 = tmp35 == tmp2
    tmp38 = tl_math.log(tmp35)
    tmp39 = tmp35 * tmp38
    tmp40 = tl.where(tmp37, tmp2, tmp39)
    tmp41 = tl.where(tmp36, tmp7, tmp40)
    tmp42 = tmp14 - tmp20
    tmp43 = tmp35 * tmp42
    tmp44 = tmp41 - tmp43
    tmp45 = tmp34 + tmp44
    tmp47 = libdevice.isnan(tmp46).to(tl.int1)
    tmp48 = tmp46 == tmp2
    tmp49 = tl_math.log(tmp46)
    tmp50 = tmp46 * tmp49
    tmp51 = tl.where(tmp48, tmp2, tmp50)
    tmp52 = tl.where(tmp47, tmp7, tmp51)
    tmp53 = tmp17 - tmp20
    tmp54 = tmp46 * tmp53
    tmp55 = tmp52 - tmp54
    tmp56 = tmp45 + tmp55
    tmp57 = 4.0
    tmp58 = tmp56 / tmp57
    tmp59 = 100.0
    tmp60 = tmp58 * tmp59
    tmp61 = tl.broadcast_to(tmp60, [XBLOCK, RBLOCK])
    tmp63 = tl.sum(tmp61, 1)[:, None]
    tmp64 = 64.0
    tmp65 = tmp63 / tmp64
    tmp66 = 1.0
    tmp67 = tmp65 * tmp66
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp67, 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, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused__softmax_0[grid(256)](arg1_1, buf0, 256, XBLOCK=
            256, num_warps=4, num_stages=1)
        del arg1_1
        buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        triton_poi_fused__softmax_1[grid(256)](buf0, buf1, 256, XBLOCK=256,
            num_warps=4, num_stages=1)
        buf2 = buf0
        del buf0
        triton_poi_fused_2[grid(256)](arg0_1, buf2, 256, XBLOCK=256,
            num_warps=4, num_stages=1)
        del arg0_1
        buf4 = empty_strided_cuda((), (), torch.float32)
        buf5 = buf4
        del buf4
        triton_per_fused__log_softmax_mean_mul_sub_xlogy_3[grid(1)](buf5,
            buf1, buf2, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
        del buf1
        del buf2
    return buf5,


def reduce_loss(loss, reduction):
    """Reduce loss as specified.

    Args:
        loss (Tensor): Elementwise loss tensor.
        reduction (str): Options are "none", "mean" and "sum".

    Return:
        Tensor: Reduced loss tensor.
    """
    reduction_enum = F._Reduction.get_enum(reduction)
    if reduction_enum == 0:
        return loss
    elif reduction_enum == 1:
        return loss.mean()
    elif reduction_enum == 2:
        return loss.sum()


def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
    """Apply element-wise weight and reduce loss.

    Args:
        loss (Tensor): Element-wise loss.
        weight (Tensor): Element-wise weights.
        reduction (str): Same as built-in losses of PyTorch.
        avg_factor (float): Avarage factor when computing the mean of losses.

    Returns:
        Tensor: Processed loss values.
    """
    if weight is not None:
        loss = loss * weight
    if avg_factor is None:
        loss = reduce_loss(loss, reduction)
    elif reduction == 'mean':
        loss = loss.sum() / avg_factor
    elif reduction != 'none':
        raise ValueError('avg_factor can not be used with reduction="sum"')
    return loss


def weighted_loss(loss_func):
    """Create a weighted version of a given loss function.

    To use this decorator, the loss function must have the signature like
    ``loss_func(pred, target, **kwargs)``. The function only needs to compute
    element-wise loss without any reduction. This decorator will add weight
    and reduction arguments to the function. The decorated function will have
    the signature like ``loss_func(pred, target, weight=None, reduction='mean',
    avg_factor=None, **kwargs)``.

    :Example:

    >>> import torch
    >>> @weighted_loss
    >>> def l1_loss(pred, target):
    >>>     return (pred - target).abs()

    >>> pred = torch.Tensor([0, 2, 3])
    >>> target = torch.Tensor([1, 1, 1])
    >>> weight = torch.Tensor([1, 0, 1])

    >>> l1_loss(pred, target)
    tensor(1.3333)
    >>> l1_loss(pred, target, weight)
    tensor(1.)
    >>> l1_loss(pred, target, reduction='none')
    tensor([1., 1., 2.])
    >>> l1_loss(pred, target, weight, avg_factor=2)
    tensor(1.5000)
    """

    @functools.wraps(loss_func)
    def wrapper(pred, target, weight=None, reduction='mean', avg_factor=
        None, **kwargs):
        loss = loss_func(pred, target, **kwargs)
        loss = weight_reduce_loss(loss, weight, reduction, avg_factor)
        return loss
    return wrapper


@weighted_loss
def knowledge_distillation_kl_div_loss(pred, soft_label, T, detach_target=True
    ):
    """Loss function for knowledge distilling using KL divergence.
    Args:
        pred (Tensor): Predicted logits with shape (N, n + 1).
        soft_label (Tensor): Target logits with shape (N, N + 1).
        T (int): Temperature for distillation.
        detach_target (bool): Remove soft_label from automatic differentiation
    Returns:
        torch.Tensor: Loss tensor with shape (N,).
    """
    assert pred.size() == soft_label.size()
    target = F.softmax(soft_label / T, dim=1)
    if detach_target:
        target = target.detach()
    kd_loss = F.kl_div(F.log_softmax(pred / T, dim=1), target, reduction='none'
        ).mean(1) * (T * T)
    return kd_loss


class KnowledgeDistillationKLDivLossNew(nn.Module):
    """Loss function for knowledge distilling using KL divergence.
    Args:
        reduction (str): Options are `'none'`, `'mean'` and `'sum'`.
        loss_weight (float): Loss weight of current loss.
        T (int): Temperature for distillation.
    """

    def __init__(self, reduction='mean', loss_weight=1.0, T=10):
        super(KnowledgeDistillationKLDivLossNew, self).__init__()
        assert T >= 1
        self.reduction = reduction
        self.loss_weight = loss_weight
        self.T = T

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