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_per_fused_abs_add_div_mean_sub_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)
    tmp7 = tl.load(in_ptr0 + (64 + r0), None)
    tmp8 = tl.load(in_ptr1 + (64 + r0), None)
    tmp14 = tl.load(in_ptr0 + (128 + r0), None)
    tmp15 = tl.load(in_ptr1 + (128 + r0), None)
    tmp21 = tl.load(in_ptr0 + (192 + r0), None)
    tmp22 = tl.load(in_ptr1 + (192 + r0), None)
    tmp2 = tmp0 - tmp1
    tmp3 = tl_math.abs(tmp2)
    tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
    tmp6 = tl.sum(tmp4, 1)[:, None]
    tmp9 = tmp7 - tmp8
    tmp10 = tl_math.abs(tmp9)
    tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK])
    tmp13 = tl.sum(tmp11, 1)[:, None]
    tmp16 = tmp14 - tmp15
    tmp17 = tl_math.abs(tmp16)
    tmp18 = tl.broadcast_to(tmp17, [XBLOCK, RBLOCK])
    tmp20 = tl.sum(tmp18, 1)[:, None]
    tmp23 = tmp21 - tmp22
    tmp24 = tl_math.abs(tmp23)
    tmp25 = tl.broadcast_to(tmp24, [XBLOCK, RBLOCK])
    tmp27 = tl.sum(tmp25, 1)[:, None]
    tmp28 = 64.0
    tmp29 = tmp6 / tmp28
    tmp30 = 0.0
    tmp31 = tmp29 + tmp30
    tmp32 = tmp13 / tmp28
    tmp33 = tmp31 + tmp32
    tmp34 = tmp20 / tmp28
    tmp35 = tmp33 + tmp34
    tmp36 = tmp27 / tmp28
    tmp37 = tmp35 + tmp36
    tmp38 = 0.25
    tmp39 = tmp37 * tmp38
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp39, 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)
        buf4 = buf0
        del buf0
        get_raw_stream(0)
        triton_per_fused_abs_add_div_mean_sub_0[grid(1)](buf4, arg1_1,
            arg0_1, 1, 64, XBLOCK=1, num_warps=2, num_stages=1)
        del arg0_1
        del arg1_1
    return buf4,


class LossW2VNew(nn.Module):
    """Triplet loss with hard positive/negative mining.

    Reference:
    Hermans et al. In Defense of the Triplet Loss for Person Re-Identification. arXiv:1703.07737.
    Code imported from https://github.com/Cysu/open-reid/blob/master/reid/loss/triplet.py.

    Args:
    - margin (float): margin for triplet.
    """

    def cosine_distance(self, x1, x2, eps=1e-08):
        cos = torch.nn.functional.cosine_similarity
        return torch.mean(1.0 - cos(x1, x2))

    def RMSELoss(self, yhat, y, eps=1e-06):
        return torch.sqrt(torch.mean((yhat - y) ** 2) + eps)

    def __init__(self, num_classes_attributes=(8, 22, 32, 32, 21, 16),
        weights=None, attr_loss_type='L1'):
        super(LossW2VNew, self).__init__()
        self.loss = 0
        self.num_classes_attributes = num_classes_attributes
        None
        if attr_loss_type == 'L1':
            self.loss = nn.L1Loss()
            None
        elif attr_loss_type == 'L2':
            self.loss = nn.MSELoss()
            None
        elif attr_loss_type == 'cos':
            self.loss = self.cosine_distance
            None
        self.weights = weights

    def remove_zeros(self, label_att, predicted_attributes_group):
        mask = label_att[:, :] != 0
        mask = torch.prod(mask, dim=1)
        mask = mask.nonzero().squeeze(-1)
        label_att = label_att[mask, :]
        predicted_attributes_group = predicted_attributes_group[mask, :]
        return label_att, predicted_attributes_group

    def remove_element(self, label_matrix):
        all_mask = []
        for i in range(0, label_matrix.size()[0]):
            mask = label_matrix[i, :, :] == 0
            mask = torch.sum(mask, dim=1)
            mask = (mask != label_matrix[i, :, :].size()[1]).nonzero()[:, 0]
            sel_mask = label_matrix[i, mask, :]
            all_mask.append(sel_mask)
        return all_mask

    def elab_label_attributes(self, label_attributes):
        end_index = 0
        start_index = 0
        for i in xrange(len(self.num_classes_attributes)):
            start_index = end_index
            end_index = start_index + self.num_classes_attributes[i]
            """ 64x131x50 """
            label_attributes_group = label_attributes[:, start_index:
                end_index, :]
            label_attributes_group = self.remove_element(label_attributes_group
                )

    def _forward(self, predicted_attributes, label_attributes):
        end_index = 0
        start_index = 0
        loss = 0
        for i in xrange(len(self.num_classes_attributes)):
            start_index = end_index
            end_index = start_index + self.num_classes_attributes[i]
            """ 64x131x50 """
            label_attributes_group = label_attributes[:, start_index:
                end_index, :]
            """ 64x50 """
            predicted_attributes_group = predicted_attributes[i]
            predicted_attributes_group = predicted_attributes_group.unsqueeze(1
                )
            """ 64x131x50 """
            predicted_attributes_group = predicted_attributes_group.repeat([
                1, label_attributes_group.size(1), 1])
            """ 256x50 """
            predicted_attributes_group = predicted_attributes_group.reshape(
                predicted_attributes_group.size(0) *
                predicted_attributes_group.size(1),
                predicted_attributes_group.size(2))
            """ 256x50 """
            label_attributes_group = label_attributes_group.reshape(
                label_attributes_group.size(0) * label_attributes_group.
                size(1), label_attributes_group.size(2))
            """ 64x300 """
            if self.weights is not None:
                W = self.weights[start_index:end_index]
                W = W.unsqueeze(0).unsqueeze(2).expand(label_attributes_group
                    .size(0), -1, label_attributes_group.size(2))
                label_att = (label_attributes_group * W).sum(1)
            else:
                label_att, predicted_attributes_group = self.remove_zeros(
                    label_attributes_group, predicted_attributes_group)
            part_loss = self.loss(predicted_attributes_group, label_att)
            if torch.isnan(part_loss).any():
                None
            loss = loss + part_loss
        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.015371