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
from typing import Tuple
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_add_exp_mul_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
    xnumel, XBLOCK: tl.constexpr):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x0 = xindex % 4
    tmp0 = tl.load(in_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
    tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
    tmp2 = tl_math.exp(tmp1)
    tmp3 = tmp0 * tmp2
    tmp5 = tmp3 + tmp4
    tl.store(out_ptr0 + x2, tmp5, xmask)


@triton.jit
def triton_per_fused_mul_sum_1(in_ptr0, out_ptr1, xnumel, rnumel, XBLOCK:
    tl.constexpr):
    RBLOCK: tl.constexpr = 4
    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
    tmp0 = tl.load(in_ptr0 + r0, None)
    tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
    tmp3 = tl.sum(tmp1, 1)[:, None]
    tmp4 = 4.0
    tmp5 = tmp4 * tmp3
    tl.store(out_ptr1 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp5, None)


def call(args):
    primals_1, primals_2, primals_3 = args
    args.clear()
    assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_2, (4,), (1,))
    assert_size_stride(primals_3, (4,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_add_exp_mul_0[grid(256)](primals_1, primals_2,
            primals_3, buf0, 256, XBLOCK=256, num_warps=4, num_stages=1)
        del primals_3
        buf2 = empty_strided_cuda((4,), (1,), torch.float32)
        triton_per_fused_mul_sum_1[grid(1)](primals_2, buf2, 1, 4, XBLOCK=1,
            num_warps=2, num_stages=1)
    return buf0, buf2, primals_1, primals_2


class Flow(nn.Module):

    def __init__(self):
        super(Flow, self).__init__()

    def forward(self, *inputs, **kwargs) ->Tuple[torch.Tensor, torch.Tensor]:
        """
        Args:
            *inputs: input [batch, *input_size]
        Returns: out: Tensor [batch, *input_size], logdet: Tensor [batch]
            out, the output of the flow
            logdet, the log determinant of :math:`\\partial output / \\partial input`
        """
        raise NotImplementedError

    def inverse(self, *inputs, **kwargs) ->Tuple[torch.Tensor, torch.Tensor]:
        """
        Args:
            *input: input [batch, *input_size]
        Returns: out: Tensor [batch, *input_size], logdet: Tensor [batch]
            out, the output of the flow
            logdet, the log determinant of :math:`\\partial output / \\partial input`
        """
        raise NotImplementedError

    def init(self, *inputs, **kwargs) ->Tuple[torch.Tensor, torch.Tensor]:
        """
        Initiate the weights according to the initial input data
        :param inputs:
        :param kwargs:
        :return:
        """
        raise NotImplementedError


class ActNormFlowNew(Flow):

    def __init__(self, channels):
        super(ActNormFlowNew, self).__init__()
        self.channels = channels
        self.register_parameter('log_scale', nn.Parameter(torch.normal(0.0,
            0.05, [self.channels])))
        self.register_parameter('bias', nn.Parameter(torch.zeros(self.
            channels)))

    def inverse(self, inputs: 'torch.Tensor', input_lengths=None, epsilon=1e-08
        ) ->Tuple[torch.Tensor, torch.Tensor]:
        input_shape = inputs.shape
        outputs = (inputs - self.bias) / (torch.exp(self.log_scale) + epsilon)
        logdet = -torch.sum(self.log_scale)
        if input_lengths is None:
            logdet = torch.ones(input_shape[0], device=inputs.device) * float(
                input_shape[1]) * logdet
        else:
            logdet = input_lengths.float() * logdet
        return outputs, logdet

    def init(self, inputs: 'torch.Tensor', input_lengths=None, init_scale=
        1.0, epsilon=1e-08):
        _mean = torch.mean(inputs.view(-1, self.channels), dim=0)
        _std = torch.std(inputs.view(-1, self.channels), dim=0)
        self.log_scale.copy_(torch.log(init_scale / (_std + epsilon)))
        self.bias.copy_(-_mean / (_std + epsilon))
        return self.forward(inputs, input_lengths)

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


Measured latency_ms: 0.109474