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 math as tl_math
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


@triton.jit
def triton_poi_fused__log_softmax_convolution_0(in_ptr0, in_ptr1, out_ptr0,
    out_ptr1, xnumel, XBLOCK: tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 4
    x1 = xindex // 4
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
    tmp1 = tl.load(in_ptr1 + 0)
    tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
    tmp6 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
    tmp7 = tl.load(in_ptr1 + 1)
    tmp8 = tl.broadcast_to(tmp7, [XBLOCK])
    tmp12 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
    tmp13 = tl.load(in_ptr1 + 2)
    tmp14 = tl.broadcast_to(tmp13, [XBLOCK])
    tmp18 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
    tmp19 = tl.load(in_ptr1 + 3)
    tmp20 = tl.broadcast_to(tmp19, [XBLOCK])
    tmp3 = tmp0 + tmp2
    tmp4 = 1.0
    tmp5 = tmp3 * tmp4
    tmp9 = tmp6 + tmp8
    tmp10 = tmp9 * tmp4
    tmp11 = triton_helpers.maximum(tmp5, tmp10)
    tmp15 = tmp12 + tmp14
    tmp16 = tmp15 * tmp4
    tmp17 = triton_helpers.maximum(tmp11, tmp16)
    tmp21 = tmp18 + tmp20
    tmp22 = tmp21 * tmp4
    tmp23 = triton_helpers.maximum(tmp17, tmp22)
    tmp24 = tmp5 - tmp23
    tmp25 = tmp24 * tmp4
    tmp26 = tl_math.exp(tmp25)
    tmp27 = tmp10 - tmp23
    tmp28 = tmp27 * tmp4
    tmp29 = tl_math.exp(tmp28)
    tmp30 = tmp26 + tmp29
    tmp31 = tmp16 - tmp23
    tmp32 = tmp31 * tmp4
    tmp33 = tl_math.exp(tmp32)
    tmp34 = tmp30 + tmp33
    tmp35 = tmp22 - tmp23
    tmp36 = tmp35 * tmp4
    tmp37 = tl_math.exp(tmp36)
    tmp38 = tmp34 + tmp37
    tl.store(out_ptr0 + x2, tmp23, xmask)
    tl.store(out_ptr1 + x2, tmp38, xmask)


@triton.jit
def triton_poi_fused__log_softmax_convolution_1(in_out_ptr0, in_ptr0,
    in_ptr1, in_ptr2, xnumel, XBLOCK: tl.constexpr):
    xnumel = 64
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex
    x1 = xindex // 4 % 4
    x0 = xindex % 4
    x2 = xindex // 16
    tmp0 = tl.load(in_out_ptr0 + x3, xmask)
    tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr1 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
        )
    tmp8 = tl.load(in_ptr2 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
        )
    tmp2 = tmp0 + tmp1
    tmp3 = 1.0
    tmp4 = tmp2 * tmp3
    tmp6 = tmp4 - tmp5
    tmp7 = tmp6 * tmp3
    tmp9 = tl_math.log(tmp8)
    tmp10 = tmp7 - tmp9
    tl.store(in_out_ptr0 + x3, tmp10, xmask)


def call(args):
    primals_1, primals_2, primals_3 = args
    args.clear()
    assert_size_stride(primals_1, (4, 4, 4), (16, 4, 1))
    assert_size_stride(primals_2, (4, 4, 1), (4, 1, 1))
    assert_size_stride(primals_3, (4,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1,),
            padding=(0,), dilation=(1,), transposed=False, output_padding=(
            0,), groups=1, bias=None)
        assert_size_stride(buf0, (4, 4, 4), (16, 4, 1))
        buf1 = empty_strided_cuda((4, 1, 4), (4, 16, 1), torch.float32)
        buf2 = empty_strided_cuda((4, 1, 4), (4, 16, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused__log_softmax_convolution_0[grid(16)](buf0,
            primals_3, buf1, buf2, 16, XBLOCK=16, num_warps=1, num_stages=1)
        buf3 = buf0
        del buf0
        triton_poi_fused__log_softmax_convolution_1[grid(64)](buf3,
            primals_3, buf1, buf2, 64, XBLOCK=64, num_warps=1, num_stages=1)
        del buf1
        del buf2
        del primals_3
    return buf3, primals_1, primals_2, buf3


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, stride=1, groups=1, norm_w=False, norm_f=False):
        super(TdnnAffine, self).__init__()
        assert input_dim % groups == 0
        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.groups = groups
        self.norm_w = norm_w
        self.norm_f = norm_f
        self.stride = stride
        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 //
            groups, *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, stride=self.stride,
            padding=0, dilation=1, groups=self.groups)
        return outputs

    def extra_repr(self):
        return (
            '{input_dim}, {output_dim}, context={context}, bias={bool_bias}, stride={stride}, pad={pad}, groups={groups}, 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 SoftmaxAffineLayerNew(torch.nn.Module):
    """ An usual 2-fold softmax layer with an affine transform.
    @dim: which dim to apply softmax on
    """

    def __init__(self, input_dim, output_dim, context=[0], dim=1, log=True,
        bias=True, groups=1, t=1.0, special_init=False):
        super(SoftmaxAffineLayerNew, self).__init__()
        self.affine = TdnnAffine(input_dim, output_dim, context=context,
            bias=bias, groups=groups)
        self.t = t
        if log:
            self.softmax = torch.nn.LogSoftmax(dim=dim)
        else:
            self.softmax = torch.nn.Softmax(dim=dim)
        if special_init:
            torch.nn.init.xavier_uniform_(self.affine.weight, gain=torch.nn
                .init.calculate_gain('sigmoid'))

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


Measured latency_ms: 0.039815