import torch
from torch._inductor.select_algorithm import extern_kernels
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
import math
import numpy as np
import torch.nn as nn
import torch.utils.data
from itertools import product as product
from math import sqrt as sqrt
import torch.nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor


@triton.jit
def triton_poi_fused_div_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x1 = xindex // 4
    tmp0 = tl.load(in_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp2 = tmp1 * tmp1
    tmp4 = tmp3 * tmp3
    tmp5 = tmp2 + tmp4
    tmp7 = tmp6 * tmp6
    tmp8 = tmp5 + tmp7
    tmp10 = tmp9 * tmp9
    tmp11 = tmp8 + tmp10
    tmp12 = libdevice.sqrt(tmp11)
    tmp13 = 1e-12
    tmp14 = triton_helpers.maximum(tmp12, tmp13)
    tmp15 = tmp0 / tmp14
    tl.store(out_ptr0 + x2, tmp15, xmask)


@triton.jit
def triton_poi_fused_div_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 20
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x1 = xindex // 4
    tmp0 = tl.load(in_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp9 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp2 = tmp1 * tmp1
    tmp4 = tmp3 * tmp3
    tmp5 = tmp2 + tmp4
    tmp7 = tmp6 * tmp6
    tmp8 = tmp5 + tmp7
    tmp10 = tmp9 * tmp9
    tmp11 = tmp8 + tmp10
    tmp12 = libdevice.sqrt(tmp11)
    tmp13 = 1e-12
    tmp14 = triton_helpers.maximum(tmp12, tmp13)
    tmp15 = tmp0 / tmp14
    tl.store(out_ptr0 + x2, tmp15, xmask)


@triton.jit
def triton_poi_fused_cat_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4,
    out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 20
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 5
    x1 = xindex // 5
    x2 = xindex
    tmp7 = tl.load(in_ptr1 + 0)
    tmp8 = tl.broadcast_to(tmp7, [XBLOCK])
    tmp0 = x0
    tl.full([1], 0, tl.int64)
    tmp3 = tl.full([1], 4, tl.int64)
    tmp4 = tmp0 < tmp3
    tmp5 = tl.load(in_ptr0 + x1, tmp4 & xmask, eviction_policy='evict_last',
        other=0.0)
    tmp6 = tl.sigmoid(tmp5)
    tmp9 = tl.load(in_ptr2 + (5 * x1 + x0), tmp4 & xmask, eviction_policy=
        'evict_last', other=0.0)
    tmp10 = tmp8 * tmp9
    tmp11 = tl.load(in_ptr3 + x0, tmp4 & xmask, eviction_policy=
        'evict_last', other=0.0)
    tmp12 = tmp10 * tmp11
    tmp13 = tl.load(in_ptr4 + x0, tmp4 & xmask, eviction_policy=
        'evict_last', other=0.0)
    tmp14 = tmp12 + tmp13
    tmp15 = tmp6 * tmp14
    tmp16 = 1.0
    tmp17 = tmp16 - tmp6
    tmp18 = tmp17 * tmp10
    tmp19 = tmp15 + tmp18
    tmp20 = tl.full(tmp19.shape, 0.0, tmp19.dtype)
    tmp21 = tl.where(tmp4, tmp19, tmp20)
    tmp22 = tmp0 >= tmp3
    tl.full([1], 5, tl.int64)
    tmp25 = tl.load(in_ptr2 + (4 + 5 * x1), tmp22 & xmask, eviction_policy=
        'evict_last', other=0.0)
    tmp26 = tmp8 * tmp25
    tmp27 = tl.full(tmp26.shape, 0.0, tmp26.dtype)
    tmp28 = tl.where(tmp22, tmp26, tmp27)
    tmp29 = tl.where(tmp4, tmp21, tmp28)
    tl.store(out_ptr0 + x2, tmp29, xmask)


def call(args):
    (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
        primals_7, primals_8, primals_9) = args
    args.clear()
    assert_size_stride(primals_1, (4, 4), (4, 1))
    assert_size_stride(primals_2, (5, 4), (4, 1))
    assert_size_stride(primals_3, (1,), (1,))
    assert_size_stride(primals_4, (1, 4), (4, 1))
    assert_size_stride(primals_5, (1,), (1,))
    assert_size_stride(primals_6, (4,), (1,))
    assert_size_stride(primals_7, (4,), (1,))
    assert_size_stride(primals_8, (4, 4), (4, 1))
    assert_size_stride(primals_9, (4,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_div_0[grid(16)](primals_1, buf0, 16, XBLOCK=16,
            num_warps=1, num_stages=1)
        buf1 = empty_strided_cuda((5, 4), (4, 1), torch.float32)
        triton_poi_fused_div_1[grid(20)](primals_2, buf1, 20, XBLOCK=32,
            num_warps=1, num_stages=1)
        buf2 = empty_strided_cuda((4, 5), (5, 1), torch.float32)
        extern_kernels.mm(buf0, reinterpret_tensor(buf1, (4, 5), (1, 4), 0),
            out=buf2)
        buf4 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
        extern_kernels.addmm(primals_5, primals_1, reinterpret_tensor(
            primals_4, (4, 1), (1, 4), 0), alpha=1, beta=1, out=buf4)
        del primals_4
        del primals_5
        buf5 = reinterpret_tensor(buf1, (4, 5), (5, 1), 0)
        del buf1
        triton_poi_fused_cat_2[grid(20)](buf4, primals_3, buf2, primals_6,
            primals_7, buf5, 20, XBLOCK=32, num_warps=1, num_stages=1)
        buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        extern_kernels.addmm(primals_9, primals_1, reinterpret_tensor(
            primals_8, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf6)
        del primals_8
        del primals_9
    return (buf5, buf6, primals_1, primals_2, primals_3, primals_6,
        primals_7, buf0, buf2, buf4)


def cat(tensors, dim=0):
    """
    Efficient version of torch.cat that avoids a copy if there is only a single element in a list
    """
    assert isinstance(tensors, (list, tuple))
    if len(tensors) == 1:
        return tensors[0]
    return torch.cat(tensors, dim)


class NormalizedLinear(torch.nn.Module):
    """
    A advanced Linear layer which supports weight normalization or cosine normalization.

    """

    def __init__(self, in_features, out_features, bias=False, feat_norm=
        True, scale_mode='learn', scale_init=1.0):
        super().__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.feat_norm = feat_norm
        self.scale_mode = scale_mode
        self.scale_init = scale_init
        self.weight = torch.nn.Parameter(torch.Tensor(out_features,
            in_features))
        if bias:
            self.bias = torch.nn.Parameter(torch.Tensor(out_features))
        else:
            self.register_parameter('bias', None)
        if self.scale_mode == 'constant':
            self.scale = scale_init
        elif self.scale_mode == 'learn':
            self.scale = torch.nn.Parameter(torch.ones(1) * scale_init)
        else:
            raise NotImplementedError

    def reset_parameters(self):
        torch.nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
        if self.bias is not None:
            fan_in, _ = torch.nn.init._calculate_fan_in_and_fan_out(self.weight
                )
            bound = 1 / math.sqrt(fan_in)
            torch.nn.init.uniform_(self.bias, -bound, bound)

    def forward(self, inputs):
        """
        Args:
            inputs (torch.Tensor): (N, C)
        Return:
            output (torch.Tensor): (N, D)
        """
        if self.feat_norm:
            inputs = torch.nn.functional.normalize(inputs, dim=1)
        output = inputs.mm(torch.nn.functional.normalize(self.weight, dim=1
            ).t())
        output = self.scale * output
        return output

    def extra_repr(self):
        s = 'in_features={in_features}, out_features={out_features}'
        if self.bias is None:
            s += ', bias=False'
        s += ', feat_norm={feat_norm}'
        s += ', scale_mode={scale_mode}'
        s += ', scale_init={scale_init}'
        return s.format(**self.__dict__)


class DisAlignCosineFastRCNNOutputLayersNew(nn.Module):
    """
    Two linear layers for predicting Fast R-CNN outputs:
      (1) proposal-to-detection box regression deltas
      (2) classification scores
    """

    def __init__(self, input_size, num_classes, cls_agnostic_bbox_reg,
        box_dim=4, scale_mode='learn', scale_init=20.0):
        """
        Args:
            input_size (int): channels, or (channels, height, width)
            num_classes (int): number of foreground classes
            cls_agnostic_bbox_reg (bool): whether to use class agnostic for bbox regression
            box_dim (int): the dimension of bounding boxes.
                Example box dimensions: 4 for regular XYXY boxes and 5 for rotated XYWHA boxes
        """
        super(DisAlignCosineFastRCNNOutputLayersNew, self).__init__()
        if not isinstance(input_size, int):
            input_size = np.prod(input_size)
        self.cls_score = NormalizedLinear(input_size, num_classes + 1,
            scale_mode=scale_mode, scale_init=scale_init)
        num_bbox_reg_classes = 1 if cls_agnostic_bbox_reg else num_classes
        self.bbox_pred = nn.Linear(input_size, num_bbox_reg_classes * box_dim)
        self.logit_scale = nn.Parameter(torch.ones(num_classes))
        self.logit_bias = nn.Parameter(torch.zeros(num_classes))
        self.confidence_layer = nn.Linear(input_size, 1)
        nn.init.normal_(self.cls_score.weight, std=0.01)
        nn.init.normal_(self.confidence_layer.weight, std=0.01)
        nn.init.normal_(self.bbox_pred.weight, std=0.001)
        for layer in [self.cls_score, self.confidence_layer, self.bbox_pred]:
            if layer.bias is not None:
                nn.init.constant_(layer.bias, 0)

    def forward(self, input_0):
        primals_6 = self.logit_scale
        primals_7 = self.logit_bias
        primals_2 = self.cls_score.weight
        primals_3 = self.cls_score.scale
        primals_1 = self.bbox_pred.weight
        primals_9 = self.bbox_pred.bias
        primals_4 = self.confidence_layer.weight
        primals_5 = self.confidence_layer.bias
        primals_8 = input_0
        output = call([primals_1, primals_2, primals_3, primals_4,
            primals_5, primals_6, primals_7, primals_8, primals_9])
        return output[0], output[1]


Measured latency_ms: 0.045368