# 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_4/inductor_cache/e7/ce7xjdj2tvxcwlhhngstv777hdifvqsxqnkbqoex2db5kmz3pccu.py
# Topologically Sorted Source Nodes: [Xn, X_1], Original ATen: [aten.linalg_vector_norm, aten.div]
# Source node to ATen node mapping:
#   X_1 => div
#   Xn => pow_1, pow_2, sum_1
# Graph fragment:
#   %pow_1 : [num_users=1] = call_function[target=torch.ops.aten.pow.Tensor_Scalar](args = (%view, 2), kwargs = {})
#   %sum_1 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%pow_1, [1], True), kwargs = {})
#   %pow_2 : [num_users=1] = call_function[target=torch.ops.aten.pow.Tensor_Scalar](args = (%sum_1, 0.5), kwargs = {})
#   %div : [num_users=2] = call_function[target=torch.ops.aten.div.Tensor](args = (%view, %pow_2), kwargs = {})
triton_per_fused_div_linalg_vector_norm_0 = async_compile.triton('triton_per_fused_div_linalg_vector_norm_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=[4, 64],
    reduction_hint=ReductionHint.INNER,
    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, 3), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_per_fused_div_linalg_vector_norm_0', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 1, 'num_reduction': 1, '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_div_linalg_vector_norm_0(in_ptr0, out_ptr1, xnumel, rnumel, XBLOCK : tl.constexpr):
    xnumel = 4
    rnumel = 64
    RBLOCK: tl.constexpr = 64
    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)
    r1 = rindex
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (r1 + (64*x0)), xmask, other=0.0)
    tmp1 = tmp0 * tmp0
    tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
    tmp4 = tl.where(xmask, tmp2, 0)
    tmp5 = tl.sum(tmp4, 1)[:, None]
    tmp6 = libdevice.sqrt(tmp5)
    tmp7 = tmp0 / tmp6
    tl.store(out_ptr1 + (r1 + (64*x0)), tmp7, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_4/inductor_cache/gv/cgvqntvmbnygnswu42nmfoc5z5zjax6kxfpgxm6jtykcehwkrvi7.py
# Topologically Sorted Source Nodes: [mul, add, X_L2, X_L2_1, mean, mul_1, gamma, neg, mul_2, kernel_XX, diag_2, tK, sum_1], Original ATen: [aten.mul, aten.add, aten.clamp, aten.mean, aten.reciprocal, aten.neg, aten.exp, aten.diagonal_copy, aten.sub, aten.sum]
# Source node to ATen node mapping:
#   X_L2 => add_1
#   X_L2_1 => clamp_min
#   add => add
#   diag_2 => diagonal_copy_2
#   gamma => mul_2, reciprocal
#   kernel_XX => exp
#   mean => mean
#   mul => mul
#   mul_1 => mul_1
#   mul_2 => mul_3
#   neg => neg
#   sum_1 => sum_4
#   tK => sub
# Graph fragment:
#   %mul : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%mm, -2), kwargs = {})
#   %add : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%mul, %unsqueeze), kwargs = {})
#   %add_1 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%add, %unsqueeze_1), kwargs = {})
#   %clamp_min : [num_users=2] = call_function[target=torch.ops.aten.clamp_min.default](args = (%add_1, 1e-12), kwargs = {})
#   %mean : [num_users=1] = call_function[target=torch.ops.aten.mean.default](args = (%clamp_min,), kwargs = {})
#   %mul_1 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%mean, 2), kwargs = {})
#   %reciprocal : [num_users=1] = call_function[target=torch.ops.aten.reciprocal.default](args = (%mul_1,), kwargs = {})
#   %mul_2 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%reciprocal, 1), kwargs = {})
#   %neg : [num_users=1] = call_function[target=torch.ops.aten.neg.default](args = (%mul_2,), kwargs = {})
#   %mul_3 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%neg, %clamp_min), kwargs = {})
#   %exp : [num_users=2] = call_function[target=torch.ops.aten.exp.default](args = (%mul_3,), kwargs = {})
#   %diagonal_copy_2 : [num_users=1] = call_function[target=torch.ops.aten.diagonal_copy.default](args = (%exp,), kwargs = {})
#   %sub : [num_users=3] = call_function[target=torch.ops.aten.sub.Tensor](args = (%exp, %diagonal_copy_2), kwargs = {})
#   %sum_4 : [num_users=1] = call_function[target=torch.ops.aten.sum.default](args = (%sub,), kwargs = {})
triton_per_fused_add_clamp_diagonal_copy_exp_mean_mul_neg_reciprocal_sub_sum_1 = async_compile.triton('triton_per_fused_add_clamp_diagonal_copy_exp_mean_mul_neg_reciprocal_sub_sum_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, 16],
    reduction_hint=ReductionHint.DEFAULT,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: 'i32', 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': {3: 1}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 4), equal_to_1=(3,))]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_per_fused_add_clamp_diagonal_copy_exp_mean_mul_neg_reciprocal_sub_sum_1', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 3, 'num_reduction': 2, '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_add_clamp_diagonal_copy_exp_mean_mul_neg_reciprocal_sub_sum_1(in_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK : tl.constexpr):
    xnumel = 1
    rnumel = 16
    RBLOCK: tl.constexpr = 16
    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)
    r2 = rindex
    r1 = (rindex // 4)
    r0 = rindex % 4
    tmp0 = tl.load(in_ptr0 + (r2), None)
    tmp3 = tl.load(in_ptr0 + (5*r1), None, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr0 + (5*r0), None, eviction_policy='evict_last')
    tmp1 = -2.0
    tmp2 = tmp0 * tmp1
    tmp4 = tmp2 + tmp3
    tmp6 = tmp4 + tmp5
    tmp7 = 1e-12
    tmp8 = triton_helpers.maximum(tmp6, tmp7)
    tmp9 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK])
    tmp11 = tl.sum(tmp9, 1)[:, None]
    tmp12 = 16.0
    tmp13 = tmp11 / tmp12
    tmp14 = 2.0
    tmp15 = tmp13 * tmp14
    tmp16 = tl.full([1, 1], 1, tl.int32)
    tmp17 = tmp16 / tmp15
    tmp18 = 1.0
    tmp19 = tmp17 * tmp18
    tmp20 = -tmp19
    tmp21 = tmp20 * tmp8
    tmp22 = tl_math.exp(tmp21)
    tmp23 = tmp5 * tmp1
    tmp24 = tmp23 + tmp5
    tmp25 = tmp24 + tmp5
    tmp26 = triton_helpers.maximum(tmp25, tmp7)
    tmp27 = tmp20 * tmp26
    tmp28 = tl_math.exp(tmp27)
    tmp29 = tmp22 - tmp28
    tmp30 = tl.broadcast_to(tmp29, [XBLOCK, RBLOCK])
    tmp32 = tl.sum(tmp30, 1)[:, None]
    tl.store(out_ptr1 + (tl.broadcast_to(r2, [XBLOCK, RBLOCK])), tmp29, None)
    tl.store(out_ptr2 + (tl.full([XBLOCK, 1], 0, tl.int32)), tmp32, None)
''', device_str='cuda')


# kernel path: runs/run_shard_4/inductor_cache/sq/csq4ts4ymmp3skpjo5ndeq3xb7zhrbverearsk22gshhezg3xbgj.py
# Topologically Sorted Source Nodes: [trace, mul_6, truediv_2, truediv_3, add_4, sum_3, sum_4, dot, mul_7, truediv_4, hsic, truediv_5, neg_2], Original ATen: [aten.trace, aten.mul, aten.div, aten.add, aten.sum, aten.dot, aten.sub, aten.neg]
# Source node to ATen node mapping:
#   add_4 => add_4
#   dot => mul_9, sum_8
#   hsic => sub_2
#   mul_6 => mul_8
#   mul_7 => mul_10
#   neg_2 => neg_2
#   sum_3 => sum_6
#   sum_4 => sum_7
#   trace => diagonal_copy_4, sum_3
#   truediv_2 => div_2
#   truediv_3 => div_3
#   truediv_4 => div_4
#   truediv_5 => div_5
# Graph fragment:
#   %diagonal_copy_4 : [num_users=1] = call_function[target=torch.ops.aten.diagonal_copy.default](args = (%mm_2,), kwargs = {})
#   %sum_3 : [num_users=1] = call_function[target=torch.ops.aten.sum.default](args = (%diagonal_copy_4,), kwargs = {})
#   %mul_8 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%sum_4, %sum_5), kwargs = {})
#   %div_2 : [num_users=1] = call_function[target=torch.ops.aten.div.Tensor](args = (%mul_8, 3), kwargs = {})
#   %div_3 : [num_users=1] = call_function[target=torch.ops.aten.div.Tensor](args = (%div_2, 2), kwargs = {})
#   %add_4 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%sum_3, %div_3), kwargs = {})
#   %sum_6 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%sub, [0]), kwargs = {})
#   %sum_7 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%sub_1, [0]), kwargs = {})
#   %mul_9 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%sum_6, %sum_7), kwargs = {})
#   %sum_8 : [num_users=1] = call_function[target=torch.ops.aten.sum.default](args = (%mul_9,), kwargs = {})
#   %mul_10 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%sum_8, 2), kwargs = {})
#   %div_4 : [num_users=1] = call_function[target=torch.ops.aten.div.Tensor](args = (%mul_10, 2), kwargs = {})
#   %sub_2 : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%add_4, %div_4), kwargs = {})
#   %div_5 : [num_users=1] = call_function[target=torch.ops.aten.div.Tensor](args = (%sub_2, 4), kwargs = {})
#   %neg_2 : [num_users=1] = call_function[target=torch.ops.aten.neg.default](args = (%div_5,), kwargs = {})
triton_per_fused_add_div_dot_mul_neg_sub_sum_trace_2 = async_compile.triton('triton_per_fused_add_div_dot_mul_neg_sub_sum_trace_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=[1, 4],
    reduction_hint=ReductionHint.INNER,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: '*fp32', 5: '*fp32', 6: 'i32', 7: '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': {6: 1}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3, 4, 5), equal_to_1=(6,))]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_per_fused_add_div_dot_mul_neg_sub_sum_trace_2', 'mutated_arg_names': ['in_out_ptr0'], 'no_x_dim': False, 'num_load': 11, 'num_reduction': 2, '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_add_div_dot_mul_neg_sub_sum_trace_2(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, 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 + (5*r0), None, eviction_policy='evict_last')
    tmp4 = tl.load(in_ptr1 + (r0), None)
    tmp5 = tl.load(in_ptr1 + (4 + r0), None)
    tmp7 = tl.load(in_ptr1 + (8 + r0), None)
    tmp9 = tl.load(in_ptr1 + (12 + r0), None)
    tmp11 = tl.load(in_ptr2 + (r0), None)
    tmp12 = tl.load(in_ptr2 + (4 + r0), None)
    tmp14 = tl.load(in_ptr2 + (8 + r0), None)
    tmp16 = tl.load(in_ptr2 + (12 + r0), None)
    tmp22 = tl.load(in_ptr3 + (0))
    tmp23 = tl.broadcast_to(tmp22, [XBLOCK, 1])
    tmp24 = tl.load(in_ptr4 + (0))
    tmp25 = tl.broadcast_to(tmp24, [XBLOCK, 1])
    tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
    tmp3 = tl.sum(tmp1, 1)[:, None]
    tmp6 = tmp4 + tmp5
    tmp8 = tmp6 + tmp7
    tmp10 = tmp8 + tmp9
    tmp13 = tmp11 + tmp12
    tmp15 = tmp13 + tmp14
    tmp17 = tmp15 + tmp16
    tmp18 = tmp10 * tmp17
    tmp19 = tl.broadcast_to(tmp18, [XBLOCK, RBLOCK])
    tmp21 = tl.sum(tmp19, 1)[:, None]
    tmp26 = tmp23 * tmp25
    tmp27 = 0.3333333333333333
    tmp28 = tmp26 * tmp27
    tmp29 = 0.5
    tmp30 = tmp28 * tmp29
    tmp31 = tmp3 + tmp30
    tmp32 = 2.0
    tmp33 = tmp21 * tmp32
    tmp34 = tmp33 * tmp29
    tmp35 = tmp31 - tmp34
    tmp36 = 0.25
    tmp37 = tmp35 * tmp36
    tmp38 = -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, 4, 4, 4), (64, 16, 4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf1 = empty_strided_cuda((4, 64), (64, 1), torch.float32)
        # Topologically Sorted Source Nodes: [Xn, X_1], Original ATen: [aten.linalg_vector_norm, aten.div]
        stream0 = get_raw_stream(0)
        triton_per_fused_div_linalg_vector_norm_0.run(arg0_1, buf1, 4, 64, grid=grid(4), stream=stream0)
        del arg0_1
        buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [XX], Original ATen: [aten.mm]
        extern_kernels.mm(buf1, reinterpret_tensor(buf1, (64, 4), (1, 64), 0), out=buf2)
        buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        buf12 = empty_strided_cuda((), (), torch.float32)
        # Topologically Sorted Source Nodes: [mul, add, X_L2, X_L2_1, mean, mul_1, gamma, neg, mul_2, kernel_XX, diag_2, tK, sum_1], Original ATen: [aten.mul, aten.add, aten.clamp, aten.mean, aten.reciprocal, aten.neg, aten.exp, aten.diagonal_copy, aten.sub, aten.sum]
        triton_per_fused_add_clamp_diagonal_copy_exp_mean_mul_neg_reciprocal_sub_sum_1.run(buf2, buf4, buf12, 1, 16, grid=grid(1), stream=stream0)
        buf6 = buf1; del buf1  # reuse
        # Topologically Sorted Source Nodes: [Xn_1, X_3], Original ATen: [aten.linalg_vector_norm, aten.div]
        triton_per_fused_div_linalg_vector_norm_0.run(arg1_1, buf6, 4, 64, grid=grid(4), stream=stream0)
        del arg1_1
        buf7 = buf2; del buf2  # reuse
        # Topologically Sorted Source Nodes: [XX_1], Original ATen: [aten.mm]
        extern_kernels.mm(buf6, reinterpret_tensor(buf6, (64, 4), (1, 64), 0), out=buf7)
        del buf6
        buf9 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        buf13 = empty_strided_cuda((), (), torch.float32)
        # Topologically Sorted Source Nodes: [mul_3, add_2, X_L2_2, X_L2_3, mean_1, mul_4, gamma_1, neg_1, mul_5, kernel_XX_1, diag_3, tL, sum_2], Original ATen: [aten.mul, aten.add, aten.clamp, aten.mean, aten.reciprocal, aten.neg, aten.exp, aten.diagonal_copy, aten.sub, aten.sum]
        triton_per_fused_add_clamp_diagonal_copy_exp_mean_mul_neg_reciprocal_sub_sum_1.run(buf7, buf9, buf13, 1, 16, grid=grid(1), stream=stream0)
        buf10 = buf7; del buf7  # reuse
        # Topologically Sorted Source Nodes: [matmul_2], Original ATen: [aten.mm]
        extern_kernels.mm(buf4, buf9, out=buf10)
        buf11 = empty_strided_cuda((), (), torch.float32)
        buf15 = buf11; del buf11  # reuse
        # Topologically Sorted Source Nodes: [trace, mul_6, truediv_2, truediv_3, add_4, sum_3, sum_4, dot, mul_7, truediv_4, hsic, truediv_5, neg_2], Original ATen: [aten.trace, aten.mul, aten.div, aten.add, aten.sum, aten.dot, aten.sub, aten.neg]
        triton_per_fused_add_div_dot_mul_neg_sub_sum_trace_2.run(buf15, buf10, buf4, buf9, buf12, buf13, 1, 4, grid=grid(1), stream=stream0)
        del buf10
        del buf12
        del buf13
        del buf4
        del buf9
    return (buf15, )


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, 4, 4, 4), (64, 16, 4, 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
import torch.nn as nn


class HSIC(nn.Module):
    """Base class for the finite sample estimator of Hilbert-Schmidt Independence Criterion (HSIC)
    ..math:: HSIC (X, Y) := || C_{x, y} ||^2_{HS}, where HSIC (X, Y) = 0 iif X and Y are independent.
    Empirically, we use the finite sample estimator of HSIC (with m observations) by,
    (1) biased estimator (HSIC_0)
        Gretton, Arthur, et al. "Measuring statistical dependence with Hilbert-Schmidt norms." 2005.
        :math: (m - 1)^2 tr KHLH.
        where K_{ij} = kernel_x (x_i, x_j), L_{ij} = kernel_y (y_i, y_j), H = 1 - m^{-1} 1 1 (Hence, K, L, H are m by m matrices).
    (2) unbiased estimator (HSIC_1)
        Song, Le, et al. "Feature selection via dependence maximization." 2012.
        :math: rac{1}{m (m - 3)} igg[ tr (	ilde K 	ilde L) + rac{1^	op 	ilde K 1 1^	op 	ilde L 1}{(m-1)(m-2)} - rac{2}{m-2} 1^	op 	ilde K 	ilde L 1 igg].
        where 	ilde K and 	ilde L are related to K and L by the diagonal entries of 	ilde K_{ij} and 	ilde L_{ij} are set to zero.
    Parameters
    ----------
    sigma_x : float
        the kernel size of the kernel function for X.
    sigma_y : float
        the kernel size of the kernel function for Y.
    algorithm: str ('unbiased' / 'biased')
        the algorithm for the finite sample estimator. 'unbiased' is used for our paper.
    reduction: not used (for compatibility with other losses).
    """

    def __init__(self, sigma_x, sigma_y=None, algorithm='unbiased',
        reduction=None):
        super(HSIC, self).__init__()
        if sigma_y is None:
            sigma_y = sigma_x
        self.sigma_x = sigma_x
        self.sigma_y = sigma_y
        if algorithm == 'biased':
            self.estimator = self.biased_estimator
        elif algorithm == 'unbiased':
            self.estimator = self.unbiased_estimator
        else:
            raise ValueError('invalid estimator: {}'.format(algorithm))

    def _kernel_x(self, X):
        raise NotImplementedError

    def _kernel_y(self, Y):
        raise NotImplementedError

    def biased_estimator(self, input1, input2):
        """Biased estimator of Hilbert-Schmidt Independence Criterion
        Gretton, Arthur, et al. "Measuring statistical dependence with Hilbert-Schmidt norms." 2005.
        """
        K = self._kernel_x(input1)
        L = self._kernel_y(input2)
        KH = K - K.mean(0, keepdim=True)
        LH = L - L.mean(0, keepdim=True)
        N = len(input1)
        return torch.trace(KH @ LH / (N - 1) ** 2)

    def unbiased_estimator(self, input1, input2):
        """Unbiased estimator of Hilbert-Schmidt Independence Criterion
        Song, Le, et al. "Feature selection via dependence maximization." 2012.
        """
        kernel_XX = self._kernel_x(input1)
        kernel_YY = self._kernel_y(input2)
        tK = kernel_XX - torch.diag(kernel_XX)
        tL = kernel_YY - torch.diag(kernel_YY)
        N = len(input1)
        hsic = torch.trace(tK @ tL) + torch.sum(tK) * torch.sum(tL) / (N - 1
            ) / (N - 2) - 2 * torch.sum(tK, 0).dot(torch.sum(tL, 0)) / (N - 2)
        return hsic / (N * (N - 3))

    def forward(self, input1, input2, **kwargs):
        return self.estimator(input1, input2)


class RbfHSIC(HSIC):
    """Radial Basis Function (RBF) kernel HSIC implementation.
    """

    def _kernel(self, X, sigma):
        X = X.view(len(X), -1)
        Xn = X.norm(2, dim=1, keepdim=True)
        X = X.div(Xn)
        XX = X @ X.t()
        X_sqnorms = torch.diag(XX)
        X_L2 = -2 * XX + X_sqnorms.unsqueeze(1) + X_sqnorms.unsqueeze(0)
        X_L2 = X_L2.clamp(1e-12)
        sigma_avg = X_L2.mean().detach()
        gamma = 1 / (2 * sigma_avg)
        kernel_XX = torch.exp(-gamma * X_L2)
        return kernel_XX

    def _kernel_x(self, X):
        return self._kernel(X, self.sigma_x)

    def _kernel_y(self, Y):
        return self._kernel(Y, self.sigma_y)


class MinusRbfHSIC(RbfHSIC):
    """``Minus'' RbfHSIC for the ``max'' optimization.
    """

    def forward(self, input1, input2, **kwargs):
        return -self.estimator(input1, input2)


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


def get_init_inputs():
    return [[], {'sigma_x': 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 import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice, 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_div_linalg_vector_norm_0(in_ptr0, out_ptr1, xnumel,
    rnumel, XBLOCK: tl.constexpr):
    xnumel = 4
    RBLOCK: tl.constexpr = 64
    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)
    r1 = rindex
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (r1 + 64 * x0), xmask, other=0.0)
    tmp1 = tmp0 * tmp0
    tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
    tmp4 = tl.where(xmask, tmp2, 0)
    tmp5 = tl.sum(tmp4, 1)[:, None]
    tmp6 = libdevice.sqrt(tmp5)
    tmp7 = tmp0 / tmp6
    tl.store(out_ptr1 + (r1 + 64 * x0), tmp7, xmask)


@triton.jit
def triton_per_fused_add_clamp_diagonal_copy_exp_mean_mul_neg_reciprocal_sub_sum_1(
    in_ptr0, out_ptr1, out_ptr2, xnumel, rnumel, XBLOCK: tl.constexpr):
    RBLOCK: tl.constexpr = 16
    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)
    r2 = rindex
    r1 = rindex // 4
    r0 = rindex % 4
    tmp0 = tl.load(in_ptr0 + r2, None)
    tmp3 = tl.load(in_ptr0 + 5 * r1, None, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr0 + 5 * r0, None, eviction_policy='evict_last')
    tmp1 = -2.0
    tmp2 = tmp0 * tmp1
    tmp4 = tmp2 + tmp3
    tmp6 = tmp4 + tmp5
    tmp7 = 1e-12
    tmp8 = triton_helpers.maximum(tmp6, tmp7)
    tmp9 = tl.broadcast_to(tmp8, [XBLOCK, RBLOCK])
    tmp11 = tl.sum(tmp9, 1)[:, None]
    tmp12 = 16.0
    tmp13 = tmp11 / tmp12
    tmp14 = 2.0
    tmp15 = tmp13 * tmp14
    tmp16 = tl.full([1, 1], 1, tl.int32)
    tmp17 = tmp16 / tmp15
    tmp18 = 1.0
    tmp19 = tmp17 * tmp18
    tmp20 = -tmp19
    tmp21 = tmp20 * tmp8
    tmp22 = tl_math.exp(tmp21)
    tmp23 = tmp5 * tmp1
    tmp24 = tmp23 + tmp5
    tmp25 = tmp24 + tmp5
    tmp26 = triton_helpers.maximum(tmp25, tmp7)
    tmp27 = tmp20 * tmp26
    tmp28 = tl_math.exp(tmp27)
    tmp29 = tmp22 - tmp28
    tmp30 = tl.broadcast_to(tmp29, [XBLOCK, RBLOCK])
    tmp32 = tl.sum(tmp30, 1)[:, None]
    tl.store(out_ptr1 + tl.broadcast_to(r2, [XBLOCK, RBLOCK]), tmp29, None)
    tl.store(out_ptr2 + tl.full([XBLOCK, 1], 0, tl.int32), tmp32, None)


@triton.jit
def triton_per_fused_add_div_dot_mul_neg_sub_sum_trace_2(in_out_ptr0,
    in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, 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 + 5 * r0, None, eviction_policy='evict_last')
    tmp4 = tl.load(in_ptr1 + r0, None)
    tmp5 = tl.load(in_ptr1 + (4 + r0), None)
    tmp7 = tl.load(in_ptr1 + (8 + r0), None)
    tmp9 = tl.load(in_ptr1 + (12 + r0), None)
    tmp11 = tl.load(in_ptr2 + r0, None)
    tmp12 = tl.load(in_ptr2 + (4 + r0), None)
    tmp14 = tl.load(in_ptr2 + (8 + r0), None)
    tmp16 = tl.load(in_ptr2 + (12 + r0), None)
    tmp22 = tl.load(in_ptr3 + 0)
    tmp23 = tl.broadcast_to(tmp22, [XBLOCK, 1])
    tmp24 = tl.load(in_ptr4 + 0)
    tmp25 = tl.broadcast_to(tmp24, [XBLOCK, 1])
    tmp1 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
    tmp3 = tl.sum(tmp1, 1)[:, None]
    tmp6 = tmp4 + tmp5
    tmp8 = tmp6 + tmp7
    tmp10 = tmp8 + tmp9
    tmp13 = tmp11 + tmp12
    tmp15 = tmp13 + tmp14
    tmp17 = tmp15 + tmp16
    tmp18 = tmp10 * tmp17
    tmp19 = tl.broadcast_to(tmp18, [XBLOCK, RBLOCK])
    tmp21 = tl.sum(tmp19, 1)[:, None]
    tmp26 = tmp23 * tmp25
    tmp27 = 0.3333333333333333
    tmp28 = tmp26 * tmp27
    tmp29 = 0.5
    tmp30 = tmp28 * tmp29
    tmp31 = tmp3 + tmp30
    tmp32 = 2.0
    tmp33 = tmp21 * tmp32
    tmp34 = tmp33 * tmp29
    tmp35 = tmp31 - tmp34
    tmp36 = 0.25
    tmp37 = tmp35 * tmp36
    tmp38 = -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, 4, 4, 4), (64, 16, 4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf1 = empty_strided_cuda((4, 64), (64, 1), torch.float32)
        get_raw_stream(0)
        triton_per_fused_div_linalg_vector_norm_0[grid(4)](arg0_1, buf1, 4,
            64, XBLOCK=1, num_warps=2, num_stages=1)
        del arg0_1
        buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        extern_kernels.mm(buf1, reinterpret_tensor(buf1, (64, 4), (1, 64), 
            0), out=buf2)
        buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        buf12 = empty_strided_cuda((), (), torch.float32)
        triton_per_fused_add_clamp_diagonal_copy_exp_mean_mul_neg_reciprocal_sub_sum_1[
            grid(1)](buf2, buf4, buf12, 1, 16, XBLOCK=1, num_warps=2,
            num_stages=1)
        buf6 = buf1
        del buf1
        triton_per_fused_div_linalg_vector_norm_0[grid(4)](arg1_1, buf6, 4,
            64, XBLOCK=1, num_warps=2, num_stages=1)
        del arg1_1
        buf7 = buf2
        del buf2
        extern_kernels.mm(buf6, reinterpret_tensor(buf6, (64, 4), (1, 64), 
            0), out=buf7)
        del buf6
        buf9 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        buf13 = empty_strided_cuda((), (), torch.float32)
        triton_per_fused_add_clamp_diagonal_copy_exp_mean_mul_neg_reciprocal_sub_sum_1[
            grid(1)](buf7, buf9, buf13, 1, 16, XBLOCK=1, num_warps=2,
            num_stages=1)
        buf10 = buf7
        del buf7
        extern_kernels.mm(buf4, buf9, out=buf10)
        buf11 = empty_strided_cuda((), (), torch.float32)
        buf15 = buf11
        del buf11
        triton_per_fused_add_div_dot_mul_neg_sub_sum_trace_2[grid(1)](buf15,
            buf10, buf4, buf9, buf12, buf13, 1, 4, XBLOCK=1, num_warps=2,
            num_stages=1)
        del buf10
        del buf12
        del buf13
        del buf4
        del buf9
    return buf15,


class HSIC(nn.Module):
    """Base class for the finite sample estimator of Hilbert-Schmidt Independence Criterion (HSIC)
    ..math:: HSIC (X, Y) := || C_{x, y} ||^2_{HS}, where HSIC (X, Y) = 0 iif X and Y are independent.
    Empirically, we use the finite sample estimator of HSIC (with m observations) by,
    (1) biased estimator (HSIC_0)
        Gretton, Arthur, et al. "Measuring statistical dependence with Hilbert-Schmidt norms." 2005.
        :math: (m - 1)^2 tr KHLH.
        where K_{ij} = kernel_x (x_i, x_j), L_{ij} = kernel_y (y_i, y_j), H = 1 - m^{-1} 1 1 (Hence, K, L, H are m by m matrices).
    (2) unbiased estimator (HSIC_1)
        Song, Le, et al. "Feature selection via dependence maximization." 2012.
        :math: rac{1}{m (m - 3)} igg[ tr (	ilde K 	ilde L) + rac{1^	op 	ilde K 1 1^	op 	ilde L 1}{(m-1)(m-2)} - rac{2}{m-2} 1^	op 	ilde K 	ilde L 1 igg].
        where 	ilde K and 	ilde L are related to K and L by the diagonal entries of 	ilde K_{ij} and 	ilde L_{ij} are set to zero.
    Parameters
    ----------
    sigma_x : float
        the kernel size of the kernel function for X.
    sigma_y : float
        the kernel size of the kernel function for Y.
    algorithm: str ('unbiased' / 'biased')
        the algorithm for the finite sample estimator. 'unbiased' is used for our paper.
    reduction: not used (for compatibility with other losses).
    """

    def __init__(self, sigma_x, sigma_y=None, algorithm='unbiased',
        reduction=None):
        super(HSIC, self).__init__()
        if sigma_y is None:
            sigma_y = sigma_x
        self.sigma_x = sigma_x
        self.sigma_y = sigma_y
        if algorithm == 'biased':
            self.estimator = self.biased_estimator
        elif algorithm == 'unbiased':
            self.estimator = self.unbiased_estimator
        else:
            raise ValueError('invalid estimator: {}'.format(algorithm))

    def _kernel_x(self, X):
        raise NotImplementedError

    def _kernel_y(self, Y):
        raise NotImplementedError

    def biased_estimator(self, input1, input2):
        """Biased estimator of Hilbert-Schmidt Independence Criterion
        Gretton, Arthur, et al. "Measuring statistical dependence with Hilbert-Schmidt norms." 2005.
        """
        K = self._kernel_x(input1)
        L = self._kernel_y(input2)
        KH = K - K.mean(0, keepdim=True)
        LH = L - L.mean(0, keepdim=True)
        N = len(input1)
        return torch.trace(KH @ LH / (N - 1) ** 2)

    def unbiased_estimator(self, input1, input2):
        """Unbiased estimator of Hilbert-Schmidt Independence Criterion
        Song, Le, et al. "Feature selection via dependence maximization." 2012.
        """
        kernel_XX = self._kernel_x(input1)
        kernel_YY = self._kernel_y(input2)
        tK = kernel_XX - torch.diag(kernel_XX)
        tL = kernel_YY - torch.diag(kernel_YY)
        N = len(input1)
        hsic = torch.trace(tK @ tL) + torch.sum(tK) * torch.sum(tL) / (N - 1
            ) / (N - 2) - 2 * torch.sum(tK, 0).dot(torch.sum(tL, 0)) / (N - 2)
        return hsic / (N * (N - 3))

    def forward(self, input1, input2, **kwargs):
        return self.estimator(input1, input2)


class RbfHSIC(HSIC):
    """Radial Basis Function (RBF) kernel HSIC implementation.
    """

    def _kernel(self, X, sigma):
        X = X.view(len(X), -1)
        Xn = X.norm(2, dim=1, keepdim=True)
        X = X.div(Xn)
        XX = X @ X.t()
        X_sqnorms = torch.diag(XX)
        X_L2 = -2 * XX + X_sqnorms.unsqueeze(1) + X_sqnorms.unsqueeze(0)
        X_L2 = X_L2.clamp(1e-12)
        sigma_avg = X_L2.mean().detach()
        gamma = 1 / (2 * sigma_avg)
        kernel_XX = torch.exp(-gamma * X_L2)
        return kernel_XX

    def _kernel_x(self, X):
        return self._kernel(X, self.sigma_x)

    def _kernel_y(self, Y):
        return self._kernel(Y, self.sigma_y)


class MinusRbfHSICNew(RbfHSIC):
    """``Minus'' RbfHSIC for the ``max'' optimization.
    """

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