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
import numpy as np
from torch import 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_mean_sub_0(in_ptr0, in_ptr1, out_ptr0, 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 + (16 + r0 + 64 * r1), None)
    tmp1 = tl.load(in_ptr1 + (16 + r0 + 64 * r1), None)
    tmp2 = tmp0 - tmp1
    tmp3 = tl_math.abs(tmp2)
    tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
    tmp6 = tl.sum(tmp4, 1)[:, None]
    tl.store(out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp6, None)


@triton.jit
def triton_per_fused_abs_add_div_exp_mean_mul_reciprocal_rsub_sub_sum_1(
    in_out_ptr0, in_out_ptr1, in_out_ptr2, in_ptr0, in_ptr1, in_ptr2,
    in_ptr3, out_ptr4, xnumel, rnumel):
    XBLOCK: tl.constexpr = 1
    RBLOCK: tl.constexpr = 256
    xoffset = tl.program_id(0) * XBLOCK
    tl.full([1], xoffset, tl.int32)
    tl.full([RBLOCK], True, tl.int1)
    rindex = tl.arange(0, RBLOCK)[:]
    tl.full([RBLOCK], True, tl.int1)
    r0 = rindex
    r1 = rindex % 16
    r2 = rindex // 16 % 4
    tmp0 = tl.load(in_out_ptr0 + 0)
    tmp1 = tl.broadcast_to(tmp0, [RBLOCK])
    tmp4 = tl.load(in_ptr0 + r0, None)
    tmp9 = tl.load(in_ptr1 + (r1 + 64 * r2), None, eviction_policy='evict_last'
        )
    tmp10 = tl.load(in_ptr2 + (r1 + 64 * r2), None, eviction_policy=
        'evict_last')
    tmp12 = tl.load(in_ptr3 + r0, None)
    tmp17 = tl.load(in_ptr2 + (16 + r1 + 64 * r2), None, eviction_policy=
        'evict_last')
    tmp2 = 64.0
    tmp3 = tmp1 / tmp2
    tmp5 = tmp3 * tmp4
    tmp6 = tl.broadcast_to(tmp5, [RBLOCK])
    tmp8 = triton_helpers.promote_to_tensor(tl.sum(tmp6, 0))
    tmp11 = tmp9 * tmp10
    tmp13 = tmp11 * tmp12
    tmp14 = tl.broadcast_to(tmp13, [RBLOCK])
    tmp16 = triton_helpers.promote_to_tensor(tl.sum(tmp14, 0))
    tmp18 = tmp10 - tmp17
    tmp19 = -50.0
    tmp20 = tmp18 * tmp19
    tmp21 = tl_math.exp(tmp20)
    tmp22 = 1.0
    tmp23 = tmp21 + tmp22
    tmp24 = tl.full([1], 1, tl.int32)
    tmp25 = tmp24 / tmp23
    tmp26 = tmp25 * tmp22
    tmp27 = tmp9 * tmp26
    tmp28 = tmp27 * tmp12
    tmp29 = tl.broadcast_to(tmp28, [RBLOCK])
    tmp31 = triton_helpers.promote_to_tensor(tl.sum(tmp29, 0))
    tmp32 = tmp26 * tmp12
    tmp33 = tl.broadcast_to(tmp32, [RBLOCK])
    tmp35 = triton_helpers.promote_to_tensor(tl.sum(tmp33, 0))
    tmp36 = tmp9 * tmp12
    tmp37 = tl.broadcast_to(tmp36, [RBLOCK])
    tmp39 = triton_helpers.promote_to_tensor(tl.sum(tmp37, 0))
    tmp40 = tmp10 * tmp12
    tmp41 = tl.broadcast_to(tmp40, [RBLOCK])
    tmp43 = triton_helpers.promote_to_tensor(tl.sum(tmp41, 0))
    tmp44 = 2.0
    tmp45 = tmp16 * tmp44
    tmp46 = tmp39 + tmp43
    tmp47 = 1e-05
    tmp48 = tmp46 + tmp47
    tmp49 = tmp45 / tmp48
    tmp50 = tmp22 - tmp49
    tmp51 = tmp50 / tmp22
    tmp52 = tmp31 * tmp44
    tmp53 = tmp39 + tmp35
    tmp54 = tmp53 + tmp47
    tmp55 = tmp52 / tmp54
    tmp56 = tmp22 - tmp55
    tmp57 = tmp56 / tmp22
    tmp58 = 256.0
    tmp59 = tmp8 / tmp58
    tmp60 = tmp57 * tmp22
    tmp61 = tmp51 + tmp60
    tmp62 = 10.0
    tmp63 = tmp59 * tmp62
    tmp64 = tmp61 + tmp63
    tl.debug_barrier()
    tl.store(in_out_ptr1 + tl.full([1], 0, tl.int32), tmp51, None)
    tl.debug_barrier()
    tl.store(in_out_ptr2 + tl.full([1], 0, tl.int32), tmp57, None)
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([1], 0, tl.int32), tmp59, None)
    tl.store(out_ptr4 + tl.full([1], 0, tl.int32), tmp64, 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)
        buf8 = empty_strided_cuda((), (), torch.float32)
        get_raw_stream(0)
        triton_per_fused_abs_mean_sub_0[grid(1)](arg0_1, arg1_1, buf8, 1, 
            64, XBLOCK=1, num_warps=2, num_stages=1)
        buf9 = buf8
        del buf8
        buf0 = empty_strided_cuda((), (), torch.float32)
        buf4 = empty_strided_cuda((), (), torch.float32)
        buf3 = buf0
        del buf0
        buf7 = buf4
        del buf4
        buf10 = buf9
        del buf9
        buf11 = empty_strided_cuda((), (), torch.float32)
        triton_per_fused_abs_add_div_exp_mean_mul_reciprocal_rsub_sub_sum_1[
            grid(1)](buf10, buf3, buf7, arg2_1, arg1_1, arg0_1, arg3_1,
            buf11, 1, 256, num_warps=2, num_stages=1)
        del arg0_1
        del arg1_1
        del arg2_1
        del arg3_1
    return buf11, buf3, buf7, buf10


class DBLossNew(nn.Module):

    def __init__(self, alpha=1.0, beta=10.0, ohem_ratio=3):
        """
        Implement DB Loss.
        :param alpha: loss binary_map 前面的系数
        :param beta: loss threshold 前面的系数
        :param ohem_ratio: OHEM的比例
        """
        super().__init__()
        self.alpha = alpha
        self.beta = beta
        self.ohem_ratio = ohem_ratio

    def DB(self, prob_map, thres_map, k=50):
        """
        Differentiable binarization
        another form: torch.sigmoid(k * (prob_map - thres_map))
        """
        return 1.0 / (torch.exp(-k * (prob_map - thres_map)) + 1)

    def dice_loss(self, pred_cls, gt_cls, training_mask):
        """
        dice loss
        此处默认真实值和预测值的格式均为 NCHW
        :param gt_cls: 
        :param pred_cls: 
        :param training_mask: 
        :return:
        """
        eps = 1e-05
        intersection = torch.sum(gt_cls * pred_cls * training_mask)
        union = torch.sum(gt_cls * training_mask) + torch.sum(pred_cls *
            training_mask) + eps
        loss = 1.0 - 2 * intersection / union
        return loss

    def bce_loss(self, input, target, mask):
        if mask.sum() == 0:
            return torch.tensor(0.0, device=input.device, requires_grad=True)
        target[target <= 0.5] = 0
        target[target > 0.5] = 1
        input = input[mask.bool()]
        target = target[mask.bool()]
        loss = nn.BCELoss(reduction='mean')(input, target)
        return loss

    def ohem_single(self, score, gt_text):
        pos_num = int(np.sum(gt_text > 0.5))
        if pos_num == 0:
            selected_mask = np.zeros_like(score)
            selected_mask = selected_mask.reshape(1, selected_mask.shape[0],
                selected_mask.shape[1]).astype('float32')
            return selected_mask
        neg_num = int(np.sum(gt_text <= 0.5))
        neg_num = int(min(pos_num * self.ohem_ratio, neg_num))
        if neg_num == 0:
            selected_mask = np.zeros_like(score)
            selected_mask = selected_mask.reshape(1, selected_mask.shape[0],
                selected_mask.shape[1]).astype('float32')
            return selected_mask
        neg_score = score[gt_text <= 0.5]
        neg_score_sorted = np.sort(-neg_score)
        threshold = -neg_score_sorted[neg_num - 1]
        selected_mask = (score >= threshold) | (gt_text > 0.5)
        selected_mask = selected_mask.reshape(1, selected_mask.shape[0],
            selected_mask.shape[1]).astype('float32')
        return selected_mask

    def ohem_batch(self, scores, gt_texts):
        scores = scores.data.cpu().numpy()
        gt_texts = gt_texts.data.cpu().numpy()
        selected_masks = []
        for i in range(scores.shape[0]):
            selected_masks.append(self.ohem_single(scores[i, :, :],
                gt_texts[i, :, :]))
        selected_masks = np.concatenate(selected_masks, 0)
        selected_masks = torch.from_numpy(selected_masks).float()
        return selected_masks

    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], output[1], output[2], output[3]


Measured latency_ms: 0.034272