# 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/lo/clogbilbksb5pe5z7x7zzgxgebeyhflxrjymvbwjeoos6el7ofav.py
# Topologically Sorted Source Nodes: [raw_scores_2, mul_1, tanh, x_clip, max_1, mul_3, pos_scores, pos_shiftexp, sub_3, exp_1, sub_2, exp, mul_6, neg_sumexp, add, all_logsumexp, nce_scores, mean_1, nce_scores_1], Original ATen: [aten.div, aten.mul, aten.tanh, aten.max, aten.sum, aten.sub, aten.exp, aten.add, aten.log, aten.mean, aten.neg]
# Source node to ATen node mapping:
#   add => add
#   all_logsumexp => log
#   exp => exp
#   exp_1 => exp_1
#   max_1 => max_1
#   mean_1 => mean_1
#   mul_1 => mul_1
#   mul_3 => mul_3
#   mul_6 => mul_6
#   nce_scores => sub_5
#   nce_scores_1 => neg
#   neg_sumexp => sum_2
#   pos_scores => sum_1
#   pos_shiftexp => sub_4
#   raw_scores_2 => div
#   sub_2 => sub_2
#   sub_3 => sub_3
#   tanh => tanh
#   x_clip => mul_2
# Graph fragment:
#   %div : [num_users=2] = call_function[target=torch.ops.aten.div.Tensor](args = (%view, 2.0), kwargs = {})
#   %mul_1 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%div, 0.25), kwargs = {})
#   %tanh : [num_users=1] = call_function[target=torch.ops.aten.tanh.default](args = (%mul_1,), kwargs = {})
#   %mul_2 : [num_users=2] = call_function[target=torch.ops.aten.mul.Tensor](args = (%tanh, 4), kwargs = {})
#   %max_1 : [num_users=1] = call_function[target=torch.ops.aten.max.dim](args = (%view_1, 1, True), kwargs = {})
#   %mul_3 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%expand, %mul_2), kwargs = {})
#   %sum_1 : [num_users=2] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%mul_3, [1]), kwargs = {})
#   %sub_4 : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%sum_1, %getitem), kwargs = {})
#   %sub_3 : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%sum_1, %getitem), kwargs = {})
#   %exp_1 : [num_users=1] = call_function[target=torch.ops.aten.exp.default](args = (%sub_3,), kwargs = {})
#   %sub_2 : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%view_1, %getitem), kwargs = {})
#   %exp : [num_users=1] = call_function[target=torch.ops.aten.exp.default](args = (%sub_2,), kwargs = {})
#   %mul_6 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%view_2, %exp), kwargs = {})
#   %sum_2 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%mul_6, [1], True), kwargs = {})
#   %add : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%exp_1, %sum_2), kwargs = {})
#   %log : [num_users=1] = call_function[target=torch.ops.aten.log.default](args = (%add,), kwargs = {})
#   %sub_5 : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%sub_4, %log), kwargs = {})
#   %mean_1 : [num_users=1] = call_function[target=torch.ops.aten.mean.default](args = (%sub_5,), kwargs = {})
#   %neg : [num_users=1] = call_function[target=torch.ops.aten.neg.default](args = (%mean_1,), kwargs = {})
triton_per_fused_add_div_exp_log_max_mean_mul_neg_sub_sum_tanh_0 = async_compile.triton('triton_per_fused_add_div_exp_log_max_mean_mul_neg_sub_sum_tanh_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=[1, 4],
    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), equal_to_1=(3,))]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_per_fused_add_div_exp_log_max_mean_mul_neg_sub_sum_tanh_0', 'mutated_arg_names': ['in_out_ptr0'], 'no_x_dim': False, 'num_load': 8, '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_add_div_exp_log_max_mean_mul_neg_sub_sum_tanh_0(in_out_ptr0, in_ptr0, in_ptr1, 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 + (4*r0), None, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr1 + (4*r0), None, eviction_policy='evict_last')
    tmp14 = tl.load(in_ptr0 + (1 + (4*r0)), None, eviction_policy='evict_last')
    tmp16 = tl.load(in_ptr1 + (1 + (4*r0)), None, eviction_policy='evict_last')
    tmp25 = tl.load(in_ptr0 + (2 + (4*r0)), None, eviction_policy='evict_last')
    tmp27 = tl.load(in_ptr1 + (2 + (4*r0)), None, eviction_policy='evict_last')
    tmp36 = tl.load(in_ptr0 + (3 + (4*r0)), None, eviction_policy='evict_last')
    tmp38 = tl.load(in_ptr1 + (3 + (4*r0)), None, eviction_policy='evict_last')
    tmp1 = 1.0
    tmp2 = tmp1 - tmp0
    tmp4 = 0.5
    tmp5 = tmp3 * tmp4
    tmp6 = 0.25
    tmp7 = tmp5 * tmp6
    tmp8 = libdevice.tanh(tmp7)
    tmp9 = 4.0
    tmp10 = tmp8 * tmp9
    tmp11 = tmp2 * tmp10
    tmp12 = tmp0 * tmp9
    tmp13 = tmp11 - tmp12
    tmp15 = tmp1 - tmp14
    tmp17 = tmp16 * tmp4
    tmp18 = tmp17 * tmp6
    tmp19 = libdevice.tanh(tmp18)
    tmp20 = tmp19 * tmp9
    tmp21 = tmp15 * tmp20
    tmp22 = tmp14 * tmp9
    tmp23 = tmp21 - tmp22
    tmp24 = triton_helpers.maximum(tmp13, tmp23)
    tmp26 = tmp1 - tmp25
    tmp28 = tmp27 * tmp4
    tmp29 = tmp28 * tmp6
    tmp30 = libdevice.tanh(tmp29)
    tmp31 = tmp30 * tmp9
    tmp32 = tmp26 * tmp31
    tmp33 = tmp25 * tmp9
    tmp34 = tmp32 - tmp33
    tmp35 = triton_helpers.maximum(tmp24, tmp34)
    tmp37 = tmp1 - tmp36
    tmp39 = tmp38 * tmp4
    tmp40 = tmp39 * tmp6
    tmp41 = libdevice.tanh(tmp40)
    tmp42 = tmp41 * tmp9
    tmp43 = tmp37 * tmp42
    tmp44 = tmp36 * tmp9
    tmp45 = tmp43 - tmp44
    tmp46 = triton_helpers.maximum(tmp35, tmp45)
    tmp47 = tmp13 - tmp46
    tmp48 = tl_math.exp(tmp47)
    tmp49 = tmp2 * tmp48
    tmp50 = tmp23 - tmp46
    tmp51 = tl_math.exp(tmp50)
    tmp52 = tmp15 * tmp51
    tmp53 = tmp49 + tmp52
    tmp54 = tmp34 - tmp46
    tmp55 = tl_math.exp(tmp54)
    tmp56 = tmp26 * tmp55
    tmp57 = tmp53 + tmp56
    tmp58 = tmp45 - tmp46
    tmp59 = tl_math.exp(tmp58)
    tmp60 = tmp37 * tmp59
    tmp61 = tmp57 + tmp60
    tmp62 = tmp0 * tmp10
    tmp63 = tmp14 * tmp20
    tmp64 = tmp62 + tmp63
    tmp65 = tmp25 * tmp31
    tmp66 = tmp64 + tmp65
    tmp67 = tmp36 * tmp42
    tmp68 = tmp66 + tmp67
    tmp69 = tmp68 - tmp46
    tmp70 = tl_math.exp(tmp69)
    tmp71 = tmp70 + tmp61
    tmp72 = tl_math.log(tmp71)
    tmp73 = tmp69 - tmp72
    tmp74 = tl.broadcast_to(tmp73, [XBLOCK, RBLOCK])
    tmp76 = tl.sum(tmp74, 1)[:, None]
    tmp77 = tmp76 / tmp9
    tmp78 = -tmp77
    tl.debug_barrier()
    tl.store(in_out_ptr0 + (tl.full([XBLOCK, 1], 0, tl.int32)), tmp78, None)
''', device_str='cuda')


# kernel path: runs/run_shard_4/inductor_cache/i7/ci7wfxaextt4cz2wvuqp24v6te3ikcbwiocamjs25ysoohh6nywz.py
# Topologically Sorted Source Nodes: [raw_scores_2, pow_1, mean, lgt_reg], Original ATen: [aten.div, aten.pow, aten.mean, aten.mul]
# Source node to ATen node mapping:
#   lgt_reg => mul
#   mean => mean
#   pow_1 => pow_1
#   raw_scores_2 => div
# Graph fragment:
#   %div : [num_users=2] = call_function[target=torch.ops.aten.div.Tensor](args = (%view, 2.0), kwargs = {})
#   %pow_1 : [num_users=1] = call_function[target=torch.ops.aten.pow.Tensor_Scalar](args = (%div, 2.0), kwargs = {})
#   %mean : [num_users=1] = call_function[target=torch.ops.aten.mean.default](args = (%pow_1,), kwargs = {})
#   %mul : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%mean, 0.05), kwargs = {})
triton_per_fused_div_mean_mul_pow_1 = async_compile.triton('triton_per_fused_div_mean_mul_pow_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.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': {2: 1}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 3), equal_to_1=(2,))]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_per_fused_div_mean_mul_pow_1', 'mutated_arg_names': ['in_out_ptr0'], '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_mean_mul_pow_1(in_out_ptr0, in_ptr0, 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)
    r0 = rindex
    tmp0 = tl.load(in_ptr0 + (r0), None)
    tmp1 = 0.5
    tmp2 = tmp0 * tmp1
    tmp3 = tmp2 * tmp2
    tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
    tmp6 = tl.sum(tmp4, 1)[:, None]
    tmp7 = 16.0
    tmp8 = tmp6 / tmp7
    tmp9 = 0.05
    tmp10 = tmp8 * tmp9
    tl.debug_barrier()
    tl.store(in_out_ptr0 + (tl.full([XBLOCK, 1], 0, tl.int32)), tmp10, None)
''', device_str='cuda')


async_compile.wait(globals())
del async_compile

def call(args):
    arg0_1, arg1_1, arg2_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4), (4, 1))
    assert_size_stride(arg1_1, (4, 4), (4, 1))
    assert_size_stride(arg2_1, (4, 4), (4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [mm], Original ATen: [aten.mm]
        extern_kernels.mm(arg0_1, arg1_1, out=buf0)
        del arg0_1
        del arg1_1
        buf4 = empty_strided_cuda((), (), torch.float32)
        buf6 = buf4; del buf4  # reuse
        # Topologically Sorted Source Nodes: [raw_scores_2, mul_1, tanh, x_clip, max_1, mul_3, pos_scores, pos_shiftexp, sub_3, exp_1, sub_2, exp, mul_6, neg_sumexp, add, all_logsumexp, nce_scores, mean_1, nce_scores_1], Original ATen: [aten.div, aten.mul, aten.tanh, aten.max, aten.sum, aten.sub, aten.exp, aten.add, aten.log, aten.mean, aten.neg]
        stream0 = get_raw_stream(0)
        triton_per_fused_add_div_exp_log_max_mean_mul_neg_sub_sum_tanh_0.run(buf6, arg2_1, buf0, 1, 4, grid=grid(1), stream=stream0)
        del arg2_1
        buf5 = empty_strided_cuda((), (), torch.float32)
        buf7 = buf5; del buf5  # reuse
        # Topologically Sorted Source Nodes: [raw_scores_2, pow_1, mean, lgt_reg], Original ATen: [aten.div, aten.pow, aten.mean, aten.mul]
        triton_per_fused_div_mean_mul_pow_1.run(buf7, buf0, 1, 16, grid=grid(1), stream=stream0)
        del buf0
    return (buf6, buf7, )


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, 1), device='cuda:0', dtype=torch.float32)
    arg1_1 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    arg2_1 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    fn = lambda: call([arg0_1, arg1_1, arg2_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 nn as nn
from torch import optim as optim


def tanh_clip(x, clip_val=10.0):
    """
    soft clip values to the range [-clip_val, +clip_val]
    """
    if clip_val is not None:
        x_clip = clip_val * torch.tanh(1.0 / clip_val * x)
    else:
        x_clip = x
    return x_clip


class AmdimNCELoss(nn.Module):
    """
    Compute the NCE scores for predicting r_src->r_trg.
    """

    def __init__(self, tclip):
        super().__init__()
        self.tclip = tclip

    def forward(self, anchor_representations, positive_representations,
        mask_mat):
        """
        Args:
            anchor_representations: (batch_size, emb_dim)
            positive_representations: (emb_dim, n_batch * w* h) (ie: nb_feat_vectors x embedding_dim)
            mask_mat: (n_batch_gpu, n_batch)

        Output:
            raw_scores: (n_batch_gpu, n_locs)
            nce_scores: (n_batch_gpu, n_locs)
            lgt_reg : scalar
        """
        r_src = anchor_representations
        r_trg = positive_representations
        batch_size, emb_dim = r_src.size()
        nb_feat_vectors = r_trg.size(1) // batch_size
        mask_pos = mask_mat.unsqueeze(dim=2).expand(-1, -1, nb_feat_vectors
            ).float()
        mask_neg = 1.0 - mask_pos
        raw_scores = torch.mm(r_src, r_trg).float()
        raw_scores = raw_scores.reshape(batch_size, batch_size, nb_feat_vectors
            )
        raw_scores = raw_scores / emb_dim ** 0.5
        lgt_reg = 0.05 * (raw_scores ** 2.0).mean()
        raw_scores = tanh_clip(raw_scores, clip_val=self.tclip)
        """
        pos_scores includes scores for all the positive samples
        neg_scores includes scores for all the negative samples, with
        scores for positive samples set to the min score (-self.tclip here)
        """
        pos_scores = (mask_pos * raw_scores).sum(dim=1)
        neg_scores = mask_neg * raw_scores - self.tclip * mask_pos
        neg_scores = neg_scores.reshape(batch_size, -1)
        mask_neg = mask_neg.reshape(batch_size, -1)
        neg_maxes = torch.max(neg_scores, dim=1, keepdim=True)[0]
        neg_sumexp = (mask_neg * torch.exp(neg_scores - neg_maxes)).sum(dim
            =1, keepdim=True)
        all_logsumexp = torch.log(torch.exp(pos_scores - neg_maxes) +
            neg_sumexp)
        pos_shiftexp = pos_scores - neg_maxes
        nce_scores = pos_shiftexp - all_logsumexp
        nce_scores = -nce_scores.mean()
        return nce_scores, lgt_reg


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


def get_init_inputs():
    return [[], {'tclip': 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
from torch import nn as nn
from torch import optim as optim
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda


@triton.jit
def triton_per_fused_add_div_exp_log_max_mean_mul_neg_sub_sum_tanh_0(
    in_out_ptr0, in_ptr0, in_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
    RBLOCK: tl.constexpr = 4
    xoffset = tl.program_id(0) * XBLOCK
    xoffset + tl.arange(0, XBLOCK)[:, None]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    rindex = tl.arange(0, RBLOCK)[None, :]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    r0 = rindex
    tmp0 = tl.load(in_ptr0 + 4 * r0, None, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr1 + 4 * r0, None, eviction_policy='evict_last')
    tmp14 = tl.load(in_ptr0 + (1 + 4 * r0), None, eviction_policy='evict_last')
    tmp16 = tl.load(in_ptr1 + (1 + 4 * r0), None, eviction_policy='evict_last')
    tmp25 = tl.load(in_ptr0 + (2 + 4 * r0), None, eviction_policy='evict_last')
    tmp27 = tl.load(in_ptr1 + (2 + 4 * r0), None, eviction_policy='evict_last')
    tmp36 = tl.load(in_ptr0 + (3 + 4 * r0), None, eviction_policy='evict_last')
    tmp38 = tl.load(in_ptr1 + (3 + 4 * r0), None, eviction_policy='evict_last')
    tmp1 = 1.0
    tmp2 = tmp1 - tmp0
    tmp4 = 0.5
    tmp5 = tmp3 * tmp4
    tmp6 = 0.25
    tmp7 = tmp5 * tmp6
    tmp8 = libdevice.tanh(tmp7)
    tmp9 = 4.0
    tmp10 = tmp8 * tmp9
    tmp11 = tmp2 * tmp10
    tmp12 = tmp0 * tmp9
    tmp13 = tmp11 - tmp12
    tmp15 = tmp1 - tmp14
    tmp17 = tmp16 * tmp4
    tmp18 = tmp17 * tmp6
    tmp19 = libdevice.tanh(tmp18)
    tmp20 = tmp19 * tmp9
    tmp21 = tmp15 * tmp20
    tmp22 = tmp14 * tmp9
    tmp23 = tmp21 - tmp22
    tmp24 = triton_helpers.maximum(tmp13, tmp23)
    tmp26 = tmp1 - tmp25
    tmp28 = tmp27 * tmp4
    tmp29 = tmp28 * tmp6
    tmp30 = libdevice.tanh(tmp29)
    tmp31 = tmp30 * tmp9
    tmp32 = tmp26 * tmp31
    tmp33 = tmp25 * tmp9
    tmp34 = tmp32 - tmp33
    tmp35 = triton_helpers.maximum(tmp24, tmp34)
    tmp37 = tmp1 - tmp36
    tmp39 = tmp38 * tmp4
    tmp40 = tmp39 * tmp6
    tmp41 = libdevice.tanh(tmp40)
    tmp42 = tmp41 * tmp9
    tmp43 = tmp37 * tmp42
    tmp44 = tmp36 * tmp9
    tmp45 = tmp43 - tmp44
    tmp46 = triton_helpers.maximum(tmp35, tmp45)
    tmp47 = tmp13 - tmp46
    tmp48 = tl_math.exp(tmp47)
    tmp49 = tmp2 * tmp48
    tmp50 = tmp23 - tmp46
    tmp51 = tl_math.exp(tmp50)
    tmp52 = tmp15 * tmp51
    tmp53 = tmp49 + tmp52
    tmp54 = tmp34 - tmp46
    tmp55 = tl_math.exp(tmp54)
    tmp56 = tmp26 * tmp55
    tmp57 = tmp53 + tmp56
    tmp58 = tmp45 - tmp46
    tmp59 = tl_math.exp(tmp58)
    tmp60 = tmp37 * tmp59
    tmp61 = tmp57 + tmp60
    tmp62 = tmp0 * tmp10
    tmp63 = tmp14 * tmp20
    tmp64 = tmp62 + tmp63
    tmp65 = tmp25 * tmp31
    tmp66 = tmp64 + tmp65
    tmp67 = tmp36 * tmp42
    tmp68 = tmp66 + tmp67
    tmp69 = tmp68 - tmp46
    tmp70 = tl_math.exp(tmp69)
    tmp71 = tmp70 + tmp61
    tmp72 = tl_math.log(tmp71)
    tmp73 = tmp69 - tmp72
    tmp74 = tl.broadcast_to(tmp73, [XBLOCK, RBLOCK])
    tmp76 = tl.sum(tmp74, 1)[:, None]
    tmp77 = tmp76 / tmp9
    tmp78 = -tmp77
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp78, None)


@triton.jit
def triton_per_fused_div_mean_mul_pow_1(in_out_ptr0, in_ptr0, 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)
    r0 = rindex
    tmp0 = tl.load(in_ptr0 + r0, None)
    tmp1 = 0.5
    tmp2 = tmp0 * tmp1
    tmp3 = tmp2 * tmp2
    tmp4 = tl.broadcast_to(tmp3, [XBLOCK, RBLOCK])
    tmp6 = tl.sum(tmp4, 1)[:, None]
    tmp7 = 16.0
    tmp8 = tmp6 / tmp7
    tmp9 = 0.05
    tmp10 = tmp8 * tmp9
    tl.debug_barrier()
    tl.store(in_out_ptr0 + tl.full([XBLOCK, 1], 0, tl.int32), tmp10, None)


def call(args):
    arg0_1, arg1_1, arg2_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4), (4, 1))
    assert_size_stride(arg1_1, (4, 4), (4, 1))
    assert_size_stride(arg2_1, (4, 4), (4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        extern_kernels.mm(arg0_1, arg1_1, out=buf0)
        del arg0_1
        del arg1_1
        buf4 = empty_strided_cuda((), (), torch.float32)
        buf6 = buf4
        del buf4
        get_raw_stream(0)
        triton_per_fused_add_div_exp_log_max_mean_mul_neg_sub_sum_tanh_0[grid
            (1)](buf6, arg2_1, buf0, 1, 4, XBLOCK=1, num_warps=2, num_stages=1)
        del arg2_1
        buf5 = empty_strided_cuda((), (), torch.float32)
        buf7 = buf5
        del buf5
        triton_per_fused_div_mean_mul_pow_1[grid(1)](buf7, buf0, 1, 16,
            XBLOCK=1, num_warps=2, num_stages=1)
        del buf0
    return buf6, buf7


def tanh_clip(x, clip_val=10.0):
    """
    soft clip values to the range [-clip_val, +clip_val]
    """
    if clip_val is not None:
        x_clip = clip_val * torch.tanh(1.0 / clip_val * x)
    else:
        x_clip = x
    return x_clip


class AmdimNCELossNew(nn.Module):
    """
    Compute the NCE scores for predicting r_src->r_trg.
    """

    def __init__(self, tclip):
        super().__init__()
        self.tclip = tclip

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