# AOT ID: ['0_forward']
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_4/inductor_cache/x3/cx3gmkffawzeqa42dt6imkp3xazph6g2avzihibptifln6prpugc.py
# Topologically Sorted Source Nodes: [parent_gating_1, parent_density_1], Original ATen: [aten.rsub, aten.clone]
# Source node to ATen node mapping:
#   parent_density_1 => clone_1
#   parent_gating_1 => sub
# Graph fragment:
#   %sub : [num_users=2] = call_function[target=torch.ops.aten.sub.Tensor](args = (1, %select), kwargs = {})
#   %clone_1 : [num_users=2] = call_function[target=torch.ops.aten.clone.default](args = (%select_7,), kwargs = {})
triton_poi_fused_clone_rsub_0 = async_compile.triton('triton_poi_fused_clone_rsub_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.pointwise(
    size_hints=[4], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_clone_rsub_0', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 2, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', '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},
    min_elem_per_thread=0
)
@triton.jit
def triton_poi_fused_clone_rsub_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1, 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_ptr0 + (x0), xmask)
    tmp1 = tl.load(in_ptr1 + (0))
    tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
    tmp3 = tmp0 + tmp2
    tmp4 = tl.sigmoid(tmp3)
    tmp5 = 1.0
    tmp6 = tmp5 - tmp4
    tmp7 = tl.full([1], 0, tl.int32)
    tmp8 = tl.full([1], 1, tl.int32)
    tmp9 = tmp7 == tmp8
    tmp10 = tmp5 * tmp4
    tmp11 = tl.where(tmp9, tmp10, tmp5)
    tl.store(out_ptr0 + (x0), tmp6, xmask)
    tl.store(out_ptr1 + (x0), tmp11, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_4/inductor_cache/eh/cehht3hukllnyz5egesrxano4ecw2ivhjbkffeiegza5yfene7cw.py
# Topologically Sorted Source Nodes: [matmul_1], Original ATen: [aten.clone, aten._unsafe_view]
# Source node to ATen node mapping:
#   matmul_1 => clone_2, view
# Graph fragment:
#   %clone_2 : [num_users=1] = call_function[target=torch.ops.aten.clone.default](args = (%primals_4,), kwargs = {memory_format: torch.contiguous_format})
#   %view : [num_users=2] = call_function[target=torch.ops.aten.reshape.default](args = (%clone_2, [16, 2]), kwargs = {})
triton_poi_fused__unsafe_view_clone_1 = async_compile.triton('triton_poi_fused__unsafe_view_clone_1', '''
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.pointwise(
    size_hints=[16, 2], tile_hint=TileHint.SQUARE,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: 'i32', 3: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused__unsafe_view_clone_1', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 1, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', '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},
    min_elem_per_thread=0
)
@triton.jit
def triton_poi_fused__unsafe_view_clone_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK : tl.constexpr, XBLOCK : tl.constexpr):
    ynumel = 16
    xnumel = 2
    yoffset = tl.program_id(1) * YBLOCK
    yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
    ymask = yindex < ynumel
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    x1 = xindex
    y0 = yindex
    tmp0 = tl.load(in_ptr0 + ((4*x1) + (8*(y0 // 4)) + (y0 % 4)), xmask & ymask, eviction_policy='evict_last')
    tl.store(out_ptr0 + (x1 + (2*y0)), tmp0, xmask & ymask)
''', device_str='cuda')


# kernel path: runs/run_shard_4/inductor_cache/qf/cqfxyshap2we5yxv54i45cr3xfqlgd5j2usidttyul5fjvhpcq4n.py
# Topologically Sorted Source Nodes: [node_densities, parent_density, mul, setitem, mul_1, setitem_1], Original ATen: [aten.ones, aten.clone, aten.mul, aten.copy]
# Source node to ATen node mapping:
#   mul => mul
#   mul_1 => mul_1
#   node_densities => full_default
#   parent_density => clone
#   setitem => copy
#   setitem_1 => copy_1
# Graph fragment:
#   %full_default : [num_users=3] = call_function[target=torch.ops.aten.full.default](args = ([4, 3], 1), kwargs = {dtype: torch.float32, layout: torch.strided, device: cuda:0, pin_memory: False})
#   %clone : [num_users=1] = call_function[target=torch.ops.aten.clone.default](args = (%select_1,), kwargs = {})
#   %mul : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%clone, %select), kwargs = {})
#   %copy : [num_users=1] = call_function[target=torch.ops.aten.copy.default](args = (%select_2, %mul), kwargs = {})
#   %select_scatter_default : [num_users=3] = call_function[target=torch.ops.aten.select_scatter.default](args = (%full_default, %copy, 1, 1), kwargs = {})
#   %mul_1 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%clone_1, %sub), kwargs = {})
#   %copy_1 : [num_users=1] = call_function[target=torch.ops.aten.copy.default](args = (%select_9, %mul_1), kwargs = {})
#   %select_scatter_default_1 : [num_users=1] = call_function[target=torch.ops.aten.select_scatter.default](args = (%select_scatter_default, %copy_1, 1, 2), kwargs = {})
triton_poi_fused_clone_copy_mul_ones_2 = async_compile.triton('triton_poi_fused_clone_copy_mul_ones_2', '''
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.pointwise(
    size_hints=[16], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: '*fp32', 5: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3, 4), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_clone_copy_mul_ones_2', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 4, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', '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},
    min_elem_per_thread=0
)
@triton.jit
def triton_poi_fused_clone_copy_mul_ones_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, xnumel, XBLOCK : tl.constexpr):
    xnumel = 12
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 3
    x1 = (xindex // 3)
    x2 = xindex
    tmp3 = tl.load(in_ptr0 + (x1), xmask, eviction_policy='evict_last')
    tmp4 = tl.load(in_ptr1 + (x1), xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr2 + (x1), xmask, eviction_policy='evict_last')
    tmp9 = tl.load(in_ptr3 + (0))
    tmp10 = tl.broadcast_to(tmp9, [XBLOCK])
    tmp0 = x0
    tmp1 = tl.full([1], 2, tl.int32)
    tmp2 = tmp0 == tmp1
    tmp5 = tmp3 * tmp4
    tmp6 = tl.full([1], 1, tl.int32)
    tmp7 = tmp0 == tmp6
    tmp11 = tmp8 + tmp10
    tmp12 = tl.sigmoid(tmp11)
    tmp13 = 1.0
    tmp14 = tmp13 * tmp12
    tmp15 = tl.where(tmp7, tmp14, tmp13)
    tmp16 = tl.where(tmp2, tmp5, tmp15)
    tl.store(out_ptr0 + (x2), tmp16, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_4/inductor_cache/5z/c5zwjiibzpmewhbugl46v3cw6thrnrno5irnt3hiqfrh3x4iwghl.py
# Topologically Sorted Source Nodes: [result], Original ATen: [aten.add]
# Source node to ATen node mapping:
#   result => add_1
# Graph fragment:
#   %add_1 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%select_12, %permute_3), kwargs = {})
triton_poi_fused_add_3 = async_compile.triton('triton_poi_fused_add_3', '''
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.pointwise(
    size_hints=[4, 4], tile_hint=TileHint.SQUARE,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: 'i32', 3: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_add_3', 'mutated_arg_names': ['in_out_ptr0'], 'no_x_dim': False, 'num_load': 2, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', '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},
    min_elem_per_thread=0
)
@triton.jit
def triton_poi_fused_add_3(in_out_ptr0, in_ptr0, ynumel, xnumel, YBLOCK : tl.constexpr, XBLOCK : tl.constexpr):
    ynumel = 4
    xnumel = 4
    yoffset = tl.program_id(1) * YBLOCK
    yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
    ymask = yindex < ynumel
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    x1 = xindex
    y0 = yindex
    tmp0 = tl.load(in_out_ptr0 + (x1 + (4*y0)), xmask & ymask)
    tmp1 = tl.load(in_ptr0 + (y0 + (4*x1)), xmask & ymask)
    tmp2 = tmp0 + tmp1
    tl.store(in_out_ptr0 + (x1 + (4*y0)), tmp2, xmask & ymask)
''', device_str='cuda')


async_compile.wait(globals())
del async_compile

def call(args):
    primals_1, primals_2, primals_3, primals_4, primals_5 = args
    args.clear()
    assert_size_stride(primals_1, (4, 1), (1, 4))
    assert_size_stride(primals_2, (4, 4), (4, 1))
    assert_size_stride(primals_3, (1, ), (1, ))
    assert_size_stride(primals_4, (4, 4, 2), (8, 1, 4))
    assert_size_stride(primals_5, (4, 2), (2, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
        # Topologically Sorted Source Nodes: [matmul], Original ATen: [aten.mm]
        extern_kernels.mm(primals_2, primals_1, out=buf0)
        del primals_1
        buf1 = empty_strided_cuda((4, ), (1, ), torch.float32)
        buf2 = empty_strided_cuda((4, ), (1, ), torch.float32)
        # Topologically Sorted Source Nodes: [parent_gating_1, parent_density_1], Original ATen: [aten.rsub, aten.clone]
        stream0 = get_raw_stream(0)
        triton_poi_fused_clone_rsub_0.run(buf0, primals_3, buf1, buf2, 4, grid=grid(4), stream=stream0)
        buf3 = empty_strided_cuda((16, 2), (2, 1), torch.float32)
        # Topologically Sorted Source Nodes: [matmul_1], Original ATen: [aten.clone, aten._unsafe_view]
        triton_poi_fused__unsafe_view_clone_1.run(primals_4, buf3, 16, 2, grid=grid(16, 2), stream=stream0)
        del primals_4
        buf4 = empty_strided_cuda((4, 3), (3, 1), torch.float32)
        # Topologically Sorted Source Nodes: [node_densities, parent_density, mul, setitem, mul_1, setitem_1], Original ATen: [aten.ones, aten.clone, aten.mul, aten.copy]
        triton_poi_fused_clone_copy_mul_ones_2.run(buf2, buf1, buf0, primals_3, buf4, 12, grid=grid(12), stream=stream0)
        buf5 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [matmul_1], Original ATen: [aten.mm]
        extern_kernels.mm(buf3, reinterpret_tensor(buf4, (2, 4), (1, 3), 1), out=buf5)
        buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [matmul_2], Original ATen: [aten.mm]
        extern_kernels.mm(primals_5, reinterpret_tensor(buf4, (2, 4), (1, 3), 1), out=buf6)
        buf7 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
        # Topologically Sorted Source Nodes: [matmul_3], Original ATen: [aten.bmm]
        extern_kernels.bmm(reinterpret_tensor(buf5, (4, 4, 4), (1, 16, 4), 0), reinterpret_tensor(primals_2, (4, 4, 1), (4, 1, 1), 0), out=buf7)
        del buf5
        buf8 = reinterpret_tensor(buf7, (4, 4), (4, 1), 0); del buf7  # reuse
        # Topologically Sorted Source Nodes: [result], Original ATen: [aten.add]
        triton_poi_fused_add_3.run(buf8, buf6, 4, 4, grid=grid(4, 4), stream=stream0)
        del buf6
    return (buf8, primals_2, primals_3, buf0, buf1, buf2, reinterpret_tensor(primals_5, (2, 4), (1, 2), 0), reinterpret_tensor(buf4, (4, 2), (3, 1), 1), reinterpret_tensor(buf3, (2, 16), (1, 2), 0), )


def benchmark_compiled_module(times=10, repeat=10):
    from torch._dynamo.testing import rand_strided
    from torch._inductor.utils import print_performance
    primals_1 = rand_strided((4, 1), (1, 4), device='cuda:0', dtype=torch.float32)
    primals_2 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    primals_3 = rand_strided((1, ), (1, ), device='cuda:0', dtype=torch.float32)
    primals_4 = rand_strided((4, 4, 2), (8, 1, 4), device='cuda:0', dtype=torch.float32)
    primals_5 = rand_strided((4, 2), (2, 1), device='cuda:0', dtype=torch.float32)
    fn = lambda: call([primals_1, primals_2, primals_3, primals_4, primals_5])
    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 numpy
import torch


class HME(torch.nn.Module):

    def __init__(self, in_features, out_features, depth, projection='linear'):
        super(HME, self).__init__()
        self.proj = projection
        self.depth = depth
        self.in_features = in_features
        self.out_features = out_features
        self.n_leaf = int(2 ** depth)
        self.gate_count = int(self.n_leaf - 1)
        self.gw = torch.nn.Parameter(torch.nn.init.kaiming_normal_(torch.
            empty(self.gate_count, in_features), nonlinearity='sigmoid').t())
        self.gb = torch.nn.Parameter(torch.zeros(self.gate_count))
        if self.proj == 'linear':
            self.pw = torch.nn.init.kaiming_normal_(torch.empty(
                out_features * self.n_leaf, in_features), nonlinearity='linear'
                )
            self.pw = torch.nn.Parameter(self.pw.reshape(out_features, self
                .n_leaf, in_features).permute(0, 2, 1))
            self.pb = torch.nn.Parameter(torch.zeros(out_features, self.n_leaf)
                )
        elif self.proj == 'constant':
            self.z = torch.nn.Parameter(torch.randn(out_features, self.n_leaf))

    def forward(self, x):
        node_densities = self.node_densities(x)
        leaf_probs = node_densities[:, -self.n_leaf:].t()
        if self.proj == 'linear':
            gated_projection = torch.matmul(self.pw, leaf_probs).permute(2,
                0, 1)
            gated_bias = torch.matmul(self.pb, leaf_probs).permute(1, 0)
            result = torch.matmul(gated_projection, x.reshape(-1, self.
                in_features, 1))[:, :, 0] + gated_bias
        elif self.proj == 'constant':
            result = torch.matmul(self.z, leaf_probs).permute(1, 0)
        return result

    def node_densities(self, x):
        gatings = self.gatings(x)
        node_densities = torch.ones(x.shape[0], 2 ** (self.depth + 1) - 1,
            device=x.device)
        it = 1
        for d in range(1, self.depth + 1):
            for i in range(2 ** d):
                parent_index = (it + 1) // 2 - 1
                child_way = (it + 1) % 2
                if child_way == 0:
                    parent_gating = gatings[:, parent_index]
                else:
                    parent_gating = 1 - gatings[:, parent_index]
                parent_density = node_densities[:, parent_index].clone()
                node_densities[:, it] = parent_density * parent_gating
                it += 1
        return node_densities

    def gatings(self, x):
        return torch.sigmoid(torch.add(torch.matmul(x, self.gw), self.gb))

    def total_path_value(self, z, index, level=None):
        gatings = self.gatings(z)
        gateways = numpy.binary_repr(index, width=self.depth)
        L = 0.0
        current = 0
        if level is None:
            level = self.depth
        for i in range(level):
            if int(gateways[i]) == 0:
                L += gatings[:, current].mean()
                current = 2 * current + 1
            else:
                L += (1 - gatings[:, current]).mean()
                current = 2 * current + 2
        return L

    def extra_repr(self):
        return 'in_features=%d, out_features=%d, depth=%d, projection=%s' % (
            self.in_features, self.out_features, self.depth, self.proj)


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


def get_init_inputs():
    return [[], {'in_features': 4, 'out_features': 4, 'depth': 1}]

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
import numpy
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_clone_rsub_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
    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_ptr0 + x0, xmask)
    tmp1 = tl.load(in_ptr1 + 0)
    tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
    tmp3 = tmp0 + tmp2
    tmp4 = tl.sigmoid(tmp3)
    tmp5 = 1.0
    tmp6 = tmp5 - tmp4
    tmp7 = tl.full([1], 0, tl.int32)
    tmp8 = tl.full([1], 1, tl.int32)
    tmp9 = tmp7 == tmp8
    tmp10 = tmp5 * tmp4
    tmp11 = tl.where(tmp9, tmp10, tmp5)
    tl.store(out_ptr0 + x0, tmp6, xmask)
    tl.store(out_ptr1 + x0, tmp11, xmask)


@triton.jit
def triton_poi_fused__unsafe_view_clone_1(in_ptr0, out_ptr0, ynumel, xnumel,
    YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
    ynumel = 16
    xnumel = 2
    yoffset = tl.program_id(1) * YBLOCK
    yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
    ymask = yindex < ynumel
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    x1 = xindex
    y0 = yindex
    tmp0 = tl.load(in_ptr0 + (4 * x1 + 8 * (y0 // 4) + y0 % 4), xmask &
        ymask, eviction_policy='evict_last')
    tl.store(out_ptr0 + (x1 + 2 * y0), tmp0, xmask & ymask)


@triton.jit
def triton_poi_fused_clone_copy_mul_ones_2(in_ptr0, in_ptr1, in_ptr2,
    in_ptr3, out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 12
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 3
    x1 = xindex // 3
    x2 = xindex
    tmp3 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
    tmp4 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
    tmp9 = tl.load(in_ptr3 + 0)
    tmp10 = tl.broadcast_to(tmp9, [XBLOCK])
    tmp0 = x0
    tmp1 = tl.full([1], 2, tl.int32)
    tmp2 = tmp0 == tmp1
    tmp5 = tmp3 * tmp4
    tmp6 = tl.full([1], 1, tl.int32)
    tmp7 = tmp0 == tmp6
    tmp11 = tmp8 + tmp10
    tmp12 = tl.sigmoid(tmp11)
    tmp13 = 1.0
    tmp14 = tmp13 * tmp12
    tmp15 = tl.where(tmp7, tmp14, tmp13)
    tmp16 = tl.where(tmp2, tmp5, tmp15)
    tl.store(out_ptr0 + x2, tmp16, xmask)


@triton.jit
def triton_poi_fused_add_3(in_out_ptr0, in_ptr0, ynumel, xnumel, YBLOCK: tl
    .constexpr, XBLOCK: tl.constexpr):
    ynumel = 4
    xnumel = 4
    yoffset = tl.program_id(1) * YBLOCK
    yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
    ymask = yindex < ynumel
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    x1 = xindex
    y0 = yindex
    tmp0 = tl.load(in_out_ptr0 + (x1 + 4 * y0), xmask & ymask)
    tmp1 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask)
    tmp2 = tmp0 + tmp1
    tl.store(in_out_ptr0 + (x1 + 4 * y0), tmp2, xmask & ymask)


def call(args):
    primals_1, primals_2, primals_3, primals_4, primals_5 = args
    args.clear()
    assert_size_stride(primals_1, (4, 1), (1, 4))
    assert_size_stride(primals_2, (4, 4), (4, 1))
    assert_size_stride(primals_3, (1,), (1,))
    assert_size_stride(primals_4, (4, 4, 2), (8, 1, 4))
    assert_size_stride(primals_5, (4, 2), (2, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
        extern_kernels.mm(primals_2, primals_1, out=buf0)
        del primals_1
        buf1 = empty_strided_cuda((4,), (1,), torch.float32)
        buf2 = empty_strided_cuda((4,), (1,), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_clone_rsub_0[grid(4)](buf0, primals_3, buf1, buf2,
            4, XBLOCK=4, num_warps=1, num_stages=1)
        buf3 = empty_strided_cuda((16, 2), (2, 1), torch.float32)
        triton_poi_fused__unsafe_view_clone_1[grid(16, 2)](primals_4, buf3,
            16, 2, XBLOCK=2, YBLOCK=16, num_warps=1, num_stages=1)
        del primals_4
        buf4 = empty_strided_cuda((4, 3), (3, 1), torch.float32)
        triton_poi_fused_clone_copy_mul_ones_2[grid(12)](buf2, buf1, buf0,
            primals_3, buf4, 12, XBLOCK=16, num_warps=1, num_stages=1)
        buf5 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
        extern_kernels.mm(buf3, reinterpret_tensor(buf4, (2, 4), (1, 3), 1),
            out=buf5)
        buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        extern_kernels.mm(primals_5, reinterpret_tensor(buf4, (2, 4), (1, 3
            ), 1), out=buf6)
        buf7 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
        extern_kernels.bmm(reinterpret_tensor(buf5, (4, 4, 4), (1, 16, 4), 
            0), reinterpret_tensor(primals_2, (4, 4, 1), (4, 1, 1), 0), out
            =buf7)
        del buf5
        buf8 = reinterpret_tensor(buf7, (4, 4), (4, 1), 0)
        del buf7
        triton_poi_fused_add_3[grid(4, 4)](buf8, buf6, 4, 4, XBLOCK=4,
            YBLOCK=4, num_warps=1, num_stages=1)
        del buf6
    return buf8, primals_2, primals_3, buf0, buf1, buf2, reinterpret_tensor(
        primals_5, (2, 4), (1, 2), 0), reinterpret_tensor(buf4, (4, 2), (3,
        1), 1), reinterpret_tensor(buf3, (2, 16), (1, 2), 0)


class HMENew(torch.nn.Module):

    def __init__(self, in_features, out_features, depth, projection='linear'):
        super(HMENew, self).__init__()
        self.proj = projection
        self.depth = depth
        self.in_features = in_features
        self.out_features = out_features
        self.n_leaf = int(2 ** depth)
        self.gate_count = int(self.n_leaf - 1)
        self.gw = torch.nn.Parameter(torch.nn.init.kaiming_normal_(torch.
            empty(self.gate_count, in_features), nonlinearity='sigmoid').t())
        self.gb = torch.nn.Parameter(torch.zeros(self.gate_count))
        if self.proj == 'linear':
            self.pw = torch.nn.init.kaiming_normal_(torch.empty(
                out_features * self.n_leaf, in_features), nonlinearity='linear'
                )
            self.pw = torch.nn.Parameter(self.pw.reshape(out_features, self
                .n_leaf, in_features).permute(0, 2, 1))
            self.pb = torch.nn.Parameter(torch.zeros(out_features, self.n_leaf)
                )
        elif self.proj == 'constant':
            self.z = torch.nn.Parameter(torch.randn(out_features, self.n_leaf))

    def node_densities(self, x):
        gatings = self.gatings(x)
        node_densities = torch.ones(x.shape[0], 2 ** (self.depth + 1) - 1,
            device=x.device)
        it = 1
        for d in range(1, self.depth + 1):
            for i in range(2 ** d):
                parent_index = (it + 1) // 2 - 1
                child_way = (it + 1) % 2
                if child_way == 0:
                    parent_gating = gatings[:, parent_index]
                else:
                    parent_gating = 1 - gatings[:, parent_index]
                parent_density = node_densities[:, parent_index].clone()
                node_densities[:, it] = parent_density * parent_gating
                it += 1
        return node_densities

    def gatings(self, x):
        return torch.sigmoid(torch.add(torch.matmul(x, self.gw), self.gb))

    def total_path_value(self, z, index, level=None):
        gatings = self.gatings(z)
        gateways = numpy.binary_repr(index, width=self.depth)
        L = 0.0
        current = 0
        if level is None:
            level = self.depth
        for i in range(level):
            if int(gateways[i]) == 0:
                L += gatings[:, current].mean()
                current = 2 * current + 1
            else:
                L += (1 - gatings[:, current]).mean()
                current = 2 * current + 2
        return L

    def extra_repr(self):
        return 'in_features=%d, out_features=%d, depth=%d, projection=%s' % (
            self.in_features, self.out_features, self.depth, self.proj)

    def forward(self, input_0):
        primals_1 = self.gw
        primals_3 = self.gb
        primals_4 = self.pw
        primals_5 = self.pb
        primals_2 = input_0
        output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
        return output[0]
