# AOT ID: ['0_inference']
from ctypes import c_void_p, c_long, c_int
import torch
import math
import random
import os
import tempfile
from math import inf, nan
from torch._inductor.hooks import run_intermediate_hooks
from torch._inductor.utils import maybe_profile
from torch._inductor.codegen.memory_planning import _align as align
from torch import device, empty_strided
from torch._inductor.async_compile import AsyncCompile
from torch._inductor.select_algorithm import extern_kernels
from torch._inductor.codegen.multi_kernel import MultiKernelCall
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid, split_scan_grid, grid_combo_kernels, start_graph, end_graph
from torch._C import _cuda_getCurrentRawStream as get_raw_stream

aten = torch.ops.aten
inductor_ops = torch.ops.inductor
_quantized = torch.ops._quantized
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cpu = torch._C._dynamo.guards._empty_strided_cpu
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
empty_strided_xpu = torch._C._dynamo.guards._empty_strided_xpu
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
alloc_from_pool = torch.ops.inductor._alloc_from_pool
async_compile = AsyncCompile()


# kernel path: runs/run_shard_1/inductor_cache/jk/cjksfpx3iwyilcfx4dpxbs6ltmwazirnk4kq6ec5mqttaqmxvhog.py
# Topologically Sorted Source Nodes: [sub, abs_1, lt, less_than_theta, pow_1, mul, mul_1, sub_1, sub_2, add, mul_2, loss, loss_1, loss_2], Original ATen: [aten.sub, aten.abs, aten.lt, aten._to_copy, aten.pow, aten.mul, aten.rsub, aten.add, aten.sum, aten.mean]
# Source node to ATen node mapping:
#   abs_1 => abs_1
#   add => add
#   less_than_theta => convert_element_type
#   loss => add_1
#   loss_1 => sum_1
#   loss_2 => mean
#   lt => lt
#   mul => mul
#   mul_1 => mul_1
#   mul_2 => mul_2
#   pow_1 => pow_1
#   sub => sub
#   sub_1 => sub_1
#   sub_2 => sub_2
# Graph fragment:
#   %sub : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%slice_6, %slice_2), kwargs = {})
#   %abs_1 : [num_users=3] = call_function[target=torch.ops.aten.abs.default](args = (%sub,), kwargs = {})
#   %lt : [num_users=1] = call_function[target=torch.ops.aten.lt.Scalar](args = (%abs_1, 0.1), kwargs = {})
#   %convert_element_type : [num_users=2] = call_function[target=torch.ops.prims.convert_element_type.default](args = (%lt, torch.float32), kwargs = {})
#   %pow_1 : [num_users=1] = call_function[target=torch.ops.aten.pow.Tensor_Scalar](args = (%abs_1, 2), kwargs = {})
#   %mul : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%convert_element_type, %pow_1), kwargs = {})
#   %mul_1 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%mul, 5.0), kwargs = {})
#   %sub_1 : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (1, %convert_element_type), kwargs = {})
#   %sub_2 : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%abs_1, 0.1), kwargs = {})
#   %add : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%sub_2, 0.05000000000000001), kwargs = {})
#   %mul_2 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%sub_1, %add), kwargs = {})
#   %add_1 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%mul_1, %mul_2), kwargs = {})
#   %sum_1 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%add_1, [1], True), kwargs = {})
#   %mean : [num_users=1] = call_function[target=torch.ops.aten.mean.default](args = (%sum_1,), kwargs = {})
triton_per_fused__to_copy_abs_add_lt_mean_mul_pow_rsub_sub_sum_0 = async_compile.triton('triton_per_fused__to_copy_abs_add_lt_mean_mul_pow_rsub_sub_sum_0', '''
import triton
import triton.language as tl
from triton.compiler.compiler import AttrsDescriptor

from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, instance_descriptor, DeviceProperties

@triton_heuristics.persistent_reduction(
    size_hints=[1, 64],
    reduction_hint=ReductionHint.INNER,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: 'i32', 4: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=90, major=9, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=132), 'constants': {3: 1}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 4), equal_to_1=(3,))]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_per_fused__to_copy_abs_add_lt_mean_mul_pow_rsub_sub_sum_0', 'mutated_arg_names': ['in_out_ptr0'], 'no_x_dim': False, 'num_load': 2, 'num_reduction': 1, 'backend_hash': 'B098E03CDA7B8ADC90DAFFDF24A2956451D1B13F297756A5DCC209498AA53705', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False}
)
@triton.jit
def triton_per_fused__to_copy_abs_add_lt_mean_mul_pow_rsub_sub_sum_0(in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK : tl.constexpr):
    xnumel = 1
    rnumel = 64
    RBLOCK: tl.constexpr = 64
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = tl.full([XBLOCK, RBLOCK], True, tl.int1)
    rindex = tl.arange(0, RBLOCK)[None, :]
    roffset = 0
    rmask = 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_ptr1 + (r0 + (64*r1)), None)
    tmp2 = tmp0 - tmp1
    tmp3 = tl_math.abs(tmp2)
    tmp4 = 0.1
    tmp5 = tmp3 < tmp4
    tmp6 = tmp5.to(tl.float32)
    tmp7 = tmp3 * tmp3
    tmp8 = tmp6 * tmp7
    tmp9 = 5.0
    tmp10 = tmp8 * tmp9
    tmp11 = 1.0
    tmp12 = tmp11 - tmp6
    tmp13 = tmp3 - tmp4
    tmp14 = 0.05000000000000001
    tmp15 = tmp13 + tmp14
    tmp16 = tmp12 * tmp15
    tmp17 = tmp10 + tmp16
    tmp18 = tl.broadcast_to(tmp17, [XBLOCK, RBLOCK])
    tmp20 = tl.sum(tmp18, 1)[:, None]
    tmp21 = 64.0
    tmp22 = tmp20 / tmp21
    tl.debug_barrier()
    tl.store(in_out_ptr0 + (tl.full([XBLOCK, 1], 0, tl.int32)), tmp22, None)
''', device_str='cuda')


async_compile.wait(globals())
del async_compile

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)
        buf1 = buf0; del buf0  # reuse
        # Topologically Sorted Source Nodes: [sub, abs_1, lt, less_than_theta, pow_1, mul, mul_1, sub_1, sub_2, add, mul_2, loss, loss_1, loss_2], Original ATen: [aten.sub, aten.abs, aten.lt, aten._to_copy, aten.pow, aten.mul, aten.rsub, aten.add, aten.sum, aten.mean]
        stream0 = get_raw_stream(0)
        triton_per_fused__to_copy_abs_add_lt_mean_mul_pow_rsub_sub_sum_0.run(buf1, arg1_1, arg0_1, 1, 64, grid=grid(1), stream=stream0)
        del arg0_1
        del arg1_1
    return (buf1, )


def benchmark_compiled_module(times=10, repeat=10):
    from torch._dynamo.testing import rand_strided
    from torch._inductor.utils import print_performance
    arg0_1 = rand_strided((4, 4, 4, 4), (64, 16, 4, 1), device='cuda:0', dtype=torch.float32)
    arg1_1 = rand_strided((4, 4, 4, 4), (64, 16, 4, 1), device='cuda:0', dtype=torch.float32)
    fn = lambda: call([arg0_1, arg1_1])
    return print_performance(fn, times=times, repeat=repeat)


if __name__ == "__main__":
    from torch._inductor.wrapper_benchmark import compiled_module_main
    compiled_module_main('None', benchmark_compiled_module)

import torch
import torch.nn as nn
import torch.nn.functional as F


def adjust_smooth_l1_loss(y_pred, theta=0.1):
    less_grad_factor = 1.0 / (2 * theta)
    less_loss_bias = less_grad_factor * theta ** 2
    less_than_theta = (y_pred < theta).float()
    loss = less_than_theta * y_pred ** 2 * less_grad_factor + (1 -
        less_than_theta) * (y_pred - theta + less_loss_bias)
    return loss


class CrossEntropyLoss(nn.Module):

    def __init__(self, weight=None, ignore_index=255, reduction='mean'):
        """ NLLLoss: negative log likelihood loss.
            # nll_loss: weights: None | a tensor of size C
                        pred in [N, C, d1, d2, ..., dk]
                        target in [N, d1, d2, ..., dk]
                        output in [N, d1, d2, ..., dk]
        """
        super(CrossEntropyLoss, self).__init__()
        self.nll_loss = nn.NLLLoss(weight, ignore_index=ignore_index,
            reduction=reduction)

    def forward(self, inputs, targets):
        return self.nll_loss(F.log_softmax(inputs, dim=1), targets)


class BinaryLoss(nn.Module):
    """This class computes the Binary loss to force BG pixels close to 0 and FG pixels far away.
    """

    def __init__(self, margin=2.0, FG_stCH=1, loss_type='l1', weights=None):
        """
        margin: minimum distance between FG/BG if prediction with 1 channel
        FG_stCH: start channel of FG objects on prediction with multiple channels
        loss_type: 'l1' | 'CE', works for prediction with multiple channel.
                   if 'l1', prediction is expected to be softmax2d output.
                   if 'CE', prediction is expected to be net logits
                   if prediction has channel=1,
        weights: if not None, a tensor of size C
        """
        super(BinaryLoss, self).__init__()
        self.margin = margin
        self.FG_stCH = FG_stCH
        self.loss_type = loss_type if FG_stCH > 1 else 'l1'
        if self.loss_type == 'CE':
            self.CE_loss = CrossEntropyLoss(weight=weights, reduction='none')

    def forward(self, preds, targets, weights=None):
        """
        Params:
            preds/targets: [bs, ch, ht, wd]
            weights:[bs, 1, ht, wd]
        """
        _bs, ch, _ht, _wd = preds.size()
        if ch > 1:
            if self.loss_type == 'l1':
                preds_0 = preds[:, :self.FG_stCH, :, :]
                targets_0 = targets[:, :self.FG_stCH, :, :].float()
                loss = adjust_smooth_l1_loss(torch.abs(targets_0 - preds_0))
                loss = loss.sum(axis=1, keepdim=True)
            else:
                preds_0 = preds[:, :self.FG_stCH, :, :].float()
                targets_0 = targets[:, :self.FG_stCH, :, :]
                preds_1, _ = preds[:, self.FG_stCH:, :, :].float().max(axis
                    =1, keepdim=True)
                targets_1 = targets[:, self.FG_stCH:, :, :].sum(axis=1,
                    keepdim=True).int()
                _, target_id = torch.cat([targets_0, targets_1], axis=1).max(
                    axis=1)
                loss = self.CE_loss(torch.cat((preds_0, preds_1), axis=1),
                    target_id)
                loss = loss[:, None, :, :]
        else:
            isFG = (targets > 0.5).float()
            loss_0 = adjust_smooth_l1_loss(F.relu(preds))
            loss_1 = adjust_smooth_l1_loss(F.relu(self.margin - preds))
            loss = loss_0 * (1.0 - isFG) + loss_1 * isFG
        if weights is not None:
            loss = torch.mul(loss, weights).sum() / (weights.sum() + 0.0001)
        else:
            loss = loss.mean()
        return loss.float()


def get_inputs():
    return [torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4])]


def get_init_inputs():
    return [[], {}]

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
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_per_fused__to_copy_abs_add_lt_mean_mul_pow_rsub_sub_sum_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 % 16
    r1 = rindex // 16
    tmp0 = tl.load(in_ptr0 + (r0 + 64 * r1), None)
    tmp1 = tl.load(in_ptr1 + (r0 + 64 * r1), None)
    tmp2 = tmp0 - tmp1
    tmp3 = tl_math.abs(tmp2)
    tmp4 = 0.1
    tmp5 = tmp3 < tmp4
    tmp6 = tmp5.to(tl.float32)
    tmp7 = tmp3 * tmp3
    tmp8 = tmp6 * tmp7
    tmp9 = 5.0
    tmp10 = tmp8 * tmp9
    tmp11 = 1.0
    tmp12 = tmp11 - tmp6
    tmp13 = tmp3 - tmp4
    tmp14 = 0.05000000000000001
    tmp15 = tmp13 + tmp14
    tmp16 = tmp12 * tmp15
    tmp17 = tmp10 + tmp16
    tmp18 = tl.broadcast_to(tmp17, [XBLOCK, RBLOCK])
    tmp20 = tl.sum(tmp18, 1)[:, None]
    tmp21 = 64.0
    tmp22 = tmp20 / tmp21
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp22, 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)
        buf1 = buf0
        del buf0
        get_raw_stream(0)
        triton_per_fused__to_copy_abs_add_lt_mean_mul_pow_rsub_sub_sum_0[grid
            (1)](buf1, arg1_1, arg0_1, 1, 64, XBLOCK=1, num_warps=2,
            num_stages=1)
        del arg0_1
        del arg1_1
    return buf1,


def adjust_smooth_l1_loss(y_pred, theta=0.1):
    less_grad_factor = 1.0 / (2 * theta)
    less_loss_bias = less_grad_factor * theta ** 2
    less_than_theta = (y_pred < theta).float()
    loss = less_than_theta * y_pred ** 2 * less_grad_factor + (1 -
        less_than_theta) * (y_pred - theta + less_loss_bias)
    return loss


class CrossEntropyLoss(nn.Module):

    def __init__(self, weight=None, ignore_index=255, reduction='mean'):
        """ NLLLoss: negative log likelihood loss.
            # nll_loss: weights: None | a tensor of size C
                        pred in [N, C, d1, d2, ..., dk]
                        target in [N, d1, d2, ..., dk]
                        output in [N, d1, d2, ..., dk]
        """
        super(CrossEntropyLoss, self).__init__()
        self.nll_loss = nn.NLLLoss(weight, ignore_index=ignore_index,
            reduction=reduction)

    def forward(self, inputs, targets):
        return self.nll_loss(F.log_softmax(inputs, dim=1), targets)


class BinaryLossNew(nn.Module):
    """This class computes the Binary loss to force BG pixels close to 0 and FG pixels far away.
    """

    def __init__(self, margin=2.0, FG_stCH=1, loss_type='l1', weights=None):
        """
        margin: minimum distance between FG/BG if prediction with 1 channel
        FG_stCH: start channel of FG objects on prediction with multiple channels
        loss_type: 'l1' | 'CE', works for prediction with multiple channel.
                   if 'l1', prediction is expected to be softmax2d output.
                   if 'CE', prediction is expected to be net logits
                   if prediction has channel=1,
        weights: if not None, a tensor of size C
        """
        super(BinaryLossNew, self).__init__()
        self.margin = margin
        self.FG_stCH = FG_stCH
        self.loss_type = loss_type if FG_stCH > 1 else 'l1'
        if self.loss_type == 'CE':
            self.CE_loss = CrossEntropyLoss(weight=weights, reduction='none')

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