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 math as tl_math
from typing import Optional
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
import torch.utils.data.distributed
import torch.optim
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__log_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)
    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 = triton_helpers.maximum(tmp1, tmp2)
    tmp5 = triton_helpers.maximum(tmp3, tmp4)
    tmp7 = triton_helpers.maximum(tmp5, tmp6)
    tmp8 = tmp0 - tmp7
    tl.store(out_ptr0 + x3, tmp8, 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 = triton_helpers.maximum(tmp1, tmp2)
    tmp5 = triton_helpers.maximum(tmp3, tmp4)
    tmp7 = triton_helpers.maximum(tmp5, tmp6)
    tmp8 = tmp0 - tmp7
    tmp9 = tl_math.exp(tmp8)
    tl.store(out_ptr0 + x3, tmp9, xmask)


@triton.jit
def triton_per_fused_add_max_mul_nll_loss2d_forward_2(in_out_ptr0, in_ptr0,
    in_ptr1, in_ptr2, in_ptr3, 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)
    tmp1 = tl.load(in_ptr0 + (16 + r0 + 64 * r1), None)
    tmp17 = tl.load(in_ptr0 + (32 + r0 + 64 * r1), None)
    tmp32 = tl.load(in_ptr0 + (48 + r0 + 64 * r1), None)
    tmp56 = tl.load(in_ptr1 + (r0 + 64 * r1), None)
    tmp58 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None)
    tmp61 = tl.load(in_ptr1 + (32 + r0 + 64 * r1), None)
    tmp64 = tl.load(in_ptr1 + (48 + r0 + 64 * r1), None)
    tmp79 = tl.load(in_ptr2 + (r0 + 64 * r1), None)
    tmp80 = tl.load(in_ptr2 + (16 + r0 + 64 * r1), None)
    tmp93 = tl.load(in_ptr2 + (32 + r0 + 64 * r1), None)
    tmp107 = tl.load(in_ptr2 + (48 + r0 + 64 * r1), None)
    tmp128 = tl.load(in_ptr3 + (r0 + 64 * r1), None)
    tmp129 = tl.load(in_ptr3 + (16 + r0 + 64 * r1), None)
    tmp131 = tl.load(in_ptr3 + (32 + r0 + 64 * r1), None)
    tmp133 = tl.load(in_ptr3 + (48 + r0 + 64 * r1), None)
    tmp2 = tmp0 > tmp1
    tmp3 = tmp0 == tmp1
    tmp4 = tmp0 != tmp0
    tmp5 = tmp1 != tmp1
    tmp6 = tmp4 > tmp5
    tmp7 = tmp2 | tmp6
    tmp8 = tmp4 & tmp5
    tmp9 = tmp3 | tmp8
    tmp10 = tl.full([1, 1], 0, tl.int64)
    tmp11 = tl.full([1, 1], 1, tl.int64)
    tmp12 = tmp10 < tmp11
    tmp13 = tmp9 & tmp12
    tmp14 = tmp7 | tmp13
    tmp15 = tl.where(tmp14, tmp0, tmp1)
    tmp16 = tl.where(tmp14, tmp10, tmp11)
    tmp18 = tmp15 > tmp17
    tmp19 = tmp15 == tmp17
    tmp20 = tmp15 != tmp15
    tmp21 = tmp17 != tmp17
    tmp22 = tmp20 > tmp21
    tmp23 = tmp18 | tmp22
    tmp24 = tmp20 & tmp21
    tmp25 = tmp19 | tmp24
    tmp26 = tl.full([1, 1], 2, tl.int64)
    tmp27 = tmp16 < tmp26
    tmp28 = tmp25 & tmp27
    tmp29 = tmp23 | tmp28
    tmp30 = tl.where(tmp29, tmp15, tmp17)
    tmp31 = tl.where(tmp29, tmp16, tmp26)
    tmp33 = tmp30 > tmp32
    tmp34 = tmp30 == tmp32
    tmp35 = tmp30 != tmp30
    tmp36 = tmp32 != tmp32
    tmp37 = tmp35 > tmp36
    tmp38 = tmp33 | tmp37
    tmp39 = tmp35 & tmp36
    tmp40 = tmp34 | tmp39
    tmp41 = tl.full([1, 1], 3, tl.int64)
    tmp42 = tmp31 < tmp41
    tmp43 = tmp40 & tmp42
    tmp44 = tmp38 | tmp43
    tl.where(tmp44, tmp30, tmp32)
    tmp46 = tl.where(tmp44, tmp31, tmp41)
    tmp47 = tl.full([1, 1], -100, tl.int64)
    tmp48 = tmp46 != tmp47
    tmp49 = tl.where(tmp48, tmp46, tmp10)
    tmp50 = tl.full([XBLOCK, RBLOCK], 4, tl.int32)
    tmp51 = tmp49 + tmp50
    tmp52 = tmp49 < 0
    tmp53 = tl.where(tmp52, tmp51, tmp49)
    tl.device_assert((0 <= tmp53) & (tmp53 < 4),
        'index out of bounds: 0 <= tmp53 < 4')
    tmp55 = tl.load(in_ptr1 + (r0 + 16 * tmp53 + 64 * r1), None)
    tmp57 = tl_math.exp(tmp56)
    tmp59 = tl_math.exp(tmp58)
    tmp60 = tmp57 + tmp59
    tmp62 = tl_math.exp(tmp61)
    tmp63 = tmp60 + tmp62
    tmp65 = tl_math.exp(tmp64)
    tmp66 = tmp63 + tmp65
    tmp67 = tl_math.log(tmp66)
    tmp68 = tmp55 - tmp67
    tmp69 = -tmp68
    tmp70 = 0.0
    tmp71 = tl.where(tmp48, tmp69, tmp70)
    tmp72 = tl.broadcast_to(tmp71, [XBLOCK, RBLOCK])
    tmp74 = tl.sum(tmp72, 1)[:, None]
    tmp75 = tmp48.to(tl.int64)
    tmp76 = tl.broadcast_to(tmp75, [XBLOCK, RBLOCK])
    tmp78 = tl.sum(tmp76, 1)[:, None]
    tmp81 = tmp79 > tmp80
    tmp82 = tmp79 == tmp80
    tmp83 = tmp79 != tmp79
    tmp84 = tmp80 != tmp80
    tmp85 = tmp83 > tmp84
    tmp86 = tmp81 | tmp85
    tmp87 = tmp83 & tmp84
    tmp88 = tmp82 | tmp87
    tmp89 = tmp88 & tmp12
    tmp90 = tmp86 | tmp89
    tmp91 = tl.where(tmp90, tmp79, tmp80)
    tmp92 = tl.where(tmp90, tmp10, tmp11)
    tmp94 = tmp91 > tmp93
    tmp95 = tmp91 == tmp93
    tmp96 = tmp91 != tmp91
    tmp97 = tmp93 != tmp93
    tmp98 = tmp96 > tmp97
    tmp99 = tmp94 | tmp98
    tmp100 = tmp96 & tmp97
    tmp101 = tmp95 | tmp100
    tmp102 = tmp92 < tmp26
    tmp103 = tmp101 & tmp102
    tmp104 = tmp99 | tmp103
    tmp105 = tl.where(tmp104, tmp91, tmp93)
    tmp106 = tl.where(tmp104, tmp92, tmp26)
    tmp108 = tmp105 > tmp107
    tmp109 = tmp105 == tmp107
    tmp110 = tmp105 != tmp105
    tmp111 = tmp107 != tmp107
    tmp112 = tmp110 > tmp111
    tmp113 = tmp108 | tmp112
    tmp114 = tmp110 & tmp111
    tmp115 = tmp109 | tmp114
    tmp116 = tmp106 < tmp41
    tmp117 = tmp115 & tmp116
    tmp118 = tmp113 | tmp117
    tl.where(tmp118, tmp105, tmp107)
    tmp120 = tl.where(tmp118, tmp106, tmp41)
    tmp121 = tmp120 != tmp47
    tmp122 = tl.where(tmp121, tmp120, tmp10)
    tmp123 = tmp122 + tmp50
    tmp124 = tmp122 < 0
    tmp125 = tl.where(tmp124, tmp123, tmp122)
    tl.device_assert((0 <= tmp125) & (tmp125 < 4),
        'index out of bounds: 0 <= tmp125 < 4')
    tmp127 = tl.load(in_ptr3 + (r0 + 16 * tmp125 + 64 * r1), None)
    tmp130 = tmp128 + tmp129
    tmp132 = tmp130 + tmp131
    tmp134 = tmp132 + tmp133
    tmp135 = tmp127 / tmp134
    tmp136 = 1.0
    tmp137 = tmp136 - tmp135
    tmp138 = 1e-06
    tmp139 = tmp137 + tmp138
    tmp140 = triton_helpers.minimum(tmp139, tmp136)
    tmp141 = tl_math.log(tmp140)
    tmp142 = -tmp141
    tmp143 = tl.where(tmp121, tmp142, tmp70)
    tmp144 = tl.broadcast_to(tmp143, [XBLOCK, RBLOCK])
    tmp146 = tl.sum(tmp144, 1)[:, None]
    tmp147 = tmp121.to(tl.int64)
    tmp148 = tl.broadcast_to(tmp147, [XBLOCK, RBLOCK])
    tmp150 = tl.sum(tmp148, 1)[:, None]
    tmp151 = tmp78.to(tl.float32)
    tmp152 = tmp74 / tmp151
    tmp153 = 4.0
    tmp154 = tmp152 * tmp153
    tmp155 = tmp150.to(tl.float32)
    tmp156 = tmp146 / tmp155
    tmp157 = tmp154 + tmp156
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp157, None)


def call(args):
    arg0_1, arg1_1, arg2_1, arg3_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))
    assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(arg3_1, (4, 4, 4, 4), (64, 16, 4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused__log_softmax_0[grid(256)](arg2_1, buf2, 256,
            XBLOCK=256, num_warps=4, num_stages=1)
        del arg2_1
        buf5 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        triton_poi_fused__softmax_1[grid(256)](arg3_1, buf5, 256, XBLOCK=
            256, num_warps=4, num_stages=1)
        del arg3_1
        buf3 = empty_strided_cuda((), (), torch.float32)
        buf8 = buf3
        del buf3
        triton_per_fused_add_max_mul_nll_loss2d_forward_2[grid(1)](buf8,
            arg0_1, buf2, arg1_1, buf5, 1, 64, XBLOCK=1, num_warps=2,
            num_stages=1)
        del arg0_1
        del arg1_1
        del buf2
        del buf5
    return buf8,


def shift_log(x: 'torch.Tensor', offset: 'Optional[float]'=1e-06
    ) ->torch.Tensor:
    """
    First shift, then calculate log, which can be described as:

    .. math::
        y = \\max(\\log(x+\\text{offset}), 0)

    Used to avoid the gradient explosion problem in log(x) function when x=0.

    Parameters:
        - **x**: input tensor
        - **offset**: offset size. Default: 1e-6

    .. note::
        Input tensor falls in [0., 1.] and the output tensor falls in [-log(offset), 0]
    """
    return torch.log(torch.clamp(x + offset, max=1.0))


class MarginDisparityDiscrepancyNew(nn.Module):
    """The margin disparity discrepancy (MDD) is proposed to measure the distribution discrepancy in domain adaptation.

    The :math:`y^s` and :math:`y^t` are logits output by the main classifier on the source and target domain respectively.
    The :math:`y_{adv}^s` and :math:`y_{adv}^t` are logits output by the adversarial classifier.
    They are expected to contain raw, unnormalized scores for each class.

    The definition can be described as:

    .. math::
        \\mathcal{D}_{\\gamma}(\\hat{\\mathcal{S}}, \\hat{\\mathcal{T}}) =
        \\gamma \\mathbb{E}_{y^s, y_{adv}^s \\sim\\hat{\\mathcal{S}}} \\log\\left(\\frac{\\exp(y_{adv}^s[h_{y^s}])}{\\sum_j \\exp(y_{adv}^s[j])}\\right) +
        \\mathbb{E}_{y^t, y_{adv}^t \\sim\\hat{\\mathcal{T}}} \\log\\left(1-\\frac{\\exp(y_{adv}^t[h_{y^t}])}{\\sum_j \\exp(y_{adv}^t[j])}\\right),

    where :math:`\\gamma` is a margin hyper-parameter and :math:`h_y` refers to the predicted label when the logits output is :math:`y`.
    You can see more details in `Bridging Theory and Algorithm for Domain Adaptation <https://arxiv.org/abs/1904.05801>`_.

    Parameters:
        - **margin** (float): margin :math:`\\gamma`. Default: 4
        - **reduction** (string, optional): Specifies the reduction to apply to the output:
          ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
          ``'mean'``: the sum of the output will be divided by the number of
          elements in the output, ``'sum'``: the output will be summed. Default: ``'mean'``

    Inputs: y_s, y_s_adv, y_t, y_t_adv
        - **y_s**: logits output :math:`y^s` by the main classifier on the source domain
        - **y_s_adv**: logits output :math:`y^s` by the adversarial classifier on the source domain
        - **y_t**: logits output :math:`y^t` by the main classifier on the target domain
        - **y_t_adv**: logits output :math:`y_{adv}^t` by the adversarial classifier on the target domain

    Shape:
        - Inputs: :math:`(minibatch, C)` where C = number of classes, or :math:`(minibatch, C, d_1, d_2, ..., d_K)`
          with :math:`K \\geq 1` in the case of `K`-dimensional loss.
        - Output: scalar. If :attr:`reduction` is ``'none'``, then the same size as the target: :math:`(minibatch)`, or
          :math:`(minibatch, d_1, d_2, ..., d_K)` with :math:`K \\geq 1` in the case of K-dimensional loss.

    Examples::
        >>> num_classes = 2
        >>> batch_size = 10
        >>> loss = MarginDisparityDiscrepancy(margin=4.)
        >>> # logits output from source domain and target domain
        >>> y_s, y_t = torch.randn(batch_size, num_classes), torch.randn(batch_size, num_classes)
        >>> # adversarial logits output from source domain and target domain
        >>> y_s_adv, y_t_adv = torch.randn(batch_size, num_classes), torch.randn(batch_size, num_classes)
        >>> output = loss(y_s, y_s_adv, y_t, y_t_adv)
    """

    def __init__(self, margin: 'Optional[int]'=4, reduction:
        'Optional[str]'='mean'):
        super(MarginDisparityDiscrepancyNew, self).__init__()
        self.margin = margin
        self.reduction = reduction

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


Measured latency_ms: 0.015741