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
import torch.nn.functional as F
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_sum_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
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp4 = tmp2 + tmp3
    tmp6 = tmp4 + tmp5
    tmp7 = 0.25
    tmp8 = tmp6 * tmp7
    tl.store(out_ptr0 + x0, tmp8, xmask)


@triton.jit
def triton_poi_fused_convolution_relu_1(in_out_ptr0, in_ptr0, xnumel,
    XBLOCK: tl.constexpr):
    xnumel = 4
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_out_ptr0 + x0, xmask)
    tmp1 = tl.load(in_ptr0 + 0)
    tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
    tmp3 = tmp0 + tmp2
    tmp4 = tl.full([1], 0, tl.int32)
    tmp5 = triton_helpers.maximum(tmp4, tmp3)
    tl.store(in_out_ptr0 + x0, tmp5, xmask)


@triton.jit
def triton_poi_fused_convolution_2(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
    .constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x0 = xindex % 4
    tmp0 = tl.load(in_out_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tl.store(in_out_ptr0 + x2, tmp2, xmask)


@triton.jit
def triton_poi_fused_mul_sigmoid_3(in_ptr0, in_ptr1, out_ptr0, xnumel,
    XBLOCK: tl.constexpr):
    xnumel = 64
    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_ptr1 + x1, xmask, eviction_policy='evict_last')
    tmp2 = tl.sigmoid(tmp1)
    tmp3 = tmp0 * tmp2
    tl.store(out_ptr0 + x2, tmp3, xmask)


def call(args):
    primals_1, primals_2, primals_3, primals_4, primals_5 = args
    args.clear()
    assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
    assert_size_stride(primals_2, (1, 4, 1), (4, 1, 1))
    assert_size_stride(primals_3, (1,), (1,))
    assert_size_stride(primals_4, (4, 1, 1), (1, 1, 1))
    assert_size_stride(primals_5, (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_sum_0[grid(16)](primals_1, buf0, 16, XBLOCK=16,
            num_warps=1, num_stages=1)
        buf1 = extern_kernels.convolution(reinterpret_tensor(buf0, (4, 4, 1
            ), (4, 1, 0), 0), primals_2, stride=(1,), padding=(0,),
            dilation=(1,), transposed=False, output_padding=(0,), groups=1,
            bias=None)
        assert_size_stride(buf1, (4, 1, 1), (1, 1, 1))
        buf2 = buf1
        del buf1
        triton_poi_fused_convolution_relu_1[grid(4)](buf2, primals_3, 4,
            XBLOCK=4, num_warps=1, num_stages=1)
        del primals_3
        buf3 = extern_kernels.convolution(buf2, primals_4, stride=(1,),
            padding=(0,), dilation=(1,), transposed=False, output_padding=(
            0,), groups=1, bias=None)
        assert_size_stride(buf3, (4, 4, 1), (4, 1, 1))
        buf4 = buf3
        del buf3
        triton_poi_fused_convolution_2[grid(16)](buf4, primals_5, 16,
            XBLOCK=16, num_warps=1, num_stages=1)
        del primals_5
        buf5 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
        triton_poi_fused_mul_sigmoid_3[grid(64)](primals_1, buf4, buf5, 64,
            XBLOCK=64, num_warps=1, num_stages=1)
    return buf5, primals_1, primals_2, primals_4, reinterpret_tensor(buf0,
        (4, 4, 1), (4, 1, 1), 0), buf2, buf4


def to_device(device_object, tensor):
    """
    Select device for non-parameters tensor w.r.t model or tensor which has been specified a device.
    """
    if isinstance(device_object, torch.nn.Module):
        next(device_object.parameters()).device
    elif isinstance(device_object, torch.Tensor):
        pass
    return tensor


class TdnnAffine(torch.nn.Module):
    """ An implemented tdnn affine component by conv1d
        y = splice(w * x, context) + b

    @input_dim: number of dims of frame <=> inputs channels of conv
    @output_dim: number of layer nodes <=> outputs channels of conv
    @context: a list of context
        e.g.  [-2,0,2]
    If context is [0], then the TdnnAffine is equal to linear layer.
    """

    def __init__(self, input_dim, output_dim, context=[0], bias=True, pad=
        True, norm_w=False, norm_f=False, subsampling_factor=1):
        super(TdnnAffine, self).__init__()
        for index in range(0, len(context) - 1):
            if context[index] >= context[index + 1]:
                raise ValueError(
                    'Context tuple {} is invalid, such as the order.'.
                    format(context))
        self.input_dim = input_dim
        self.output_dim = output_dim
        self.context = context
        self.bool_bias = bias
        self.pad = pad
        self.norm_w = norm_w
        self.norm_f = norm_f
        self.stride = subsampling_factor
        self.left_context = context[0] if context[0] < 0 else 0
        self.right_context = context[-1] if context[-1] > 0 else 0
        self.tot_context = self.right_context - self.left_context + 1
        if self.tot_context > 1 and self.norm_f:
            self.norm_f = False
            None
        kernel_size = self.tot_context,
        self.weight = torch.nn.Parameter(torch.randn(output_dim, input_dim,
            *kernel_size))
        if self.bool_bias:
            self.bias = torch.nn.Parameter(torch.randn(output_dim))
        else:
            self.register_parameter('bias', None)
        self.init_weight()
        if len(context) != self.tot_context:
            self.mask = torch.tensor([[[(1 if index in context else 0) for
                index in range(self.left_context, self.right_context + 1)]]])
        else:
            self.mask = None
        self.selected_device = False

    def init_weight(self):
        torch.nn.init.normal_(self.weight, 0.0, 0.01)
        if self.bias is not None:
            torch.nn.init.constant_(self.bias, 0.0)

    def forward(self, inputs):
        """
        @inputs: a 3-dimensional tensor (a batch), including [samples-index, frames-dim-index, frames-index]
        """
        assert len(inputs.shape) == 3
        assert inputs.shape[1] == self.input_dim
        if self.pad:
            inputs = F.pad(inputs, (-self.left_context, self.right_context),
                mode='constant', value=0)
        assert inputs.shape[2] >= self.tot_context
        if not self.selected_device and self.mask is not None:
            self.mask = to_device(self, self.mask)
            self.selected_device = True
        filters = (self.weight * self.mask if self.mask is not None else
            self.weight)
        if self.norm_w:
            filters = F.normalize(filters, dim=1)
        if self.norm_f:
            inputs = F.normalize(inputs, dim=1)
        outputs = F.conv1d(inputs, filters, self.bias, self.stride, padding
            =0, dilation=1, groups=1)
        return outputs

    def extra_repr(self):
        return (
            '{input_dim}, {output_dim}, context={context}, bias={bool_bias}, stride={stride}, pad={pad}, norm_w={norm_w}, norm_f={norm_f}'
            .format(**self.__dict__))

    @classmethod
    def thop_count(self, m, x, y):
        x = x[0]
        kernel_ops = torch.zeros(m.weight.size()[2:]).numel()
        bias_ops = 1 if m.bias is not None else 0
        total_ops = y.nelement() * (m.input_dim * kernel_ops + bias_ops)
        m.total_ops += torch.DoubleTensor([int(total_ops)])


class StatisticsPooling(torch.nn.Module):
    """ An usual mean [+ stddev] poolling layer"""

    def __init__(self, input_dim, stddev=True, unbiased=False, eps=1e-10):
        super(StatisticsPooling, self).__init__()
        self.stddev = stddev
        self.input_dim = input_dim
        if self.stddev:
            self.output_dim = 2 * input_dim
        else:
            self.output_dim = input_dim
        self.eps = eps
        self.unbiased = unbiased

    def forward(self, inputs):
        """
        @inputs: a 3-dimensional tensor (a batch), including [samples-index, frames-dim-index, frames-index]
        """
        assert len(inputs.shape) == 3
        assert inputs.shape[1] == self.input_dim
        counts = inputs.shape[2]
        mean = torch.unsqueeze(inputs.sum(dim=2) / counts, dim=2)
        if self.stddev:
            if self.unbiased and counts > 1:
                counts = counts - 1
            var = torch.sum((inputs - mean) ** 2, dim=2) / counts
            std = torch.unsqueeze(torch.sqrt(var.clamp(min=self.eps)), dim=2)
            return torch.cat((mean, std), dim=1)
        else:
            return mean

    def get_output_dim(self):
        return self.output_dim

    def extra_repr(self):
        return (
            '{input_dim}, {output_dim}, stddev={stddev}, unbiased={unbiased}, eps={eps}'
            .format(**self.__dict__))

    @classmethod
    def thop_count(self, m, x, y):
        pass


class SEBlockNew(torch.nn.Module):
    """ A SE Block layer layer which can learn to use global information to selectively emphasise informative 
    features and suppress less useful ones.
    This is a pytorch implementation of SE Block based on the paper:
    Squeeze-and-Excitation Networks
    by JFChou xmuspeech 2019-07-13
       Snowdar xmuspeech 2020-04-28 [Check and update]
    """

    def __init__(self, input_dim, ratio=4, inplace=True):
        """
        @ratio: a reduction ratio which allows us to vary the capacity and computational cost of the SE blocks 
        in the network.
        """
        super(SEBlockNew, self).__init__()
        self.input_dim = input_dim
        self.pooling = StatisticsPooling(input_dim, stddev=False)
        self.fc_1 = TdnnAffine(input_dim, input_dim // ratio)
        self.relu = torch.nn.ReLU(inplace=inplace)
        self.fc_2 = TdnnAffine(input_dim // ratio, input_dim)
        self.sigmoid = torch.nn.Sigmoid()

    def forward(self, input_0):
        primals_2 = self.fc_1.weight
        primals_3 = self.fc_1.bias
        primals_4 = self.fc_2.weight
        primals_5 = self.fc_2.bias
        primals_1 = input_0
        output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
        return output[0]


Measured latency_ms: 0.078565