# 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_6/inductor_cache/eu/ceumtj7xcyreceoebyoq72ouno24pfm4fehgrvjy66alrzwrddk6.py
# Topologically Sorted Source Nodes: [mul, sum_1, sum_2, mul_1, sum_3, sum_4, mul_2, sum_5, sum_6, mul_3, sum_7, sum_8], Original ATen: [aten.mul, aten.sum]
# Source node to ATen node mapping:
#   mul => mul
#   mul_1 => mul_1
#   mul_2 => mul_2
#   mul_3 => mul_3
#   sum_1 => sum_1
#   sum_2 => sum_2
#   sum_3 => sum_3
#   sum_4 => sum_4
#   sum_5 => sum_5
#   sum_6 => sum_6
#   sum_7 => sum_7
#   sum_8 => sum_8
# Graph fragment:
#   %mul : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%arg1_1, %permute_1), kwargs = {})
#   %sum_1 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%mul, [2, 3]), kwargs = {})
#   %sum_2 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%arg1_1, [2, 3]), kwargs = {})
#   %mul_1 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%arg1_1, %permute_13), kwargs = {})
#   %sum_3 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%mul_1, [2, 3]), kwargs = {})
#   %sum_4 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%arg1_1, [2, 3]), kwargs = {})
#   %mul_2 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%arg1_1, %permute_25), kwargs = {})
#   %sum_5 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%mul_2, [2, 3]), kwargs = {})
#   %sum_6 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%arg1_1, [2, 3]), kwargs = {})
#   %mul_3 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%arg1_1, %permute_37), kwargs = {})
#   %sum_7 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%mul_3, [2, 3]), kwargs = {})
#   %sum_8 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%arg1_1, [2, 3]), kwargs = {})
triton_per_fused_mul_sum_0 = async_compile.triton('triton_per_fused_mul_sum_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.persistent_reduction(
    size_hints=[64, 128],
    reduction_hint=ReductionHint.INNER,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: '*fp32', 5: '*fp32', 6: '*fp32', 7: '*fp32', 8: '*fp32', 9: '*fp32', 10: 'i32', 11: '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, 5, 6, 7, 8, 9, 10), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_per_fused_mul_sum_0', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 5, 'num_reduction': 8, '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}
)
@triton.jit
def triton_per_fused_mul_sum_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1, out_ptr2, out_ptr3, out_ptr4, out_ptr5, out_ptr6, out_ptr7, xnumel, rnumel, XBLOCK : tl.constexpr):
    xnumel = 64
    rnumel = 121
    RBLOCK: tl.constexpr = 128
    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 = rindex < rnumel
    r5 = rindex
    x4 = xindex
    r3 = (rindex // 11)
    x0 = xindex % 16
    r2 = rindex % 11
    x1 = (xindex // 16)
    tmp0 = tl.load(in_ptr0 + (r5 + (121*x4)), rmask & xmask, other=0.0)
    tmp1 = (-5) + r3 + (x0 // 4)
    tmp2 = tl.full([1, 1], 0, tl.int64)
    tmp3 = tmp1 >= tmp2
    tmp4 = tl.full([1, 1], 4, tl.int64)
    tmp5 = tmp1 < tmp4
    tmp6 = (-5) + r2 + (x0 % 4)
    tmp7 = tmp6 >= tmp2
    tmp8 = tmp6 < tmp4
    tmp9 = tmp3 & tmp5
    tmp10 = tmp9 & tmp7
    tmp11 = tmp10 & tmp8
    tmp12 = tl.load(in_ptr1 + ((-25) + r2 + x0 + (4*r3) + (64*x1)), rmask & tmp11 & xmask, other=0.0)
    tmp13 = tmp0 * tmp12
    tmp14 = tl.broadcast_to(tmp13, [XBLOCK, RBLOCK])
    tmp16 = tl.where(rmask & xmask, tmp14, 0)
    tmp17 = tl.sum(tmp16, 1)[:, None]
    tmp18 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
    tmp20 = tl.where(rmask & xmask, tmp18, 0)
    tmp21 = tl.sum(tmp20, 1)[:, None]
    tmp22 = tl.load(in_ptr1 + ((-9) + r2 + x0 + (4*r3) + (64*x1)), rmask & tmp11 & xmask, other=0.0)
    tmp23 = tmp0 * tmp22
    tmp24 = tl.broadcast_to(tmp23, [XBLOCK, RBLOCK])
    tmp26 = tl.where(rmask & xmask, tmp24, 0)
    tmp27 = tl.sum(tmp26, 1)[:, None]
    tmp28 = tl.load(in_ptr1 + (7 + r2 + x0 + (4*r3) + (64*x1)), rmask & tmp11 & xmask, other=0.0)
    tmp29 = tmp0 * tmp28
    tmp30 = tl.broadcast_to(tmp29, [XBLOCK, RBLOCK])
    tmp32 = tl.where(rmask & xmask, tmp30, 0)
    tmp33 = tl.sum(tmp32, 1)[:, None]
    tmp34 = tl.load(in_ptr1 + (23 + r2 + x0 + (4*r3) + (64*x1)), rmask & tmp11 & xmask, other=0.0)
    tmp35 = tmp0 * tmp34
    tmp36 = tl.broadcast_to(tmp35, [XBLOCK, RBLOCK])
    tmp38 = tl.where(rmask & xmask, tmp36, 0)
    tmp39 = tl.sum(tmp38, 1)[:, None]
    tl.store(out_ptr0 + (x4), tmp17, xmask)
    tl.store(out_ptr1 + (x4), tmp21, xmask)
    tl.store(out_ptr2 + (x4), tmp27, xmask)
    tl.store(out_ptr3 + (x4), tmp21, xmask)
    tl.store(out_ptr4 + (x4), tmp33, xmask)
    tl.store(out_ptr5 + (x4), tmp21, xmask)
    tl.store(out_ptr6 + (x4), tmp39, xmask)
    tl.store(out_ptr7 + (x4), tmp21, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_6/inductor_cache/37/c37d5tkkh5wgblx6jju22mcemevae53qwki2t43o26tnrodtxflo.py
# Topologically Sorted Source Nodes: [l1_loss, add, l1_loss_1, add_1, l1_loss_2, add_2, l1_loss_3, add_3, sub], Original ATen: [aten.sub, aten.abs, aten.mean, aten.add, aten.rsub]
# Source node to ATen node mapping:
#   add => add_8
#   add_1 => add_9
#   add_2 => add_10
#   add_3 => add_11
#   l1_loss => abs_1, div, mean
#   l1_loss_1 => abs_2, div_1, mean_1
#   l1_loss_2 => abs_3, div_2, mean_2
#   l1_loss_3 => abs_4, div_3, mean_3
#   sub => sub_4
# Graph fragment:
#   %div : [num_users=1] = call_function[target=torch.ops.aten.div.Tensor](args = (%view_6, %view_10), kwargs = {})
#   %abs_1 : [num_users=1] = call_function[target=torch.ops.aten.abs.default](args = (%div,), kwargs = {})
#   %mean : [num_users=1] = call_function[target=torch.ops.aten.mean.default](args = (%abs_1,), kwargs = {})
#   %add_8 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%mean, 0), kwargs = {})
#   %div_1 : [num_users=1] = call_function[target=torch.ops.aten.div.Tensor](args = (%view_17, %view_21), kwargs = {})
#   %abs_2 : [num_users=1] = call_function[target=torch.ops.aten.abs.default](args = (%div_1,), kwargs = {})
#   %mean_1 : [num_users=1] = call_function[target=torch.ops.aten.mean.default](args = (%abs_2,), kwargs = {})
#   %add_9 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%add_8, %mean_1), kwargs = {})
#   %div_2 : [num_users=1] = call_function[target=torch.ops.aten.div.Tensor](args = (%view_28, %view_32), kwargs = {})
#   %abs_3 : [num_users=1] = call_function[target=torch.ops.aten.abs.default](args = (%div_2,), kwargs = {})
#   %mean_2 : [num_users=1] = call_function[target=torch.ops.aten.mean.default](args = (%abs_3,), kwargs = {})
#   %add_10 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%add_9, %mean_2), kwargs = {})
#   %div_3 : [num_users=1] = call_function[target=torch.ops.aten.div.Tensor](args = (%view_39, %view_43), kwargs = {})
#   %abs_4 : [num_users=1] = call_function[target=torch.ops.aten.abs.default](args = (%div_3,), kwargs = {})
#   %mean_3 : [num_users=1] = call_function[target=torch.ops.aten.mean.default](args = (%abs_4,), kwargs = {})
#   %add_11 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%add_10, %mean_3), kwargs = {})
#   %sub_4 : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (4, %add_11), kwargs = {})
triton_per_fused_abs_add_mean_rsub_sub_1 = async_compile.triton('triton_per_fused_abs_add_mean_rsub_sub_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.persistent_reduction(
    size_hints=[1, 4],
    reduction_hint=ReductionHint.INNER,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: '*fp32', 5: '*fp32', 6: '*fp32', 7: '*fp32', 8: '*fp32', 9: 'i32', 10: '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': {9: 1}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3, 4, 5, 6, 7, 8), equal_to_1=(9,))]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_per_fused_abs_add_mean_rsub_sub_1', 'mutated_arg_names': ['in_out_ptr0'], 'no_x_dim': False, 'num_load': 8, 'num_reduction': 4, '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}
)
@triton.jit
def triton_per_fused_abs_add_mean_rsub_sub_1(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, xnumel, rnumel, XBLOCK : tl.constexpr):
    xnumel = 1
    rnumel = 4
    RBLOCK: tl.constexpr = 4
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = tl.full([XBLOCK, RBLOCK], True, tl.int1)
    rindex = tl.arange(0, RBLOCK)[None, :]
    roffset = 0
    rmask = tl.full([XBLOCK, RBLOCK], True, tl.int1)
    r0 = rindex
    tmp0 = tl.load(in_ptr0 + (r0), None)
    tmp1 = tl.load(in_ptr1 + (r0), None)
    tmp7 = tl.load(in_ptr2 + (r0), None)
    tmp8 = tl.load(in_ptr3 + (r0), None)
    tmp14 = tl.load(in_ptr4 + (r0), None)
    tmp15 = tl.load(in_ptr5 + (r0), None)
    tmp21 = tl.load(in_ptr6 + (r0), None)
    tmp22 = tl.load(in_ptr7 + (r0), None)
    tmp2 = tmp0 / tmp1
    tmp3 = tl_math.abs(tmp2)
    tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
    tmp6 = tl.sum(tmp4, 1)[:, None]
    tmp9 = tmp7 / tmp8
    tmp10 = tl_math.abs(tmp9)
    tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK])
    tmp13 = tl.sum(tmp11, 1)[:, None]
    tmp16 = tmp14 / tmp15
    tmp17 = tl_math.abs(tmp16)
    tmp18 = tl.broadcast_to(tmp17, [XBLOCK, RBLOCK])
    tmp20 = tl.sum(tmp18, 1)[:, None]
    tmp23 = tmp21 / tmp22
    tmp24 = tl_math.abs(tmp23)
    tmp25 = tl.broadcast_to(tmp24, [XBLOCK, RBLOCK])
    tmp27 = tl.sum(tmp25, 1)[:, None]
    tmp28 = 4.0
    tmp29 = tmp6 / tmp28
    tmp30 = 0.0
    tmp31 = tmp29 + tmp30
    tmp32 = tmp13 / tmp28
    tmp33 = tmp31 + tmp32
    tmp34 = tmp20 / tmp28
    tmp35 = tmp33 + tmp34
    tmp36 = tmp27 / tmp28
    tmp37 = tmp35 + tmp36
    tmp38 = tmp28 - tmp37
    tl.debug_barrier()
    tl.store(in_out_ptr0 + (tl.full([XBLOCK, 1], 0, tl.int32)), tmp38, None)
''', device_str='cuda')


async_compile.wait(globals())
del async_compile

def call(args):
    arg0_1, arg1_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(arg1_1, (4, 16, 11, 11), (1936, 121, 11, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
        buf2 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
        buf5 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
        buf7 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
        buf10 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
        buf12 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
        buf15 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
        buf17 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
        # Topologically Sorted Source Nodes: [mul, sum_1, sum_2, mul_1, sum_3, sum_4, mul_2, sum_5, sum_6, mul_3, sum_7, sum_8], Original ATen: [aten.mul, aten.sum]
        stream0 = get_raw_stream(0)
        triton_per_fused_mul_sum_0.run(arg1_1, arg0_1, buf0, buf2, buf5, buf7, buf10, buf12, buf15, buf17, 64, 121, grid=grid(64), stream=stream0)
        del arg1_1
        buf1 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        # Topologically Sorted Source Nodes: [einsum], Original ATen: [aten.bmm]
        extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 1, 16), (64, 0, 1), 0), reinterpret_tensor(buf0, (4, 16, 1), (16, 1, 1), 0), out=buf1)
        del buf0
        buf3 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        # Topologically Sorted Source Nodes: [einsum_1], Original ATen: [aten.bmm]
        extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 1, 16), (64, 0, 1), 0), reinterpret_tensor(buf2, (4, 16, 1), (16, 1, 1), 0), out=buf3)
        del buf2
        buf11 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        # Topologically Sorted Source Nodes: [einsum_4], Original ATen: [aten.bmm]
        extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 1, 16), (64, 0, 1), 32), reinterpret_tensor(buf10, (4, 16, 1), (16, 1, 1), 0), out=buf11)
        del buf10
        buf13 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        # Topologically Sorted Source Nodes: [einsum_5], Original ATen: [aten.bmm]
        extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 1, 16), (64, 0, 1), 32), reinterpret_tensor(buf12, (4, 16, 1), (16, 1, 1), 0), out=buf13)
        del buf12
        buf16 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        # Topologically Sorted Source Nodes: [einsum_6], Original ATen: [aten.bmm]
        extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 1, 16), (64, 0, 1), 48), reinterpret_tensor(buf15, (4, 16, 1), (16, 1, 1), 0), out=buf16)
        del buf15
        buf18 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        # Topologically Sorted Source Nodes: [einsum_7], Original ATen: [aten.bmm]
        extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 1, 16), (64, 0, 1), 48), reinterpret_tensor(buf17, (4, 16, 1), (16, 1, 1), 0), out=buf18)
        del buf17
        buf6 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        # Topologically Sorted Source Nodes: [einsum_2], Original ATen: [aten.bmm]
        extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 1, 16), (64, 0, 1), 16), reinterpret_tensor(buf5, (4, 16, 1), (16, 1, 1), 0), out=buf6)
        del buf5
        buf8 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        # Topologically Sorted Source Nodes: [einsum_3], Original ATen: [aten.bmm]
        extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 1, 16), (64, 0, 1), 16), reinterpret_tensor(buf7, (4, 16, 1), (16, 1, 1), 0), out=buf8)
        del arg0_1
        del buf7
        buf14 = empty_strided_cuda((), (), torch.float32)
        buf20 = buf14; del buf14  # reuse
        # Topologically Sorted Source Nodes: [l1_loss, add, l1_loss_1, add_1, l1_loss_2, add_2, l1_loss_3, add_3, sub], Original ATen: [aten.sub, aten.abs, aten.mean, aten.add, aten.rsub]
        triton_per_fused_abs_add_mean_rsub_sub_1.run(buf20, buf1, buf3, buf6, buf8, buf11, buf13, buf16, buf18, 1, 4, grid=grid(1), stream=stream0)
        del buf1
        del buf11
        del buf13
        del buf16
        del buf18
        del buf3
        del buf6
        del buf8
    return (buf20, )


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((4, 16, 11, 11), (1936, 121, 11, 1), device='cuda:0', dtype=torch.float32)
    fn = lambda: call([arg0_1, arg1_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
from torch import Tensor
import torch.nn as nn


class NCutLossOptimized(nn.Module):
    """Implementation of the continuous N-Cut loss, as in:
    'W-Net: A Deep Model for Fully Unsupervised Image Segmentation', by Xia, Kulis (2017)"""

    def __init__(self, radius: 'int'=5):
        """
        :param radius: Radius of the spatial interaction term
        """
        super(NCutLossOptimized, self).__init__()
        self.radius = radius

    def forward(self, labels: 'Tensor', weights: 'Tensor') ->Tensor:
        """Computes the continuous N-Cut loss, given a set of class probabilities (labels) and image weights (weights).
        :param weights: Image pixel weights
        :param labels: Predicted class probabilities
        :return: Continuous N-Cut loss
        """
        num_classes = labels.shape[1]
        losses = []
        region_size = 2 * [2 * self.radius + 1]
        unfold = torch.nn.Unfold(region_size, padding=self.radius)
        unflatten = torch.nn.Unflatten(1, region_size)
        for k in range(num_classes):
            class_probs = labels[:, k].unsqueeze(1)
            p_f = class_probs.flatten(start_dim=1)
            P = unflatten(unfold(class_probs)).permute(0, 3, 1, 2)
            L = torch.einsum('ij,ij->i', p_f, torch.sum(weights * P, dim=(2,
                3))) / torch.einsum('ij,ij->i', p_f, torch.sum(weights, dim
                =(2, 3)))
            losses.append(nn.L1Loss()(L, torch.zeros_like(L)))
        return num_classes - sum(losses)


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


def get_init_inputs():
    return [[], {}]

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.nn as nn
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor


@triton.jit
def triton_per_fused_mul_sum_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1,
    out_ptr2, out_ptr3, out_ptr4, out_ptr5, out_ptr6, out_ptr7, xnumel,
    rnumel, XBLOCK: tl.constexpr):
    xnumel = 64
    rnumel = 121
    RBLOCK: tl.constexpr = 128
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    rindex = tl.arange(0, RBLOCK)[None, :]
    rmask = rindex < rnumel
    r5 = rindex
    x4 = xindex
    r3 = rindex // 11
    x0 = xindex % 16
    r2 = rindex % 11
    x1 = xindex // 16
    tmp0 = tl.load(in_ptr0 + (r5 + 121 * x4), rmask & xmask, other=0.0)
    tmp1 = -5 + r3 + x0 // 4
    tmp2 = tl.full([1, 1], 0, tl.int64)
    tmp3 = tmp1 >= tmp2
    tmp4 = tl.full([1, 1], 4, tl.int64)
    tmp5 = tmp1 < tmp4
    tmp6 = -5 + r2 + x0 % 4
    tmp7 = tmp6 >= tmp2
    tmp8 = tmp6 < tmp4
    tmp9 = tmp3 & tmp5
    tmp10 = tmp9 & tmp7
    tmp11 = tmp10 & tmp8
    tmp12 = tl.load(in_ptr1 + (-25 + r2 + x0 + 4 * r3 + 64 * x1), rmask &
        tmp11 & xmask, other=0.0)
    tmp13 = tmp0 * tmp12
    tmp14 = tl.broadcast_to(tmp13, [XBLOCK, RBLOCK])
    tmp16 = tl.where(rmask & xmask, tmp14, 0)
    tmp17 = tl.sum(tmp16, 1)[:, None]
    tmp18 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
    tmp20 = tl.where(rmask & xmask, tmp18, 0)
    tmp21 = tl.sum(tmp20, 1)[:, None]
    tmp22 = tl.load(in_ptr1 + (-9 + r2 + x0 + 4 * r3 + 64 * x1), rmask &
        tmp11 & xmask, other=0.0)
    tmp23 = tmp0 * tmp22
    tmp24 = tl.broadcast_to(tmp23, [XBLOCK, RBLOCK])
    tmp26 = tl.where(rmask & xmask, tmp24, 0)
    tmp27 = tl.sum(tmp26, 1)[:, None]
    tmp28 = tl.load(in_ptr1 + (7 + r2 + x0 + 4 * r3 + 64 * x1), rmask &
        tmp11 & xmask, other=0.0)
    tmp29 = tmp0 * tmp28
    tmp30 = tl.broadcast_to(tmp29, [XBLOCK, RBLOCK])
    tmp32 = tl.where(rmask & xmask, tmp30, 0)
    tmp33 = tl.sum(tmp32, 1)[:, None]
    tmp34 = tl.load(in_ptr1 + (23 + r2 + x0 + 4 * r3 + 64 * x1), rmask &
        tmp11 & xmask, other=0.0)
    tmp35 = tmp0 * tmp34
    tmp36 = tl.broadcast_to(tmp35, [XBLOCK, RBLOCK])
    tmp38 = tl.where(rmask & xmask, tmp36, 0)
    tmp39 = tl.sum(tmp38, 1)[:, None]
    tl.store(out_ptr0 + x4, tmp17, xmask)
    tl.store(out_ptr1 + x4, tmp21, xmask)
    tl.store(out_ptr2 + x4, tmp27, xmask)
    tl.store(out_ptr3 + x4, tmp21, xmask)
    tl.store(out_ptr4 + x4, tmp33, xmask)
    tl.store(out_ptr5 + x4, tmp21, xmask)
    tl.store(out_ptr6 + x4, tmp39, xmask)
    tl.store(out_ptr7 + x4, tmp21, xmask)


@triton.jit
def triton_per_fused_abs_add_mean_rsub_sub_1(in_out_ptr0, in_ptr0, in_ptr1,
    in_ptr2, in_ptr3, in_ptr4, in_ptr5, in_ptr6, in_ptr7, 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.load(in_ptr1 + r0, None)
    tmp7 = tl.load(in_ptr2 + r0, None)
    tmp8 = tl.load(in_ptr3 + r0, None)
    tmp14 = tl.load(in_ptr4 + r0, None)
    tmp15 = tl.load(in_ptr5 + r0, None)
    tmp21 = tl.load(in_ptr6 + r0, None)
    tmp22 = tl.load(in_ptr7 + r0, None)
    tmp2 = tmp0 / tmp1
    tmp3 = tl_math.abs(tmp2)
    tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
    tmp6 = tl.sum(tmp4, 1)[:, None]
    tmp9 = tmp7 / tmp8
    tmp10 = tl_math.abs(tmp9)
    tmp11 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK])
    tmp13 = tl.sum(tmp11, 1)[:, None]
    tmp16 = tmp14 / tmp15
    tmp17 = tl_math.abs(tmp16)
    tmp18 = tl.broadcast_to(tmp17, [XBLOCK, RBLOCK])
    tmp20 = tl.sum(tmp18, 1)[:, None]
    tmp23 = tmp21 / tmp22
    tmp24 = tl_math.abs(tmp23)
    tmp25 = tl.broadcast_to(tmp24, [XBLOCK, RBLOCK])
    tmp27 = tl.sum(tmp25, 1)[:, None]
    tmp28 = 4.0
    tmp29 = tmp6 / tmp28
    tmp30 = 0.0
    tmp31 = tmp29 + tmp30
    tmp32 = tmp13 / tmp28
    tmp33 = tmp31 + tmp32
    tmp34 = tmp20 / tmp28
    tmp35 = tmp33 + tmp34
    tmp36 = tmp27 / tmp28
    tmp37 = tmp35 + tmp36
    tmp38 = tmp28 - tmp37
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp38, None)


def call(args):
    arg0_1, arg1_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(arg1_1, (4, 16, 11, 11), (1936, 121, 11, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
        buf2 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
        buf5 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
        buf7 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
        buf10 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
        buf12 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
        buf15 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
        buf17 = empty_strided_cuda((4, 16), (16, 1), torch.float32)
        get_raw_stream(0)
        triton_per_fused_mul_sum_0[grid(64)](arg1_1, arg0_1, buf0, buf2,
            buf5, buf7, buf10, buf12, buf15, buf17, 64, 121, XBLOCK=1,
            num_warps=2, num_stages=1)
        del arg1_1
        buf1 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 1, 16), (64, 0, 1
            ), 0), reinterpret_tensor(buf0, (4, 16, 1), (16, 1, 1), 0), out
            =buf1)
        del buf0
        buf3 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 1, 16), (64, 0, 1
            ), 0), reinterpret_tensor(buf2, (4, 16, 1), (16, 1, 1), 0), out
            =buf3)
        del buf2
        buf11 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 1, 16), (64, 0, 1
            ), 32), reinterpret_tensor(buf10, (4, 16, 1), (16, 1, 1), 0),
            out=buf11)
        del buf10
        buf13 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 1, 16), (64, 0, 1
            ), 32), reinterpret_tensor(buf12, (4, 16, 1), (16, 1, 1), 0),
            out=buf13)
        del buf12
        buf16 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 1, 16), (64, 0, 1
            ), 48), reinterpret_tensor(buf15, (4, 16, 1), (16, 1, 1), 0),
            out=buf16)
        del buf15
        buf18 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 1, 16), (64, 0, 1
            ), 48), reinterpret_tensor(buf17, (4, 16, 1), (16, 1, 1), 0),
            out=buf18)
        del buf17
        buf6 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 1, 16), (64, 0, 1
            ), 16), reinterpret_tensor(buf5, (4, 16, 1), (16, 1, 1), 0),
            out=buf6)
        del buf5
        buf8 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        extern_kernels.bmm(reinterpret_tensor(arg0_1, (4, 1, 16), (64, 0, 1
            ), 16), reinterpret_tensor(buf7, (4, 16, 1), (16, 1, 1), 0),
            out=buf8)
        del arg0_1
        del buf7
        buf14 = empty_strided_cuda((), (), torch.float32)
        buf20 = buf14
        del buf14
        triton_per_fused_abs_add_mean_rsub_sub_1[grid(1)](buf20, buf1, buf3,
            buf6, buf8, buf11, buf13, buf16, buf18, 1, 4, XBLOCK=1,
            num_warps=2, num_stages=1)
        del buf1
        del buf11
        del buf13
        del buf16
        del buf18
        del buf3
        del buf6
        del buf8
    return buf20,


class NCutLossOptimizedNew(nn.Module):
    """Implementation of the continuous N-Cut loss, as in:
    'W-Net: A Deep Model for Fully Unsupervised Image Segmentation', by Xia, Kulis (2017)"""

    def __init__(self, radius: 'int'=5):
        """
        :param radius: Radius of the spatial interaction term
        """
        super(NCutLossOptimizedNew, self).__init__()
        self.radius = radius

    def forward(self, input_0, input_1):
        arg0_1 = input_0
        arg1_1 = input_1
        output = call([arg0_1, arg1_1])
        return output[0]
