# AOT ID: ['0_inference']
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_1/inductor_cache/ox/coxuvkcjxjrjqpijd7rdotbhq2tyyemxh32vvfqxztmetqjicteg.py
# Topologically Sorted Source Nodes: [conv2d], Original ATen: [aten.convolution]
# Source node to ATen node mapping:
#   conv2d => convolution
# Graph fragment:
#   %convolution : [num_users=1] = call_function[target=torch.ops.aten.convolution.default](args = (%arg0_1, %arg1_1, None, [1, 1], [1, 1], [1, 1], False, [0, 0], 4), kwargs = {})
triton_poi_fused_convolution_0 = async_compile.triton('triton_poi_fused_convolution_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=[16, 16], tile_hint=TileHint.SQUARE,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: 'i32', 3: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=90, major=9, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=132), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_convolution_0', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 1, 'num_reduction': 0, 'backend_hash': 'B098E03CDA7B8ADC90DAFFDF24A2956451D1B13F297756A5DCC209498AA53705', '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_convolution_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK : tl.constexpr, XBLOCK : tl.constexpr):
    ynumel = 16
    xnumel = 16
    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
    x2 = xindex
    y3 = yindex
    y0 = yindex % 4
    y1 = (yindex // 4)
    tmp0 = tl.load(in_ptr0 + (x2 + (16*y3)), xmask & ymask)
    tl.store(out_ptr0 + (y0 + (4*x2) + (64*y1)), tmp0, xmask & ymask)
''', device_str='cuda')


# kernel path: runs/run_shard_1/inductor_cache/oa/coaribucmmh3awhduh4rmgeb2azcbmc2flvje6jwwwsoobc4c342.py
# Topologically Sorted Source Nodes: [conv2d_1, Qtilde_2], Original ATen: [aten.convolution]
# Source node to ATen node mapping:
#   Qtilde_2 => convolution_2
#   conv2d_1 => convolution_1
# Graph fragment:
#   %convolution_1 : [num_users=1] = call_function[target=torch.ops.aten.convolution.default](args = (%arg2_1, %arg3_1, None, [1, 1], [1, 1], [1, 1], False, [0, 0], 4), kwargs = {})
#   %convolution_2 : [num_users=1] = call_function[target=torch.ops.aten.convolution.default](args = (%arg2_1, %arg5_1, None, [1, 1], [1, 1], [1, 1], False, [0, 0], 4), kwargs = {})
triton_poi_fused_convolution_1 = async_compile.triton('triton_poi_fused_convolution_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, 16], tile_hint=TileHint.DEFAULT,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: 'i32', 4: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=90, major=9, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=132), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3, 4), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_convolution_1', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 1, 'num_reduction': 0, 'backend_hash': 'B098E03CDA7B8ADC90DAFFDF24A2956451D1B13F297756A5DCC209498AA53705', '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_convolution_1(in_ptr0, out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK : tl.constexpr, XBLOCK : tl.constexpr):
    ynumel = 16
    xnumel = 16
    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
    x2 = xindex
    y3 = yindex
    y0 = yindex % 4
    y1 = (yindex // 4)
    tmp0 = tl.load(in_ptr0 + (x2 + (16*y3)), xmask & ymask)
    tl.store(out_ptr0 + (y0 + (4*x2) + (64*y1)), tmp0, xmask & ymask)
    tl.store(out_ptr1 + (y0 + (4*x2) + (64*y1)), tmp0, xmask & ymask)
''', device_str='cuda')


# kernel path: runs/run_shard_1/inductor_cache/oe/coelm6cq7x2kepyqo7tkmpwdboanfkmykt5gik2rl7cluqksji66.py
# Topologically Sorted Source Nodes: [Qj, Qj_1, Qtilde], Original ATen: [aten.mul, aten.sum]
# Source node to ATen node mapping:
#   Qj => mul
#   Qj_1 => mul_1
#   Qtilde => sum_1
# Graph fragment:
#   %mul : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%unsqueeze_1, %unsqueeze_2), kwargs = {})
#   %mul_1 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%mul, %arg4_1), kwargs = {})
#   %sum_1 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%mul_1, [3]), kwargs = {})
triton_per_fused_mul_sum_2 = async_compile.triton('triton_per_fused_mul_sum_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.persistent_reduction(
    size_hints=[1024, 8],
    reduction_hint=ReductionHint.DEFAULT,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: '*fp32', 5: 'i32', 6: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=90, major=9, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=132), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3, 4, 5), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_per_fused_mul_sum_2', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 4, 'num_reduction': 1, 'backend_hash': 'B098E03CDA7B8ADC90DAFFDF24A2956451D1B13F297756A5DCC209498AA53705', '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}
)
@triton.jit
def triton_per_fused_mul_sum_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0, xnumel, rnumel, XBLOCK : tl.constexpr):
    xnumel = 1024
    rnumel = 8
    RBLOCK: tl.constexpr = 8
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    rindex = tl.arange(0, RBLOCK)[None, :]
    roffset = 0
    rmask = tl.full([XBLOCK, RBLOCK], True, tl.int1)
    r4 = rindex
    x1 = (xindex // 4) % 16
    x2 = (xindex // 64) % 4
    x3 = (xindex // 256)
    x5 = (xindex // 4)
    x6 = xindex % 64
    x7 = xindex
    tmp0 = tl.load(in_ptr0 + (r4 + (8*x2) + (32*x1) + (512*x3)), xmask, eviction_policy='evict_last', other=0.0)
    tmp1 = tl.load(in_ptr1 + (x5), xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr2 + (r4 + (8*x6) + (512*x3)), xmask, eviction_policy='evict_last', other=0.0)
    tmp10 = tl.load(in_ptr3 + (r4), None, eviction_policy='evict_last')
    tmp2 = tmp0 - tmp1
    tmp3 = tmp2 * tmp2
    tmp4 = 0.125
    tmp5 = tmp3 * tmp4
    tmp6 = -tmp5
    tmp7 = tl_math.exp(tmp6)
    tmp9 = tmp7 * tmp8
    tmp11 = tmp9 * tmp10
    tmp12 = tl.broadcast_to(tmp11, [XBLOCK, RBLOCK])
    tmp14 = tl.where(xmask, tmp12, 0)
    tmp15 = tl.sum(tmp14, 1)[:, None]
    tl.store(out_ptr0 + (x7), tmp15, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_1/inductor_cache/bh/cbhvjus77qwpgzwut2mamf5b47tvjlkchxobjkyyrq3r7kkktri5.py
# Topologically Sorted Source Nodes: [sub, pow_1, K, neg, K_1, norm_weight, norm_weight_1], Original ATen: [aten.sub, aten.pow, aten.div, aten.neg, aten.exp, aten.mul, aten.sum]
# Source node to ATen node mapping:
#   K => div
#   K_1 => exp
#   neg => neg
#   norm_weight => mul_2
#   norm_weight_1 => sum_2
#   pow_1 => pow_1
#   sub => sub
# Graph fragment:
#   %sub : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%view, %unsqueeze), kwargs = {})
#   %pow_1 : [num_users=1] = call_function[target=torch.ops.aten.pow.Tensor_Scalar](args = (%sub, 2), kwargs = {})
#   %div : [num_users=1] = call_function[target=torch.ops.aten.div.Tensor](args = (%pow_1, 8.0), kwargs = {})
#   %neg : [num_users=1] = call_function[target=torch.ops.aten.neg.default](args = (%div,), kwargs = {})
#   %exp : [num_users=2] = call_function[target=torch.ops.aten.exp.default](args = (%neg,), kwargs = {})
#   %mul_2 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%exp, %squeeze), kwargs = {})
#   %sum_2 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%mul_2, [2]), kwargs = {})
triton_per_fused_div_exp_mul_neg_pow_sub_sum_3 = async_compile.triton('triton_per_fused_div_exp_mul_neg_pow_sub_sum_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.persistent_reduction(
    size_hints=[256, 8],
    reduction_hint=ReductionHint.DEFAULT,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: 'i32', 5: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=90, major=9, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=132), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3, 4), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_per_fused_div_exp_mul_neg_pow_sub_sum_3', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 3, 'num_reduction': 1, 'backend_hash': 'B098E03CDA7B8ADC90DAFFDF24A2956451D1B13F297756A5DCC209498AA53705', '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}
)
@triton.jit
def triton_per_fused_div_exp_mul_neg_pow_sub_sum_3(in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, rnumel, XBLOCK : tl.constexpr):
    xnumel = 256
    rnumel = 8
    RBLOCK: tl.constexpr = 8
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    rindex = tl.arange(0, RBLOCK)[None, :]
    roffset = 0
    rmask = tl.full([XBLOCK, RBLOCK], True, tl.int1)
    r3 = rindex
    x0 = xindex % 16
    x1 = (xindex // 16) % 4
    x2 = (xindex // 64)
    x4 = xindex
    tmp0 = tl.load(in_ptr0 + (r3 + (8*x1) + (32*x0) + (512*x2)), xmask, other=0.0)
    tmp1 = tl.load(in_ptr1 + (x4), xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr2 + (r3), None, eviction_policy='evict_last')
    tmp2 = tmp0 - tmp1
    tmp3 = tmp2 * tmp2
    tmp4 = 0.125
    tmp5 = tmp3 * tmp4
    tmp6 = -tmp5
    tmp7 = tl_math.exp(tmp6)
    tmp9 = tmp7 * tmp8
    tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
    tmp12 = tl.where(xmask, tmp10, 0)
    tmp13 = tl.sum(tmp12, 1)[:, None]
    tl.store(out_ptr0 + (x4), tmp13, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_1/inductor_cache/au/cauxalw57ngmfac2gzeotsz5bm26ucwwnormbypyayjjedwj7cs5.py
# Topologically Sorted Source Nodes: [new_ones], Original ATen: [aten.new_ones]
# Source node to ATen node mapping:
#   new_ones => full_default
# Graph fragment:
#   %full_default : [num_users=1] = call_function[target=torch.ops.aten.full.default](args = ([4, 4, 4, 4], 1), kwargs = {dtype: torch.float32, layout: torch.strided, device: cuda:0, pin_memory: False})
triton_poi_fused_new_ones_4 = async_compile.triton('triton_poi_fused_new_ones_4', '''
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=[256], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=90, major=9, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=132), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_new_ones_4', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 0, 'num_reduction': 0, 'backend_hash': 'B098E03CDA7B8ADC90DAFFDF24A2956451D1B13F297756A5DCC209498AA53705', '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_new_ones_4(out_ptr0, xnumel, XBLOCK : tl.constexpr):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = 1.0
    tl.store(out_ptr0 + (x0), tmp0, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_1/inductor_cache/hh/chhefgnjetcueppfj4sysb4wln6qp32onc24s6cdnhlyzt54bx4q.py
# Topologically Sorted Source Nodes: [Qtilde_1], Original ATen: [aten.div]
# Source node to ATen node mapping:
#   Qtilde_1 => div_1
# Graph fragment:
#   %div_1 : [num_users=1] = call_function[target=torch.ops.aten.div.Tensor](args = (%sum_1, %unsqueeze_3), kwargs = {})
triton_poi_fused_div_5 = async_compile.triton('triton_poi_fused_div_5', '''
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, 64], tile_hint=TileHint.DEFAULT,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: 'i32', 4: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=90, major=9, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=132), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3, 4), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_div_5', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 2, 'num_reduction': 0, 'backend_hash': 'B098E03CDA7B8ADC90DAFFDF24A2956451D1B13F297756A5DCC209498AA53705', '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_div_5(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel, YBLOCK : tl.constexpr, XBLOCK : tl.constexpr):
    ynumel = 16
    xnumel = 64
    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
    x2 = xindex % 16
    x3 = (xindex // 16)
    y4 = yindex
    x5 = xindex
    y0 = yindex % 4
    y1 = (yindex // 4)
    tmp0 = tl.load(in_ptr0 + (x3 + (4*x2) + (64*y4)), xmask & ymask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr1 + (x2 + (16*y4)), xmask & ymask, eviction_policy='evict_last')
    tmp2 = tmp0 / tmp1
    tl.store(out_ptr0 + (y0 + (5*x5) + (320*y1)), tmp2, xmask & ymask)
''', device_str='cuda')


# kernel path: runs/run_shard_1/inductor_cache/7c/c7cgxeuirb3emknpobtc6zjuworhtpthb5urkgih3tvtsrov2d2c.py
# Topologically Sorted Source Nodes: [Qtilde_4], Original ATen: [aten.cat]
# Source node to ATen node mapping:
#   Qtilde_4 => cat
# Graph fragment:
#   %cat : [num_users=1] = call_function[target=torch.ops.aten.cat.default](args = ([%div_1, %unsqueeze_4], 1), kwargs = {})
triton_poi_fused_cat_6 = async_compile.triton('triton_poi_fused_cat_6', '''
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=[256], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=90, major=9, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=132), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 3), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_cat_6', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 2, 'num_reduction': 0, 'backend_hash': 'B098E03CDA7B8ADC90DAFFDF24A2956451D1B13F297756A5DCC209498AA53705', '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_cat_6(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK : tl.constexpr):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex
    x0 = xindex % 4
    x1 = (xindex // 4) % 16
    x2 = (xindex // 64)
    tmp0 = tl.load(in_ptr0 + (x3), xmask)
    tmp1 = tl.load(in_ptr1 + (x3), xmask)
    tmp2 = tmp0 / tmp1
    tl.store(out_ptr0 + ((5*x1) + (80*x0) + (320*x2)), tmp2, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_1/inductor_cache/dv/cdvalb2fqnvytkrtqw5cehknbgtm7v3flnzdty47vhec6hjpqe6p.py
# Topologically Sorted Source Nodes: [Qtilde_4], Original ATen: [aten.cat]
# Source node to ATen node mapping:
#   Qtilde_4 => cat
# Graph fragment:
#   %cat : [num_users=1] = call_function[target=torch.ops.aten.cat.default](args = ([%div_1, %unsqueeze_4], 1), kwargs = {})
triton_poi_fused_cat_7 = async_compile.triton('triton_poi_fused_cat_7', '''
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=[32, 64], tile_hint=TileHint.SQUARE,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: 'i32', 3: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=90, major=9, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=132), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 3), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_cat_7', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 1, 'num_reduction': 0, 'backend_hash': 'B098E03CDA7B8ADC90DAFFDF24A2956451D1B13F297756A5DCC209498AA53705', '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_cat_7(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK : tl.constexpr, XBLOCK : tl.constexpr):
    ynumel = 20
    xnumel = 64
    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
    x2 = xindex
    y0 = yindex % 5
    y1 = (yindex // 5)
    y3 = yindex
    tmp0 = tl.load(in_ptr0 + (y0 + (5*x2) + (320*y1)), xmask & ymask, eviction_policy='evict_last')
    tl.store(out_ptr0 + (x2 + (64*y3)), tmp0, xmask & ymask)
''', device_str='cuda')


async_compile.wait(globals())
del async_compile

def call(args):
    arg0_1, arg1_1, arg2_1, arg3_1, arg4_1, arg5_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(arg1_1, (32, 1, 3, 3), (9, 9, 3, 1))
    assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(arg3_1, (32, 1, 3, 3), (9, 9, 3, 1))
    assert_size_stride(arg4_1, (1, 1, 1, 8, 1, 1), (8, 8, 8, 1, 1, 1))
    assert_size_stride(arg5_1, (4, 1, 3, 3), (9, 9, 3, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 1, 16, 4), torch.float32)
        # Topologically Sorted Source Nodes: [conv2d], Original ATen: [aten.convolution]
        stream0 = get_raw_stream(0)
        triton_poi_fused_convolution_0.run(arg0_1, buf0, 16, 16, grid=grid(16, 16), stream=stream0)
        # Topologically Sorted Source Nodes: [conv2d], Original ATen: [aten.convolution]
        buf1 = extern_kernels.convolution(buf0, arg1_1, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=4, bias=None)
        assert_size_stride(buf1, (4, 32, 4, 4), (512, 1, 128, 32))
        del arg1_1
        buf2 = buf0; del buf0  # reuse
        buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 1, 16, 4), torch.float32)
        # Topologically Sorted Source Nodes: [conv2d_1, Qtilde_2], Original ATen: [aten.convolution]
        triton_poi_fused_convolution_1.run(arg2_1, buf2, buf6, 16, 16, grid=grid(16, 16), stream=stream0)
        del arg2_1
        # Topologically Sorted Source Nodes: [conv2d_1], Original ATen: [aten.convolution]
        buf3 = extern_kernels.convolution(buf2, arg3_1, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=4, bias=None)
        assert_size_stride(buf3, (4, 32, 4, 4), (512, 1, 128, 32))
        del arg3_1
        buf4 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 1, 16, 4), torch.float32)
        # Topologically Sorted Source Nodes: [Qj, Qj_1, Qtilde], Original ATen: [aten.mul, aten.sum]
        triton_per_fused_mul_sum_2.run(buf1, arg0_1, buf3, arg4_1, buf4, 1024, 8, grid=grid(1024), stream=stream0)
        del buf3
        buf5 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0); del buf2  # reuse
        # Topologically Sorted Source Nodes: [sub, pow_1, K, neg, K_1, norm_weight, norm_weight_1], Original ATen: [aten.sub, aten.pow, aten.div, aten.neg, aten.exp, aten.mul, aten.sum]
        triton_per_fused_div_exp_mul_neg_pow_sub_sum_3.run(buf1, arg0_1, arg4_1, buf5, 256, 8, grid=grid(256), stream=stream0)
        del arg0_1
        del arg4_1
        del buf1
        # Topologically Sorted Source Nodes: [Qtilde_2], Original ATen: [aten.convolution]
        buf7 = extern_kernels.convolution(buf6, arg5_1, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=4, bias=None)
        assert_size_stride(buf7, (4, 4, 4, 4), (64, 1, 16, 4))
        buf8 = buf6; del buf6  # reuse
        # Topologically Sorted Source Nodes: [new_ones], Original ATen: [aten.new_ones]
        triton_poi_fused_new_ones_4.run(buf8, 256, grid=grid(256), stream=stream0)
        # Topologically Sorted Source Nodes: [new_ones, norm_weight_2], Original ATen: [aten.new_ones, aten.convolution]
        buf9 = extern_kernels.convolution(buf8, arg5_1, stride=(1, 1), padding=(1, 1), dilation=(1, 1), transposed=False, output_padding=(0, 0), groups=4, bias=None)
        assert_size_stride(buf9, (4, 4, 4, 4), (64, 1, 16, 4))
        del arg5_1
        del buf8
        buf12 = empty_strided_cuda((4, 5, 4, 4, 4), (320, 1, 80, 20, 5), torch.float32)
        buf10 = reinterpret_tensor(buf12, (4, 4, 4, 4, 4), (320, 1, 80, 20, 5), 0)  # alias
        # Topologically Sorted Source Nodes: [Qtilde_1], Original ATen: [aten.div]
        triton_poi_fused_div_5.run(buf4, buf5, buf10, 16, 64, grid=grid(16, 64), stream=stream0)
        del buf4
        del buf5
        buf11 = reinterpret_tensor(buf12, (4, 1, 4, 4, 4), (320, 1, 80, 20, 5), 4)  # alias
        # Topologically Sorted Source Nodes: [Qtilde_4], Original ATen: [aten.cat]
        triton_poi_fused_cat_6.run(buf7, buf9, buf11, 256, grid=grid(256), stream=stream0)
        del buf7
        del buf9
        buf13 = empty_strided_cuda((4, 5, 4, 4, 4), (320, 64, 16, 4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [Qtilde_4], Original ATen: [aten.cat]
        triton_poi_fused_cat_7.run(buf12, buf13, 20, 64, grid=grid(20, 64), stream=stream0)
        del buf10
        del buf11
        del buf12
    return (buf13, )


def benchmark_compiled_module(times=10, repeat=10):
    from torch._dynamo.testing import rand_strided
    from torch._inductor.utils import print_performance
    arg0_1 = rand_strided((4, 4, 4, 4), (64, 16, 4, 1), device='cuda:0', dtype=torch.float32)
    arg1_1 = rand_strided((32, 1, 3, 3), (9, 9, 3, 1), device='cuda:0', dtype=torch.float32)
    arg2_1 = rand_strided((4, 4, 4, 4), (64, 16, 4, 1), device='cuda:0', dtype=torch.float32)
    arg3_1 = rand_strided((32, 1, 3, 3), (9, 9, 3, 1), device='cuda:0', dtype=torch.float32)
    arg4_1 = rand_strided((1, 1, 1, 8, 1, 1), (8, 8, 8, 1, 1, 1), device='cuda:0', dtype=torch.float32)
    arg5_1 = rand_strided((4, 1, 3, 3), (9, 9, 3, 1), device='cuda:0', dtype=torch.float32)
    fn = lambda: call([arg0_1, arg1_1, arg2_1, arg3_1, arg4_1, arg5_1])
    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 torch
import torch._C
import torch.serialization
from torch import nn
from torch.nn import Parameter


def make_onehot_kernel(kernel_size, index):
    """
    Make 2D one hot square kernel, i.e. h=w
    k[kernel_size, kernel_size] = 0 except k.view(-1)[index] = 1
    """
    kernel = torch.zeros(kernel_size, kernel_size)
    kernel.view(-1)[index] = 1
    return kernel.view(1, 1, kernel_size, kernel_size)


def make_spatial_kernel(kernel_size, bandwidth, isreshape=True):
    """
    Make 2D square smoothness kernel, i.e. h=w
    k = 1/bandwidth * exp(-(pj-pi)**2/(2*bandwidth**2))
    pj, pi = location of pixel
    """
    assert bandwidth > 0, 'bandwidth of kernel must be > 0'
    assert kernel_size % 2 != 0, 'kernel must be odd'
    p_end = (kernel_size - 1) // 2
    X = torch.linspace(-p_end, p_end, steps=kernel_size).expand(kernel_size,
        kernel_size)
    Y = X.clone().t()
    kernel = torch.exp(-(X ** 2 + Y ** 2) / (2 * bandwidth ** 2))
    kernel[p_end, p_end] = 0
    if isreshape:
        return kernel.view(1, 1, kernel_size, kernel_size)
    return kernel


class GaussianMask(nn.Module):
    """
    Break down Gaussian kernel (2nd part of appearance kernel) into CNN
    kj = (I(j) - I(i))**2/2*bandwidth**2, j#i
    but compute all maps instead of 1 kernel
    """

    def __init__(self, in_channels, kernel_size, bandwidth, iskernel=True):
        super(GaussianMask, self).__init__()
        assert bandwidth > 0, 'bandwidth of kernel must be > 0'
        assert kernel_size % 2 != 0, 'kernel must be odd'
        self.bandwidth = bandwidth
        self.iskernel = iskernel
        self.n_kernels = kernel_size ** 2 - 1
        kernel_weight = self._make_kernel_weight(in_channels, kernel_size,
            self.n_kernels)
        padding = kernel_size // 2
        self.conv = nn.Conv2d(in_channels, in_channels * self.n_kernels,
            kernel_size, stride=1, padding=padding, groups=in_channels,
            bias=False)
        self.conv.weight.requires_grad = False
        self.conv.weight.copy_(kernel_weight.view_as(self.conv.weight))

    def _make_kernel_weight(self, in_channels, kernel_size, n_kernels):
        kernel_weight = torch.zeros(in_channels, n_kernels, kernel_size,
            kernel_size)
        for i in range(n_kernels):
            index = i if i < n_kernels // 2 else i + 1
            kernel_i = make_onehot_kernel(kernel_size, index)
            kernel_weight[:, i, :] = kernel_i
        return kernel_weight

    def forward(self, X):
        batch_size, in_channels, H, W = X.shape
        Xj = self.conv(X).view(batch_size, in_channels, self.n_kernels, H, W)
        if not self.iskernel:
            return Xj
        Xi = X.unsqueeze(dim=2)
        K = (Xj - Xi) ** 2 / (2 * self.bandwidth ** 2)
        K = torch.exp(-K)
        return K


class SpatialFilter(nn.Module):
    """
    Break down spatial filter (smoothest kernel) into CNN blocks
    refer: https://arxiv.org/pdf/1210.5644.pdf
    """

    def __init__(self, n_classes, kernel_size, theta_gamma):
        super(SpatialFilter, self).__init__()
        padding = kernel_size // 2
        kernel_weight = make_spatial_kernel(kernel_size, theta_gamma)
        self.conv = nn.Conv2d(n_classes, n_classes, kernel_size, stride=1,
            padding=padding, groups=n_classes, bias=False)
        self.conv.weight.requires_grad = False
        self.conv.weight.copy_(kernel_weight)

    def forward(self, Q):
        Qtilde = self.conv(Q)
        norm_weight = self.conv(Q.new_ones(*Q.shape, requires_grad=False))
        Qtilde = Qtilde / norm_weight
        return Qtilde


class BilateralFilter(nn.Module):
    """
    Break down bilateral filter (appearance kernel) into CNN blocks
    remember that exp(-a-b) =exp(-a)*exp(b)
    """

    def __init__(self, in_channels, n_classes, kernel_size, theta_alpha,
        theta_beta):
        super(BilateralFilter, self).__init__()
        kernel_weight = make_spatial_kernel(kernel_size, theta_alpha,
            isreshape=False)
        self.spatial_weight = Parameter(kernel_weight[kernel_weight > 0].
            view(1, 1, 1, -1, 1, 1), requires_grad=False)
        self.gauss_mask_I = GaussianMask(in_channels, kernel_size, theta_beta)
        self.guass_mask_Q = GaussianMask(n_classes, kernel_size, 1,
            iskernel=False)

    def forward(self, Q, I):
        Ij = self.gauss_mask_I(I)
        Qj = self.guass_mask_Q(Q)
        Qj = Ij.unsqueeze(dim=2) * Qj.unsqueeze(dim=1)
        Qj = Qj * self.spatial_weight
        Qtilde = Qj.sum(dim=3)
        norm_weight = Ij * self.spatial_weight.squeeze(dim=2)
        norm_weight = norm_weight.sum(dim=2)
        Qtilde = Qtilde / norm_weight.unsqueeze(dim=2)
        return Qtilde


class MessagePassing(nn.Module):
    """
    Combine bilateral filter (appearance filter)
    and spatial filter to make message passing
    """

    def __init__(self, in_channels, n_classes, kernel_size=[3], theta_alpha
        =[2.0], theta_beta=[2.0], theta_gamma=[2.0]):
        super(MessagePassing, self).__init__()
        assert len(theta_alpha) == len(theta_beta
            ), 'theta_alpha and theta_beta have different lengths'
        self.n_bilaterals, self.n_spatials = len(theta_alpha), len(theta_gamma)
        for i in range(self.n_bilaterals):
            self.add_module('bilateral{}'.format(i), BilateralFilter(
                in_channels, n_classes, kernel_size[i], theta_alpha[i],
                theta_beta[i]))
        for i in range(self.n_spatials):
            self.add_module('spatial{}'.format(i), SpatialFilter(n_classes,
                kernel_size[i], theta_gamma[i]))

    def _get_child(self, child_name):
        return getattr(self, child_name)

    def forward(self, Q, I):
        filteredQ = []
        for i in range(self.n_bilaterals):
            tmp_bilateral = self._get_child('bilateral{}'.format(i))(Q, I)
            filteredQ.append(tmp_bilateral)
        for i in range(self.n_spatials):
            tmp_spatial = self._get_child('spatial{}'.format(i))(Q)
            filteredQ.append(tmp_spatial.unsqueeze(dim=1))
        Qtilde = torch.cat(filteredQ, dim=1)
        return Qtilde


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


def get_init_inputs():
    return [[], {'in_channels': 4, 'n_classes': 4}]

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.triton_helpers import math as tl_math
import torch._C
import torch.serialization
from torch import nn
from torch.nn import Parameter
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_convolution_0(in_ptr0, out_ptr0, ynumel, xnumel,
    YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
    ynumel = 16
    xnumel = 16
    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
    x2 = xindex
    y3 = yindex
    y0 = yindex % 4
    y1 = yindex // 4
    tmp0 = tl.load(in_ptr0 + (x2 + 16 * y3), xmask & ymask)
    tl.store(out_ptr0 + (y0 + 4 * x2 + 64 * y1), tmp0, xmask & ymask)


@triton.jit
def triton_poi_fused_convolution_1(in_ptr0, out_ptr0, out_ptr1, ynumel,
    xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
    ynumel = 16
    xnumel = 16
    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
    x2 = xindex
    y3 = yindex
    y0 = yindex % 4
    y1 = yindex // 4
    tmp0 = tl.load(in_ptr0 + (x2 + 16 * y3), xmask & ymask)
    tl.store(out_ptr0 + (y0 + 4 * x2 + 64 * y1), tmp0, xmask & ymask)
    tl.store(out_ptr1 + (y0 + 4 * x2 + 64 * y1), tmp0, xmask & ymask)


@triton.jit
def triton_per_fused_mul_sum_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3, out_ptr0,
    xnumel, rnumel, XBLOCK: tl.constexpr):
    xnumel = 1024
    RBLOCK: tl.constexpr = 8
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    rindex = tl.arange(0, RBLOCK)[None, :]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    r4 = rindex
    x1 = xindex // 4 % 16
    x2 = xindex // 64 % 4
    x3 = xindex // 256
    x5 = xindex // 4
    x6 = xindex % 64
    x7 = xindex
    tmp0 = tl.load(in_ptr0 + (r4 + 8 * x2 + 32 * x1 + 512 * x3), xmask,
        eviction_policy='evict_last', other=0.0)
    tmp1 = tl.load(in_ptr1 + x5, xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr2 + (r4 + 8 * x6 + 512 * x3), xmask,
        eviction_policy='evict_last', other=0.0)
    tmp10 = tl.load(in_ptr3 + r4, None, eviction_policy='evict_last')
    tmp2 = tmp0 - tmp1
    tmp3 = tmp2 * tmp2
    tmp4 = 0.125
    tmp5 = tmp3 * tmp4
    tmp6 = -tmp5
    tmp7 = tl_math.exp(tmp6)
    tmp9 = tmp7 * tmp8
    tmp11 = tmp9 * tmp10
    tmp12 = tl.broadcast_to(tmp11, [XBLOCK, RBLOCK])
    tmp14 = tl.where(xmask, tmp12, 0)
    tmp15 = tl.sum(tmp14, 1)[:, None]
    tl.store(out_ptr0 + x7, tmp15, xmask)


@triton.jit
def triton_per_fused_div_exp_mul_neg_pow_sub_sum_3(in_ptr0, in_ptr1,
    in_ptr2, out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
    xnumel = 256
    RBLOCK: tl.constexpr = 8
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    rindex = tl.arange(0, RBLOCK)[None, :]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    r3 = rindex
    x0 = xindex % 16
    x1 = xindex // 16 % 4
    x2 = xindex // 64
    x4 = xindex
    tmp0 = tl.load(in_ptr0 + (r3 + 8 * x1 + 32 * x0 + 512 * x2), xmask,
        other=0.0)
    tmp1 = tl.load(in_ptr1 + x4, xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr2 + r3, None, eviction_policy='evict_last')
    tmp2 = tmp0 - tmp1
    tmp3 = tmp2 * tmp2
    tmp4 = 0.125
    tmp5 = tmp3 * tmp4
    tmp6 = -tmp5
    tmp7 = tl_math.exp(tmp6)
    tmp9 = tmp7 * tmp8
    tmp10 = tl.broadcast_to(tmp9, [XBLOCK, RBLOCK])
    tmp12 = tl.where(xmask, tmp10, 0)
    tmp13 = tl.sum(tmp12, 1)[:, None]
    tl.store(out_ptr0 + x4, tmp13, xmask)


@triton.jit
def triton_poi_fused_new_ones_4(out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = 1.0
    tl.store(out_ptr0 + x0, tmp0, xmask)


@triton.jit
def triton_poi_fused_div_5(in_ptr0, in_ptr1, out_ptr0, ynumel, xnumel,
    YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
    ynumel = 16
    xnumel = 64
    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
    x2 = xindex % 16
    x3 = xindex // 16
    y4 = yindex
    x5 = xindex
    y0 = yindex % 4
    y1 = yindex // 4
    tmp0 = tl.load(in_ptr0 + (x3 + 4 * x2 + 64 * y4), xmask & ymask,
        eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr1 + (x2 + 16 * y4), xmask & ymask, eviction_policy
        ='evict_last')
    tmp2 = tmp0 / tmp1
    tl.store(out_ptr0 + (y0 + 5 * x5 + 320 * y1), tmp2, xmask & ymask)


@triton.jit
def triton_poi_fused_cat_6(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
    constexpr):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex
    x0 = xindex % 4
    x1 = xindex // 4 % 16
    x2 = xindex // 64
    tmp0 = tl.load(in_ptr0 + x3, xmask)
    tmp1 = tl.load(in_ptr1 + x3, xmask)
    tmp2 = tmp0 / tmp1
    tl.store(out_ptr0 + (5 * x1 + 80 * x0 + 320 * x2), tmp2, xmask)


@triton.jit
def triton_poi_fused_cat_7(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
    constexpr, XBLOCK: tl.constexpr):
    ynumel = 20
    xnumel = 64
    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
    x2 = xindex
    y0 = yindex % 5
    y1 = yindex // 5
    y3 = yindex
    tmp0 = tl.load(in_ptr0 + (y0 + 5 * x2 + 320 * y1), xmask & ymask,
        eviction_policy='evict_last')
    tl.store(out_ptr0 + (x2 + 64 * y3), tmp0, xmask & ymask)


def call(args):
    arg0_1, arg1_1, arg2_1, arg3_1, arg4_1, arg5_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(arg1_1, (32, 1, 3, 3), (9, 9, 3, 1))
    assert_size_stride(arg2_1, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(arg3_1, (32, 1, 3, 3), (9, 9, 3, 1))
    assert_size_stride(arg4_1, (1, 1, 1, 8, 1, 1), (8, 8, 8, 1, 1, 1))
    assert_size_stride(arg5_1, (4, 1, 3, 3), (9, 9, 3, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 1, 16, 4), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_convolution_0[grid(16, 16)](arg0_1, buf0, 16, 16,
            XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1)
        buf1 = extern_kernels.convolution(buf0, arg1_1, stride=(1, 1),
            padding=(1, 1), dilation=(1, 1), transposed=False,
            output_padding=(0, 0), groups=4, bias=None)
        assert_size_stride(buf1, (4, 32, 4, 4), (512, 1, 128, 32))
        del arg1_1
        buf2 = buf0
        del buf0
        buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 1, 16, 4), torch.float32)
        triton_poi_fused_convolution_1[grid(16, 16)](arg2_1, buf2, buf6, 16,
            16, XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1)
        del arg2_1
        buf3 = extern_kernels.convolution(buf2, arg3_1, stride=(1, 1),
            padding=(1, 1), dilation=(1, 1), transposed=False,
            output_padding=(0, 0), groups=4, bias=None)
        assert_size_stride(buf3, (4, 32, 4, 4), (512, 1, 128, 32))
        del arg3_1
        buf4 = empty_strided_cuda((4, 4, 4, 4, 4), (256, 64, 1, 16, 4),
            torch.float32)
        triton_per_fused_mul_sum_2[grid(1024)](buf1, arg0_1, buf3, arg4_1,
            buf4, 1024, 8, XBLOCK=32, num_warps=2, num_stages=1)
        del buf3
        buf5 = reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0)
        del buf2
        triton_per_fused_div_exp_mul_neg_pow_sub_sum_3[grid(256)](buf1,
            arg0_1, arg4_1, buf5, 256, 8, XBLOCK=8, num_warps=2, num_stages=1)
        del arg0_1
        del arg4_1
        del buf1
        buf7 = extern_kernels.convolution(buf6, arg5_1, stride=(1, 1),
            padding=(1, 1), dilation=(1, 1), transposed=False,
            output_padding=(0, 0), groups=4, bias=None)
        assert_size_stride(buf7, (4, 4, 4, 4), (64, 1, 16, 4))
        buf8 = buf6
        del buf6
        triton_poi_fused_new_ones_4[grid(256)](buf8, 256, XBLOCK=128,
            num_warps=4, num_stages=1)
        buf9 = extern_kernels.convolution(buf8, arg5_1, stride=(1, 1),
            padding=(1, 1), dilation=(1, 1), transposed=False,
            output_padding=(0, 0), groups=4, bias=None)
        assert_size_stride(buf9, (4, 4, 4, 4), (64, 1, 16, 4))
        del arg5_1
        del buf8
        buf12 = empty_strided_cuda((4, 5, 4, 4, 4), (320, 1, 80, 20, 5),
            torch.float32)
        buf10 = reinterpret_tensor(buf12, (4, 4, 4, 4, 4), (320, 1, 80, 20,
            5), 0)
        triton_poi_fused_div_5[grid(16, 64)](buf4, buf5, buf10, 16, 64,
            XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1)
        del buf4
        del buf5
        buf11 = reinterpret_tensor(buf12, (4, 1, 4, 4, 4), (320, 1, 80, 20,
            5), 4)
        triton_poi_fused_cat_6[grid(256)](buf7, buf9, buf11, 256, XBLOCK=
            256, num_warps=4, num_stages=1)
        del buf7
        del buf9
        buf13 = empty_strided_cuda((4, 5, 4, 4, 4), (320, 64, 16, 4, 1),
            torch.float32)
        triton_poi_fused_cat_7[grid(20, 64)](buf12, buf13, 20, 64, XBLOCK=
            32, YBLOCK=32, num_warps=4, num_stages=1)
        del buf10
        del buf11
        del buf12
    return buf13,


def make_onehot_kernel(kernel_size, index):
    """
    Make 2D one hot square kernel, i.e. h=w
    k[kernel_size, kernel_size] = 0 except k.view(-1)[index] = 1
    """
    kernel = torch.zeros(kernel_size, kernel_size)
    kernel.view(-1)[index] = 1
    return kernel.view(1, 1, kernel_size, kernel_size)


def make_spatial_kernel(kernel_size, bandwidth, isreshape=True):
    """
    Make 2D square smoothness kernel, i.e. h=w
    k = 1/bandwidth * exp(-(pj-pi)**2/(2*bandwidth**2))
    pj, pi = location of pixel
    """
    assert bandwidth > 0, 'bandwidth of kernel must be > 0'
    assert kernel_size % 2 != 0, 'kernel must be odd'
    p_end = (kernel_size - 1) // 2
    X = torch.linspace(-p_end, p_end, steps=kernel_size).expand(kernel_size,
        kernel_size)
    Y = X.clone().t()
    kernel = torch.exp(-(X ** 2 + Y ** 2) / (2 * bandwidth ** 2))
    kernel[p_end, p_end] = 0
    if isreshape:
        return kernel.view(1, 1, kernel_size, kernel_size)
    return kernel


class GaussianMask(nn.Module):
    """
    Break down Gaussian kernel (2nd part of appearance kernel) into CNN
    kj = (I(j) - I(i))**2/2*bandwidth**2, j#i
    but compute all maps instead of 1 kernel
    """

    def __init__(self, in_channels, kernel_size, bandwidth, iskernel=True):
        super(GaussianMask, self).__init__()
        assert bandwidth > 0, 'bandwidth of kernel must be > 0'
        assert kernel_size % 2 != 0, 'kernel must be odd'
        self.bandwidth = bandwidth
        self.iskernel = iskernel
        self.n_kernels = kernel_size ** 2 - 1
        kernel_weight = self._make_kernel_weight(in_channels, kernel_size,
            self.n_kernels)
        padding = kernel_size // 2
        self.conv = nn.Conv2d(in_channels, in_channels * self.n_kernels,
            kernel_size, stride=1, padding=padding, groups=in_channels,
            bias=False)
        self.conv.weight.requires_grad = False
        self.conv.weight.copy_(kernel_weight.view_as(self.conv.weight))

    def _make_kernel_weight(self, in_channels, kernel_size, n_kernels):
        kernel_weight = torch.zeros(in_channels, n_kernels, kernel_size,
            kernel_size)
        for i in range(n_kernels):
            index = i if i < n_kernels // 2 else i + 1
            kernel_i = make_onehot_kernel(kernel_size, index)
            kernel_weight[:, i, :] = kernel_i
        return kernel_weight

    def forward(self, X):
        batch_size, in_channels, H, W = X.shape
        Xj = self.conv(X).view(batch_size, in_channels, self.n_kernels, H, W)
        if not self.iskernel:
            return Xj
        Xi = X.unsqueeze(dim=2)
        K = (Xj - Xi) ** 2 / (2 * self.bandwidth ** 2)
        K = torch.exp(-K)
        return K


class SpatialFilter(nn.Module):
    """
    Break down spatial filter (smoothest kernel) into CNN blocks
    refer: https://arxiv.org/pdf/1210.5644.pdf
    """

    def __init__(self, n_classes, kernel_size, theta_gamma):
        super(SpatialFilter, self).__init__()
        padding = kernel_size // 2
        kernel_weight = make_spatial_kernel(kernel_size, theta_gamma)
        self.conv = nn.Conv2d(n_classes, n_classes, kernel_size, stride=1,
            padding=padding, groups=n_classes, bias=False)
        self.conv.weight.requires_grad = False
        self.conv.weight.copy_(kernel_weight)

    def forward(self, Q):
        Qtilde = self.conv(Q)
        norm_weight = self.conv(Q.new_ones(*Q.shape, requires_grad=False))
        Qtilde = Qtilde / norm_weight
        return Qtilde


class BilateralFilter(nn.Module):
    """
    Break down bilateral filter (appearance kernel) into CNN blocks
    remember that exp(-a-b) =exp(-a)*exp(b)
    """

    def __init__(self, in_channels, n_classes, kernel_size, theta_alpha,
        theta_beta):
        super(BilateralFilter, self).__init__()
        kernel_weight = make_spatial_kernel(kernel_size, theta_alpha,
            isreshape=False)
        self.spatial_weight = Parameter(kernel_weight[kernel_weight > 0].
            view(1, 1, 1, -1, 1, 1), requires_grad=False)
        self.gauss_mask_I = GaussianMask(in_channels, kernel_size, theta_beta)
        self.guass_mask_Q = GaussianMask(n_classes, kernel_size, 1,
            iskernel=False)

    def forward(self, Q, I):
        Ij = self.gauss_mask_I(I)
        Qj = self.guass_mask_Q(Q)
        Qj = Ij.unsqueeze(dim=2) * Qj.unsqueeze(dim=1)
        Qj = Qj * self.spatial_weight
        Qtilde = Qj.sum(dim=3)
        norm_weight = Ij * self.spatial_weight.squeeze(dim=2)
        norm_weight = norm_weight.sum(dim=2)
        Qtilde = Qtilde / norm_weight.unsqueeze(dim=2)
        return Qtilde


class MessagePassingNew(nn.Module):
    """
    Combine bilateral filter (appearance filter)
    and spatial filter to make message passing
    """

    def __init__(self, in_channels, n_classes, kernel_size=[3], theta_alpha
        =[2.0], theta_beta=[2.0], theta_gamma=[2.0]):
        super(MessagePassingNew, self).__init__()
        assert len(theta_alpha) == len(theta_beta
            ), 'theta_alpha and theta_beta have different lengths'
        self.n_bilaterals, self.n_spatials = len(theta_alpha), len(theta_gamma)
        for i in range(self.n_bilaterals):
            self.add_module('bilateral{}'.format(i), BilateralFilter(
                in_channels, n_classes, kernel_size[i], theta_alpha[i],
                theta_beta[i]))
        for i in range(self.n_spatials):
            self.add_module('spatial{}'.format(i), SpatialFilter(n_classes,
                kernel_size[i], theta_gamma[i]))

    def _get_child(self, child_name):
        return getattr(self, child_name)

    def forward(self, input_0, input_1):
        arg4_1 = self.bilateral0.spatial_weight
        arg1_1 = self.bilateral0.gauss_mask_I.conv.weight
        arg3_1 = self.bilateral0.guass_mask_Q.conv.weight
        arg5_1 = self.spatial0.conv.weight
        arg0_1 = input_0
        arg2_1 = input_1
        output = call([arg0_1, arg1_1, arg2_1, arg3_1, arg4_1, arg5_1])
        return output[0]
