# 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_7/inductor_cache/2b/c2bkqvv3w46os3y2jfp7zebz4v4e3jusxayajeubp3hevuxzgzn6.py
# Topologically Sorted Source Nodes: [add_1, max_1], Original ATen: [aten.add, aten.max]
# Source node to ATen node mapping:
#   add_1 => add_1
#   max_1 => max_1
# Graph fragment:
#   %add_1 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%unsqueeze_2, %unsqueeze_1), kwargs = {})
#   %max_1 : [num_users=2] = call_function[target=torch.ops.aten.max.dim](args = (%add_1, 1), kwargs = {})
triton_poi_fused_add_max_0 = async_compile.triton('triton_poi_fused_add_max_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], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: '*i64', 5: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3, 4, 5), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_add_max_0', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 12, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False},
    min_elem_per_thread=0
)
@triton.jit
def triton_poi_fused_add_max_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, xnumel, XBLOCK : tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x1 = (xindex // 4)
    x0 = xindex % 4
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + (16*x1), xmask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr1 + (0))
    tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
    tmp4 = tl.load(in_ptr2 + (x0), xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr0 + (1 + (16*x1)), xmask, eviction_policy='evict_last')
    tmp7 = tl.load(in_ptr1 + (1))
    tmp8 = tl.broadcast_to(tmp7, [XBLOCK])
    tmp10 = tl.load(in_ptr2 + (4 + x0), xmask, eviction_policy='evict_last')
    tmp13 = tl.load(in_ptr0 + (2 + (16*x1)), xmask, eviction_policy='evict_last')
    tmp14 = tl.load(in_ptr1 + (2))
    tmp15 = tl.broadcast_to(tmp14, [XBLOCK])
    tmp17 = tl.load(in_ptr2 + (8 + x0), xmask, eviction_policy='evict_last')
    tmp20 = tl.load(in_ptr0 + (3 + (16*x1)), xmask, eviction_policy='evict_last')
    tmp21 = tl.load(in_ptr1 + (3))
    tmp22 = tl.broadcast_to(tmp21, [XBLOCK])
    tmp24 = tl.load(in_ptr2 + (12 + x0), xmask, eviction_policy='evict_last')
    tmp3 = tmp0 + tmp2
    tmp5 = tmp3 + tmp4
    tmp9 = tmp6 + tmp8
    tmp11 = tmp9 + tmp10
    tmp12 = triton_helpers.maximum(tmp5, tmp11)
    tmp16 = tmp13 + tmp15
    tmp18 = tmp16 + tmp17
    tmp19 = triton_helpers.maximum(tmp12, tmp18)
    tmp23 = tmp20 + tmp22
    tmp25 = tmp23 + tmp24
    tmp26 = triton_helpers.maximum(tmp19, tmp25)
    tmp27 = tmp5 > tmp11
    tmp28 = tmp5 == tmp11
    tmp29 = tmp5 != tmp5
    tmp30 = tmp11 != tmp11
    tmp31 = tmp29 > tmp30
    tmp32 = tmp27 | tmp31
    tmp33 = tmp29 & tmp30
    tmp34 = tmp28 | tmp33
    tmp35 = tl.full([1], 0, tl.int64)
    tmp36 = tl.full([1], 1, tl.int64)
    tmp37 = tmp35 < tmp36
    tmp38 = tmp34 & tmp37
    tmp39 = tmp32 | tmp38
    tmp40 = tl.where(tmp39, tmp5, tmp11)
    tmp41 = tl.where(tmp39, tmp35, tmp36)
    tmp42 = tmp40 > tmp18
    tmp43 = tmp40 == tmp18
    tmp44 = tmp40 != tmp40
    tmp45 = tmp18 != tmp18
    tmp46 = tmp44 > tmp45
    tmp47 = tmp42 | tmp46
    tmp48 = tmp44 & tmp45
    tmp49 = tmp43 | tmp48
    tmp50 = tl.full([1], 2, tl.int64)
    tmp51 = tmp41 < tmp50
    tmp52 = tmp49 & tmp51
    tmp53 = tmp47 | tmp52
    tmp54 = tl.where(tmp53, tmp40, tmp18)
    tmp55 = tl.where(tmp53, tmp41, tmp50)
    tmp56 = tmp54 > tmp25
    tmp57 = tmp54 == tmp25
    tmp58 = tmp54 != tmp54
    tmp59 = tmp25 != tmp25
    tmp60 = tmp58 > tmp59
    tmp61 = tmp56 | tmp60
    tmp62 = tmp58 & tmp59
    tmp63 = tmp57 | tmp62
    tmp64 = tl.full([1], 3, tl.int64)
    tmp65 = tmp55 < tmp64
    tmp66 = tmp63 & tmp65
    tmp67 = tmp61 | tmp66
    tmp68 = tl.where(tmp67, tmp54, tmp25)
    tmp69 = tl.where(tmp67, tmp55, tmp64)
    tl.store(out_ptr0 + (x2), tmp26, xmask)
    tl.store(out_ptr1 + (x2), tmp69, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_7/inductor_cache/dy/cdy673rrkjiv3qikoqrlvr3x4djhltg5txuuelkcf3bbizc3xryu.py
# Topologically Sorted Source Nodes: [add_3, max_2], Original ATen: [aten.add, aten.max]
# Source node to ATen node mapping:
#   add_3 => add_3
#   max_2 => max_2
# Graph fragment:
#   %add_3 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%unsqueeze_3, %unsqueeze_1), kwargs = {})
#   %max_2 : [num_users=2] = call_function[target=torch.ops.aten.max.dim](args = (%add_3, 1), kwargs = {})
triton_poi_fused_add_max_1 = async_compile.triton('triton_poi_fused_add_max_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], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: '*i64', 5: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3, 4, 5), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_add_max_1', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 12, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False},
    min_elem_per_thread=0
)
@triton.jit
def triton_poi_fused_add_max_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, xnumel, XBLOCK : tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x1 = (xindex // 4)
    x0 = xindex % 4
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + (4*x1), xmask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr1 + (4 + (16*x1)), xmask, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr2 + (x0), xmask, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr0 + (1 + (4*x1)), xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr1 + (5 + (16*x1)), xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr2 + (4 + x0), xmask, eviction_policy='evict_last')
    tmp11 = tl.load(in_ptr0 + (2 + (4*x1)), xmask, eviction_policy='evict_last')
    tmp12 = tl.load(in_ptr1 + (6 + (16*x1)), xmask, eviction_policy='evict_last')
    tmp14 = tl.load(in_ptr2 + (8 + x0), xmask, eviction_policy='evict_last')
    tmp17 = tl.load(in_ptr0 + (3 + (4*x1)), xmask, eviction_policy='evict_last')
    tmp18 = tl.load(in_ptr1 + (7 + (16*x1)), xmask, eviction_policy='evict_last')
    tmp20 = tl.load(in_ptr2 + (12 + x0), xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp4 = tmp2 + tmp3
    tmp7 = tmp5 + tmp6
    tmp9 = tmp7 + tmp8
    tmp10 = triton_helpers.maximum(tmp4, tmp9)
    tmp13 = tmp11 + tmp12
    tmp15 = tmp13 + tmp14
    tmp16 = triton_helpers.maximum(tmp10, tmp15)
    tmp19 = tmp17 + tmp18
    tmp21 = tmp19 + tmp20
    tmp22 = triton_helpers.maximum(tmp16, tmp21)
    tmp23 = tmp4 > tmp9
    tmp24 = tmp4 == tmp9
    tmp25 = tmp4 != tmp4
    tmp26 = tmp9 != tmp9
    tmp27 = tmp25 > tmp26
    tmp28 = tmp23 | tmp27
    tmp29 = tmp25 & tmp26
    tmp30 = tmp24 | tmp29
    tmp31 = tl.full([1], 0, tl.int64)
    tmp32 = tl.full([1], 1, tl.int64)
    tmp33 = tmp31 < tmp32
    tmp34 = tmp30 & tmp33
    tmp35 = tmp28 | tmp34
    tmp36 = tl.where(tmp35, tmp4, tmp9)
    tmp37 = tl.where(tmp35, tmp31, tmp32)
    tmp38 = tmp36 > tmp15
    tmp39 = tmp36 == tmp15
    tmp40 = tmp36 != tmp36
    tmp41 = tmp15 != tmp15
    tmp42 = tmp40 > tmp41
    tmp43 = tmp38 | tmp42
    tmp44 = tmp40 & tmp41
    tmp45 = tmp39 | tmp44
    tmp46 = tl.full([1], 2, tl.int64)
    tmp47 = tmp37 < tmp46
    tmp48 = tmp45 & tmp47
    tmp49 = tmp43 | tmp48
    tmp50 = tl.where(tmp49, tmp36, tmp15)
    tmp51 = tl.where(tmp49, tmp37, tmp46)
    tmp52 = tmp50 > tmp21
    tmp53 = tmp50 == tmp21
    tmp54 = tmp50 != tmp50
    tmp55 = tmp21 != tmp21
    tmp56 = tmp54 > tmp55
    tmp57 = tmp52 | tmp56
    tmp58 = tmp54 & tmp55
    tmp59 = tmp53 | tmp58
    tmp60 = tl.full([1], 3, tl.int64)
    tmp61 = tmp51 < tmp60
    tmp62 = tmp59 & tmp61
    tmp63 = tmp57 | tmp62
    tmp64 = tl.where(tmp63, tmp50, tmp21)
    tmp65 = tl.where(tmp63, tmp51, tmp60)
    tl.store(out_ptr0 + (x2), tmp22, xmask)
    tl.store(out_ptr1 + (x2), tmp65, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_7/inductor_cache/y6/cy6aidx4xjpi7w6qjmhugi7jyuzpadheqvm6f3ovuoln3kiyejvo.py
# Topologically Sorted Source Nodes: [add_5, max_3], Original ATen: [aten.add, aten.max]
# Source node to ATen node mapping:
#   add_5 => add_5
#   max_3 => max_3
# Graph fragment:
#   %add_5 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%unsqueeze_4, %unsqueeze_1), kwargs = {})
#   %max_3 : [num_users=2] = call_function[target=torch.ops.aten.max.dim](args = (%add_5, 1), kwargs = {})
triton_poi_fused_add_max_2 = async_compile.triton('triton_poi_fused_add_max_2', '''
import triton
import triton.language as tl
from triton.compiler.compiler import AttrsDescriptor

from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, instance_descriptor, DeviceProperties

@triton_heuristics.pointwise(
    size_hints=[16], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: '*i64', 5: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3, 4, 5), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_add_max_2', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 12, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False},
    min_elem_per_thread=0
)
@triton.jit
def triton_poi_fused_add_max_2(in_ptr0, in_ptr1, in_ptr2, out_ptr0, out_ptr1, xnumel, XBLOCK : tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x1 = (xindex // 4)
    x0 = xindex % 4
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + (4*x1), xmask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr1 + (8 + (16*x1)), xmask, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr2 + (x0), xmask, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr0 + (1 + (4*x1)), xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr1 + (9 + (16*x1)), xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr2 + (4 + x0), xmask, eviction_policy='evict_last')
    tmp11 = tl.load(in_ptr0 + (2 + (4*x1)), xmask, eviction_policy='evict_last')
    tmp12 = tl.load(in_ptr1 + (10 + (16*x1)), xmask, eviction_policy='evict_last')
    tmp14 = tl.load(in_ptr2 + (8 + x0), xmask, eviction_policy='evict_last')
    tmp17 = tl.load(in_ptr0 + (3 + (4*x1)), xmask, eviction_policy='evict_last')
    tmp18 = tl.load(in_ptr1 + (11 + (16*x1)), xmask, eviction_policy='evict_last')
    tmp20 = tl.load(in_ptr2 + (12 + x0), xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp4 = tmp2 + tmp3
    tmp7 = tmp5 + tmp6
    tmp9 = tmp7 + tmp8
    tmp10 = triton_helpers.maximum(tmp4, tmp9)
    tmp13 = tmp11 + tmp12
    tmp15 = tmp13 + tmp14
    tmp16 = triton_helpers.maximum(tmp10, tmp15)
    tmp19 = tmp17 + tmp18
    tmp21 = tmp19 + tmp20
    tmp22 = triton_helpers.maximum(tmp16, tmp21)
    tmp23 = tmp4 > tmp9
    tmp24 = tmp4 == tmp9
    tmp25 = tmp4 != tmp4
    tmp26 = tmp9 != tmp9
    tmp27 = tmp25 > tmp26
    tmp28 = tmp23 | tmp27
    tmp29 = tmp25 & tmp26
    tmp30 = tmp24 | tmp29
    tmp31 = tl.full([1], 0, tl.int64)
    tmp32 = tl.full([1], 1, tl.int64)
    tmp33 = tmp31 < tmp32
    tmp34 = tmp30 & tmp33
    tmp35 = tmp28 | tmp34
    tmp36 = tl.where(tmp35, tmp4, tmp9)
    tmp37 = tl.where(tmp35, tmp31, tmp32)
    tmp38 = tmp36 > tmp15
    tmp39 = tmp36 == tmp15
    tmp40 = tmp36 != tmp36
    tmp41 = tmp15 != tmp15
    tmp42 = tmp40 > tmp41
    tmp43 = tmp38 | tmp42
    tmp44 = tmp40 & tmp41
    tmp45 = tmp39 | tmp44
    tmp46 = tl.full([1], 2, tl.int64)
    tmp47 = tmp37 < tmp46
    tmp48 = tmp45 & tmp47
    tmp49 = tmp43 | tmp48
    tmp50 = tl.where(tmp49, tmp36, tmp15)
    tmp51 = tl.where(tmp49, tmp37, tmp46)
    tmp52 = tmp50 > tmp21
    tmp53 = tmp50 == tmp21
    tmp54 = tmp50 != tmp50
    tmp55 = tmp21 != tmp21
    tmp56 = tmp54 > tmp55
    tmp57 = tmp52 | tmp56
    tmp58 = tmp54 & tmp55
    tmp59 = tmp53 | tmp58
    tmp60 = tl.full([1], 3, tl.int64)
    tmp61 = tmp51 < tmp60
    tmp62 = tmp59 & tmp61
    tmp63 = tmp57 | tmp62
    tmp64 = tl.where(tmp63, tmp50, tmp21)
    tmp65 = tl.where(tmp63, tmp51, tmp60)
    tl.store(out_ptr0 + (x2), tmp22, xmask)
    tl.store(out_ptr1 + (x2), tmp65, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_7/inductor_cache/pz/cpzuxuwhwbn22vaq3ndvkouqpztabhutjiktjp3d5vxwx3ptniiy.py
# Topologically Sorted Source Nodes: [v_6, add_7, max_4, tag_1, tag_2, tag_3], Original ATen: [aten.add, aten.max, aten.gather]
# Source node to ATen node mapping:
#   add_7 => add_7
#   max_4 => max_4
#   tag_1 => gather
#   tag_2 => gather_1
#   tag_3 => gather_2
#   v_6 => add_6
# Graph fragment:
#   %add_6 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%getitem_4, %select_3), kwargs = {})
#   %add_7 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%add_6, %unsqueeze_5), kwargs = {})
#   %max_4 : [num_users=1] = call_function[target=torch.ops.aten.max.dim](args = (%add_7, 1, True), kwargs = {})
#   %gather : [num_users=2] = call_function[target=torch.ops.aten.gather.default](args = (%getitem_5, 1, %getitem_7), kwargs = {})
#   %gather_1 : [num_users=2] = call_function[target=torch.ops.aten.gather.default](args = (%getitem_3, 1, %gather), kwargs = {})
#   %gather_2 : [num_users=1] = call_function[target=torch.ops.aten.gather.default](args = (%getitem_1, 1, %gather_1), kwargs = {})
triton_poi_fused_add_gather_max_3 = async_compile.triton('triton_poi_fused_add_gather_max_3', '''
import triton
import triton.language as tl
from triton.compiler.compiler import AttrsDescriptor

from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, instance_descriptor, DeviceProperties

@triton_heuristics.pointwise(
    size_hints=[4], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*i64', 4: '*i64', 5: '*i64', 6: '*i64', 7: '*i64', 8: '*i64', 9: '*i64', 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': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3, 4, 5, 7), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_add_gather_max_3', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 12, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False},
    min_elem_per_thread=0
)
@triton.jit
def triton_poi_fused_add_gather_max_3(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4, in_ptr5, out_ptr0, out_ptr1, out_ptr2, out_ptr3, xnumel, XBLOCK : tl.constexpr):
    xnumel = 4
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (4*x0), xmask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr1 + (12 + (16*x0)), xmask, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr2 + (0))
    tmp4 = tl.broadcast_to(tmp3, [XBLOCK])
    tmp6 = tl.load(in_ptr0 + (1 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp7 = tl.load(in_ptr1 + (13 + (16*x0)), xmask, eviction_policy='evict_last')
    tmp9 = tl.load(in_ptr2 + (1))
    tmp10 = tl.broadcast_to(tmp9, [XBLOCK])
    tmp27 = tl.load(in_ptr0 + (2 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp28 = tl.load(in_ptr1 + (14 + (16*x0)), xmask, eviction_policy='evict_last')
    tmp30 = tl.load(in_ptr2 + (2))
    tmp31 = tl.broadcast_to(tmp30, [XBLOCK])
    tmp47 = tl.load(in_ptr0 + (3 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp48 = tl.load(in_ptr1 + (15 + (16*x0)), xmask, eviction_policy='evict_last')
    tmp50 = tl.load(in_ptr2 + (3))
    tmp51 = tl.broadcast_to(tmp50, [XBLOCK])
    tmp2 = tmp0 + tmp1
    tmp5 = tmp2 + tmp4
    tmp8 = tmp6 + tmp7
    tmp11 = tmp8 + tmp10
    tmp12 = tmp5 > tmp11
    tmp13 = tmp5 == tmp11
    tmp14 = tmp5 != tmp5
    tmp15 = tmp11 != tmp11
    tmp16 = tmp14 > tmp15
    tmp17 = tmp12 | tmp16
    tmp18 = tmp14 & tmp15
    tmp19 = tmp13 | tmp18
    tmp20 = tl.full([1], 0, tl.int64)
    tmp21 = tl.full([1], 1, tl.int64)
    tmp22 = tmp20 < tmp21
    tmp23 = tmp19 & tmp22
    tmp24 = tmp17 | tmp23
    tmp25 = tl.where(tmp24, tmp5, tmp11)
    tmp26 = tl.where(tmp24, tmp20, tmp21)
    tmp29 = tmp27 + tmp28
    tmp32 = tmp29 + tmp31
    tmp33 = tmp25 > tmp32
    tmp34 = tmp25 == tmp32
    tmp35 = tmp25 != tmp25
    tmp36 = tmp32 != tmp32
    tmp37 = tmp35 > tmp36
    tmp38 = tmp33 | tmp37
    tmp39 = tmp35 & tmp36
    tmp40 = tmp34 | tmp39
    tmp41 = tl.full([1], 2, tl.int64)
    tmp42 = tmp26 < tmp41
    tmp43 = tmp40 & tmp42
    tmp44 = tmp38 | tmp43
    tmp45 = tl.where(tmp44, tmp25, tmp32)
    tmp46 = tl.where(tmp44, tmp26, tmp41)
    tmp49 = tmp47 + tmp48
    tmp52 = tmp49 + tmp51
    tmp53 = tmp45 > tmp52
    tmp54 = tmp45 == tmp52
    tmp55 = tmp45 != tmp45
    tmp56 = tmp52 != tmp52
    tmp57 = tmp55 > tmp56
    tmp58 = tmp53 | tmp57
    tmp59 = tmp55 & tmp56
    tmp60 = tmp54 | tmp59
    tmp61 = tl.full([1], 3, tl.int64)
    tmp62 = tmp46 < tmp61
    tmp63 = tmp60 & tmp62
    tmp64 = tmp58 | tmp63
    tmp65 = tl.where(tmp64, tmp45, tmp52)
    tmp66 = tl.where(tmp64, tmp46, tmp61)
    tmp67 = tl.full([XBLOCK], 4, tl.int32)
    tmp68 = tmp66 + tmp67
    tmp69 = tmp66 < 0
    tmp70 = tl.where(tmp69, tmp68, tmp66)
    tl.device_assert(((0 <= tmp70) & (tmp70 < 4)) | ~(xmask), "index out of bounds: 0 <= tmp70 < 4")
    tmp72 = tl.load(in_ptr3 + (tmp70 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp73 = tmp72 + tmp67
    tmp74 = tmp72 < 0
    tmp75 = tl.where(tmp74, tmp73, tmp72)
    tl.device_assert(((0 <= tmp75) & (tmp75 < 4)) | ~(xmask), "index out of bounds: 0 <= tmp75 < 4")
    tmp77 = tl.load(in_ptr4 + (tmp75 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp78 = tmp77 + tmp67
    tmp79 = tmp77 < 0
    tmp80 = tl.where(tmp79, tmp78, tmp77)
    tl.device_assert(((0 <= tmp80) & (tmp80 < 4)) | ~(xmask), "index out of bounds: 0 <= tmp80 < 4")
    tmp82 = tl.load(in_ptr5 + (tmp80 + (4*x0)), xmask, eviction_policy='evict_last')
    tl.store(out_ptr0 + (4*x0), tmp66, xmask)
    tl.store(out_ptr1 + (4*x0), tmp82, xmask)
    tl.store(out_ptr2 + (4*x0), tmp77, xmask)
    tl.store(out_ptr3 + (4*x0), tmp72, xmask)
''', device_str='cuda')


async_compile.wait(globals())
del async_compile

def call(args):
    arg0_1, arg1_1, arg2_1, arg3_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1))
    assert_size_stride(arg1_1, (4, ), (1, ))
    assert_size_stride(arg2_1, (4, 4), (4, 1))
    assert_size_stride(arg3_1, (4, ), (1, ))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        buf1 = empty_strided_cuda((4, 4), (4, 1), torch.int64)
        # Topologically Sorted Source Nodes: [add_1, max_1], Original ATen: [aten.add, aten.max]
        stream0 = get_raw_stream(0)
        triton_poi_fused_add_max_0.run(arg0_1, arg1_1, arg2_1, buf0, buf1, 16, grid=grid(16), stream=stream0)
        del arg1_1
        buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        buf3 = empty_strided_cuda((4, 4), (4, 1), torch.int64)
        # Topologically Sorted Source Nodes: [add_3, max_2], Original ATen: [aten.add, aten.max]
        triton_poi_fused_add_max_1.run(buf0, arg0_1, arg2_1, buf2, buf3, 16, grid=grid(16), stream=stream0)
        buf4 = buf0; del buf0  # reuse
        buf5 = empty_strided_cuda((4, 4), (4, 1), torch.int64)
        # Topologically Sorted Source Nodes: [add_5, max_3], Original ATen: [aten.add, aten.max]
        triton_poi_fused_add_max_2.run(buf2, arg0_1, arg2_1, buf4, buf5, 16, grid=grid(16), stream=stream0)
        del arg2_1
        del buf2
        buf10 = empty_strided_cuda((4, 4), (4, 1), torch.int64)
        buf6 = reinterpret_tensor(buf10, (4, 1), (4, 1), 3)  # alias
        buf7 = reinterpret_tensor(buf10, (4, 1), (4, 1), 0)  # alias
        buf8 = reinterpret_tensor(buf10, (4, 1), (4, 1), 1)  # alias
        buf9 = reinterpret_tensor(buf10, (4, 1), (4, 1), 2)  # alias
        # Topologically Sorted Source Nodes: [v_6, add_7, max_4, tag_1, tag_2, tag_3], Original ATen: [aten.add, aten.max, aten.gather]
        triton_poi_fused_add_gather_max_3.run(buf4, arg0_1, arg3_1, buf5, buf3, buf1, buf6, buf7, buf8, buf9, 4, grid=grid(4), stream=stream0)
        del arg0_1
        del arg3_1
        del buf1
        del buf3
        del buf4
        del buf5
    return (buf10, )


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), (16, 4, 1), device='cuda:0', dtype=torch.float32)
    arg1_1 = rand_strided((4, ), (1, ), device='cuda:0', dtype=torch.float32)
    arg2_1 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    arg3_1 = rand_strided((4, ), (1, ), device='cuda:0', dtype=torch.float32)
    fn = lambda: call([arg0_1, arg1_1, arg2_1, arg3_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
import torch.utils.data


class CRF(nn.Module):
    """Implements Conditional Random Fields"""

    def __init__(self, num_tags):
        super(CRF, self).__init__()
        self.num_tags = num_tags
        self.transitions = nn.Parameter(torch.Tensor(num_tags, num_tags))
        self.start_transitions = nn.Parameter(torch.randn(num_tags))
        self.stop_transitions = nn.Parameter(torch.randn(num_tags))
        nn.init.xavier_normal_(self.transitions)

    def forward(self, feats):
        if len(feats.shape) != 3:
            raise ValueError('feats must be 3-d got {}-d'.format(feats.shape))
        return self._viterbi(feats)

    def loss(self, feats, tags):
        """
        Computes negative log likelihood between features and tags.
        Essentially difference between individual sequence scores and 
        sum of all possible sequence scores (partition function)
        Parameters:
            feats: Input features [batch size, sequence length, number of tags]
            tags: Target tag indices [batch size, sequence length]. Should be between
                    0 and num_tags
        Returns:
            Negative log likelihood [a scalar] 
        """
        if len(feats.shape) != 3:
            raise ValueError('feats must be 3-d got {}-d'.format(feats.shape))
        if len(tags.shape) != 2:
            raise ValueError('tags must be 2-d but got {}-d'.format(tags.shape)
                )
        if feats.shape[:2] != tags.shape:
            raise ValueError(
                'First two dimensions of feats and tags must match')
        sequence_score = self._sequence_score(feats, tags)
        partition_function = self._partition_function(feats)
        log_probability = sequence_score - partition_function
        return -log_probability.mean()

    def _sequence_score(self, feats, tags):
        """
        Parameters:
            feats: Input features [batch size, sequence length, number of tags]
            tags: Target tag indices [batch size, sequence length]. Should be between
                    0 and num_tags
        Returns: Sequence score of shape [batch size]
        """
        feats.shape[0]
        feat_score = feats.gather(2, tags.unsqueeze(-1)).squeeze(-1).sum(dim=-1
            )
        tags_pairs = tags.unfold(1, 2, 1)
        indices = tags_pairs.permute(2, 0, 1).chunk(2)
        trans_score = self.transitions[indices].squeeze(0).sum(dim=-1)
        start_score = self.start_transitions[tags[:, 0]]
        stop_score = self.stop_transitions[tags[:, -1]]
        return feat_score + start_score + trans_score + stop_score

    def _partition_function(self, feats):
        """
        Computes the partition function for CRF using the forward algorithm.
        Basically calculate scores for all possible tag sequences for 
        the given feature vector sequence
        Parameters:
            feats: Input features [batch size, sequence length, number of tags]
        Returns:
            Total scores of shape [batch size]
        """
        _, seq_size, num_tags = feats.shape
        if self.num_tags != num_tags:
            raise ValueError('num_tags should be {} but got {}'.format(self
                .num_tags, num_tags))
        a = feats[:, 0] + self.start_transitions.unsqueeze(0)
        transitions = self.transitions.unsqueeze(0)
        for i in range(1, seq_size):
            feat = feats[:, i].unsqueeze(1)
            a = self._log_sum_exp(a.unsqueeze(-1) + transitions + feat, 1)
        return self._log_sum_exp(a + self.stop_transitions.unsqueeze(0), 1)

    def _viterbi(self, feats):
        """
        Uses Viterbi algorithm to predict the best sequence
        Parameters:
            feats: Input features [batch size, sequence length, number of tags]
        Returns: Best tag sequence [batch size, sequence length]
        """
        _, seq_size, num_tags = feats.shape
        if self.num_tags != num_tags:
            raise ValueError('num_tags should be {} but got {}'.format(self
                .num_tags, num_tags))
        v = feats[:, 0] + self.start_transitions.unsqueeze(0)
        transitions = self.transitions.unsqueeze(0)
        paths = []
        for i in range(1, seq_size):
            feat = feats[:, i]
            v, idx = (v.unsqueeze(-1) + transitions).max(1)
            paths.append(idx)
            v = v + feat
        v, tag = (v + self.stop_transitions.unsqueeze(0)).max(1, True)
        tags = [tag]
        for idx in reversed(paths):
            tag = idx.gather(1, tag)
            tags.append(tag)
        tags.reverse()
        return torch.cat(tags, 1)

    def _log_sum_exp(self, logits, dim):
        """
        Computes log-sum-exp in a stable way
        """
        max_val, _ = logits.max(dim)
        return max_val + (logits - max_val.unsqueeze(dim)).exp().sum(dim).log()


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


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

import torch
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
import torch.nn as nn
import torch.utils.data
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_add_max_0(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
    out_ptr1, xnumel, XBLOCK: tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x1 = xindex // 4
    x0 = xindex % 4
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + 16 * x1, xmask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr1 + 0)
    tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
    tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr0 + (1 + 16 * x1), xmask, eviction_policy='evict_last'
        )
    tmp7 = tl.load(in_ptr1 + 1)
    tmp8 = tl.broadcast_to(tmp7, [XBLOCK])
    tmp10 = tl.load(in_ptr2 + (4 + x0), xmask, eviction_policy='evict_last')
    tmp13 = tl.load(in_ptr0 + (2 + 16 * x1), xmask, eviction_policy=
        'evict_last')
    tmp14 = tl.load(in_ptr1 + 2)
    tmp15 = tl.broadcast_to(tmp14, [XBLOCK])
    tmp17 = tl.load(in_ptr2 + (8 + x0), xmask, eviction_policy='evict_last')
    tmp20 = tl.load(in_ptr0 + (3 + 16 * x1), xmask, eviction_policy=
        'evict_last')
    tmp21 = tl.load(in_ptr1 + 3)
    tmp22 = tl.broadcast_to(tmp21, [XBLOCK])
    tmp24 = tl.load(in_ptr2 + (12 + x0), xmask, eviction_policy='evict_last')
    tmp3 = tmp0 + tmp2
    tmp5 = tmp3 + tmp4
    tmp9 = tmp6 + tmp8
    tmp11 = tmp9 + tmp10
    tmp12 = triton_helpers.maximum(tmp5, tmp11)
    tmp16 = tmp13 + tmp15
    tmp18 = tmp16 + tmp17
    tmp19 = triton_helpers.maximum(tmp12, tmp18)
    tmp23 = tmp20 + tmp22
    tmp25 = tmp23 + tmp24
    tmp26 = triton_helpers.maximum(tmp19, tmp25)
    tmp27 = tmp5 > tmp11
    tmp28 = tmp5 == tmp11
    tmp29 = tmp5 != tmp5
    tmp30 = tmp11 != tmp11
    tmp31 = tmp29 > tmp30
    tmp32 = tmp27 | tmp31
    tmp33 = tmp29 & tmp30
    tmp34 = tmp28 | tmp33
    tmp35 = tl.full([1], 0, tl.int64)
    tmp36 = tl.full([1], 1, tl.int64)
    tmp37 = tmp35 < tmp36
    tmp38 = tmp34 & tmp37
    tmp39 = tmp32 | tmp38
    tmp40 = tl.where(tmp39, tmp5, tmp11)
    tmp41 = tl.where(tmp39, tmp35, tmp36)
    tmp42 = tmp40 > tmp18
    tmp43 = tmp40 == tmp18
    tmp44 = tmp40 != tmp40
    tmp45 = tmp18 != tmp18
    tmp46 = tmp44 > tmp45
    tmp47 = tmp42 | tmp46
    tmp48 = tmp44 & tmp45
    tmp49 = tmp43 | tmp48
    tmp50 = tl.full([1], 2, tl.int64)
    tmp51 = tmp41 < tmp50
    tmp52 = tmp49 & tmp51
    tmp53 = tmp47 | tmp52
    tmp54 = tl.where(tmp53, tmp40, tmp18)
    tmp55 = tl.where(tmp53, tmp41, tmp50)
    tmp56 = tmp54 > tmp25
    tmp57 = tmp54 == tmp25
    tmp58 = tmp54 != tmp54
    tmp59 = tmp25 != tmp25
    tmp60 = tmp58 > tmp59
    tmp61 = tmp56 | tmp60
    tmp62 = tmp58 & tmp59
    tmp63 = tmp57 | tmp62
    tmp64 = tl.full([1], 3, tl.int64)
    tmp65 = tmp55 < tmp64
    tmp66 = tmp63 & tmp65
    tmp67 = tmp61 | tmp66
    tl.where(tmp67, tmp54, tmp25)
    tmp69 = tl.where(tmp67, tmp55, tmp64)
    tl.store(out_ptr0 + x2, tmp26, xmask)
    tl.store(out_ptr1 + x2, tmp69, xmask)


@triton.jit
def triton_poi_fused_add_max_1(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
    out_ptr1, xnumel, XBLOCK: tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x1 = xindex // 4
    x0 = xindex % 4
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr1 + (4 + 16 * x1), xmask, eviction_policy='evict_last'
        )
    tmp3 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr1 + (5 + 16 * x1), xmask, eviction_policy='evict_last'
        )
    tmp8 = tl.load(in_ptr2 + (4 + x0), xmask, eviction_policy='evict_last')
    tmp11 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
        )
    tmp12 = tl.load(in_ptr1 + (6 + 16 * x1), xmask, eviction_policy=
        'evict_last')
    tmp14 = tl.load(in_ptr2 + (8 + x0), xmask, eviction_policy='evict_last')
    tmp17 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
        )
    tmp18 = tl.load(in_ptr1 + (7 + 16 * x1), xmask, eviction_policy=
        'evict_last')
    tmp20 = tl.load(in_ptr2 + (12 + x0), xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp4 = tmp2 + tmp3
    tmp7 = tmp5 + tmp6
    tmp9 = tmp7 + tmp8
    tmp10 = triton_helpers.maximum(tmp4, tmp9)
    tmp13 = tmp11 + tmp12
    tmp15 = tmp13 + tmp14
    tmp16 = triton_helpers.maximum(tmp10, tmp15)
    tmp19 = tmp17 + tmp18
    tmp21 = tmp19 + tmp20
    tmp22 = triton_helpers.maximum(tmp16, tmp21)
    tmp23 = tmp4 > tmp9
    tmp24 = tmp4 == tmp9
    tmp25 = tmp4 != tmp4
    tmp26 = tmp9 != tmp9
    tmp27 = tmp25 > tmp26
    tmp28 = tmp23 | tmp27
    tmp29 = tmp25 & tmp26
    tmp30 = tmp24 | tmp29
    tmp31 = tl.full([1], 0, tl.int64)
    tmp32 = tl.full([1], 1, tl.int64)
    tmp33 = tmp31 < tmp32
    tmp34 = tmp30 & tmp33
    tmp35 = tmp28 | tmp34
    tmp36 = tl.where(tmp35, tmp4, tmp9)
    tmp37 = tl.where(tmp35, tmp31, tmp32)
    tmp38 = tmp36 > tmp15
    tmp39 = tmp36 == tmp15
    tmp40 = tmp36 != tmp36
    tmp41 = tmp15 != tmp15
    tmp42 = tmp40 > tmp41
    tmp43 = tmp38 | tmp42
    tmp44 = tmp40 & tmp41
    tmp45 = tmp39 | tmp44
    tmp46 = tl.full([1], 2, tl.int64)
    tmp47 = tmp37 < tmp46
    tmp48 = tmp45 & tmp47
    tmp49 = tmp43 | tmp48
    tmp50 = tl.where(tmp49, tmp36, tmp15)
    tmp51 = tl.where(tmp49, tmp37, tmp46)
    tmp52 = tmp50 > tmp21
    tmp53 = tmp50 == tmp21
    tmp54 = tmp50 != tmp50
    tmp55 = tmp21 != tmp21
    tmp56 = tmp54 > tmp55
    tmp57 = tmp52 | tmp56
    tmp58 = tmp54 & tmp55
    tmp59 = tmp53 | tmp58
    tmp60 = tl.full([1], 3, tl.int64)
    tmp61 = tmp51 < tmp60
    tmp62 = tmp59 & tmp61
    tmp63 = tmp57 | tmp62
    tl.where(tmp63, tmp50, tmp21)
    tmp65 = tl.where(tmp63, tmp51, tmp60)
    tl.store(out_ptr0 + x2, tmp22, xmask)
    tl.store(out_ptr1 + x2, tmp65, xmask)


@triton.jit
def triton_poi_fused_add_max_2(in_ptr0, in_ptr1, in_ptr2, out_ptr0,
    out_ptr1, xnumel, XBLOCK: tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x1 = xindex // 4
    x0 = xindex % 4
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + 4 * x1, xmask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr1 + (8 + 16 * x1), xmask, eviction_policy='evict_last'
        )
    tmp3 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr0 + (1 + 4 * x1), xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr1 + (9 + 16 * x1), xmask, eviction_policy='evict_last'
        )
    tmp8 = tl.load(in_ptr2 + (4 + x0), xmask, eviction_policy='evict_last')
    tmp11 = tl.load(in_ptr0 + (2 + 4 * x1), xmask, eviction_policy='evict_last'
        )
    tmp12 = tl.load(in_ptr1 + (10 + 16 * x1), xmask, eviction_policy=
        'evict_last')
    tmp14 = tl.load(in_ptr2 + (8 + x0), xmask, eviction_policy='evict_last')
    tmp17 = tl.load(in_ptr0 + (3 + 4 * x1), xmask, eviction_policy='evict_last'
        )
    tmp18 = tl.load(in_ptr1 + (11 + 16 * x1), xmask, eviction_policy=
        'evict_last')
    tmp20 = tl.load(in_ptr2 + (12 + x0), xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp4 = tmp2 + tmp3
    tmp7 = tmp5 + tmp6
    tmp9 = tmp7 + tmp8
    tmp10 = triton_helpers.maximum(tmp4, tmp9)
    tmp13 = tmp11 + tmp12
    tmp15 = tmp13 + tmp14
    tmp16 = triton_helpers.maximum(tmp10, tmp15)
    tmp19 = tmp17 + tmp18
    tmp21 = tmp19 + tmp20
    tmp22 = triton_helpers.maximum(tmp16, tmp21)
    tmp23 = tmp4 > tmp9
    tmp24 = tmp4 == tmp9
    tmp25 = tmp4 != tmp4
    tmp26 = tmp9 != tmp9
    tmp27 = tmp25 > tmp26
    tmp28 = tmp23 | tmp27
    tmp29 = tmp25 & tmp26
    tmp30 = tmp24 | tmp29
    tmp31 = tl.full([1], 0, tl.int64)
    tmp32 = tl.full([1], 1, tl.int64)
    tmp33 = tmp31 < tmp32
    tmp34 = tmp30 & tmp33
    tmp35 = tmp28 | tmp34
    tmp36 = tl.where(tmp35, tmp4, tmp9)
    tmp37 = tl.where(tmp35, tmp31, tmp32)
    tmp38 = tmp36 > tmp15
    tmp39 = tmp36 == tmp15
    tmp40 = tmp36 != tmp36
    tmp41 = tmp15 != tmp15
    tmp42 = tmp40 > tmp41
    tmp43 = tmp38 | tmp42
    tmp44 = tmp40 & tmp41
    tmp45 = tmp39 | tmp44
    tmp46 = tl.full([1], 2, tl.int64)
    tmp47 = tmp37 < tmp46
    tmp48 = tmp45 & tmp47
    tmp49 = tmp43 | tmp48
    tmp50 = tl.where(tmp49, tmp36, tmp15)
    tmp51 = tl.where(tmp49, tmp37, tmp46)
    tmp52 = tmp50 > tmp21
    tmp53 = tmp50 == tmp21
    tmp54 = tmp50 != tmp50
    tmp55 = tmp21 != tmp21
    tmp56 = tmp54 > tmp55
    tmp57 = tmp52 | tmp56
    tmp58 = tmp54 & tmp55
    tmp59 = tmp53 | tmp58
    tmp60 = tl.full([1], 3, tl.int64)
    tmp61 = tmp51 < tmp60
    tmp62 = tmp59 & tmp61
    tmp63 = tmp57 | tmp62
    tl.where(tmp63, tmp50, tmp21)
    tmp65 = tl.where(tmp63, tmp51, tmp60)
    tl.store(out_ptr0 + x2, tmp22, xmask)
    tl.store(out_ptr1 + x2, tmp65, xmask)


@triton.jit
def triton_poi_fused_add_gather_max_3(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
    in_ptr4, in_ptr5, out_ptr0, out_ptr1, out_ptr2, out_ptr3, xnumel,
    XBLOCK: tl.constexpr):
    xnumel = 4
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
    tmp1 = tl.load(in_ptr1 + (12 + 16 * x0), xmask, eviction_policy=
        'evict_last')
    tmp3 = tl.load(in_ptr2 + 0)
    tmp4 = tl.broadcast_to(tmp3, [XBLOCK])
    tmp6 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp7 = tl.load(in_ptr1 + (13 + 16 * x0), xmask, eviction_policy=
        'evict_last')
    tmp9 = tl.load(in_ptr2 + 1)
    tmp10 = tl.broadcast_to(tmp9, [XBLOCK])
    tmp27 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp28 = tl.load(in_ptr1 + (14 + 16 * x0), xmask, eviction_policy=
        'evict_last')
    tmp30 = tl.load(in_ptr2 + 2)
    tmp31 = tl.broadcast_to(tmp30, [XBLOCK])
    tmp47 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp48 = tl.load(in_ptr1 + (15 + 16 * x0), xmask, eviction_policy=
        'evict_last')
    tmp50 = tl.load(in_ptr2 + 3)
    tmp51 = tl.broadcast_to(tmp50, [XBLOCK])
    tmp2 = tmp0 + tmp1
    tmp5 = tmp2 + tmp4
    tmp8 = tmp6 + tmp7
    tmp11 = tmp8 + tmp10
    tmp12 = tmp5 > tmp11
    tmp13 = tmp5 == tmp11
    tmp14 = tmp5 != tmp5
    tmp15 = tmp11 != tmp11
    tmp16 = tmp14 > tmp15
    tmp17 = tmp12 | tmp16
    tmp18 = tmp14 & tmp15
    tmp19 = tmp13 | tmp18
    tmp20 = tl.full([1], 0, tl.int64)
    tmp21 = tl.full([1], 1, tl.int64)
    tmp22 = tmp20 < tmp21
    tmp23 = tmp19 & tmp22
    tmp24 = tmp17 | tmp23
    tmp25 = tl.where(tmp24, tmp5, tmp11)
    tmp26 = tl.where(tmp24, tmp20, tmp21)
    tmp29 = tmp27 + tmp28
    tmp32 = tmp29 + tmp31
    tmp33 = tmp25 > tmp32
    tmp34 = tmp25 == tmp32
    tmp35 = tmp25 != tmp25
    tmp36 = tmp32 != tmp32
    tmp37 = tmp35 > tmp36
    tmp38 = tmp33 | tmp37
    tmp39 = tmp35 & tmp36
    tmp40 = tmp34 | tmp39
    tmp41 = tl.full([1], 2, tl.int64)
    tmp42 = tmp26 < tmp41
    tmp43 = tmp40 & tmp42
    tmp44 = tmp38 | tmp43
    tmp45 = tl.where(tmp44, tmp25, tmp32)
    tmp46 = tl.where(tmp44, tmp26, tmp41)
    tmp49 = tmp47 + tmp48
    tmp52 = tmp49 + tmp51
    tmp53 = tmp45 > tmp52
    tmp54 = tmp45 == tmp52
    tmp55 = tmp45 != tmp45
    tmp56 = tmp52 != tmp52
    tmp57 = tmp55 > tmp56
    tmp58 = tmp53 | tmp57
    tmp59 = tmp55 & tmp56
    tmp60 = tmp54 | tmp59
    tmp61 = tl.full([1], 3, tl.int64)
    tmp62 = tmp46 < tmp61
    tmp63 = tmp60 & tmp62
    tmp64 = tmp58 | tmp63
    tl.where(tmp64, tmp45, tmp52)
    tmp66 = tl.where(tmp64, tmp46, tmp61)
    tmp67 = tl.full([XBLOCK], 4, tl.int32)
    tmp68 = tmp66 + tmp67
    tmp69 = tmp66 < 0
    tmp70 = tl.where(tmp69, tmp68, tmp66)
    tl.device_assert((0 <= tmp70) & (tmp70 < 4) | ~xmask,
        'index out of bounds: 0 <= tmp70 < 4')
    tmp72 = tl.load(in_ptr3 + (tmp70 + 4 * x0), xmask, eviction_policy=
        'evict_last')
    tmp73 = tmp72 + tmp67
    tmp74 = tmp72 < 0
    tmp75 = tl.where(tmp74, tmp73, tmp72)
    tl.device_assert((0 <= tmp75) & (tmp75 < 4) | ~xmask,
        'index out of bounds: 0 <= tmp75 < 4')
    tmp77 = tl.load(in_ptr4 + (tmp75 + 4 * x0), xmask, eviction_policy=
        'evict_last')
    tmp78 = tmp77 + tmp67
    tmp79 = tmp77 < 0
    tmp80 = tl.where(tmp79, tmp78, tmp77)
    tl.device_assert((0 <= tmp80) & (tmp80 < 4) | ~xmask,
        'index out of bounds: 0 <= tmp80 < 4')
    tmp82 = tl.load(in_ptr5 + (tmp80 + 4 * x0), xmask, eviction_policy=
        'evict_last')
    tl.store(out_ptr0 + 4 * x0, tmp66, xmask)
    tl.store(out_ptr1 + 4 * x0, tmp82, xmask)
    tl.store(out_ptr2 + 4 * x0, tmp77, xmask)
    tl.store(out_ptr3 + 4 * x0, tmp72, xmask)


def call(args):
    arg0_1, arg1_1, arg2_1, arg3_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4, 4), (16, 4, 1))
    assert_size_stride(arg1_1, (4,), (1,))
    assert_size_stride(arg2_1, (4, 4), (4, 1))
    assert_size_stride(arg3_1, (4,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        buf1 = empty_strided_cuda((4, 4), (4, 1), torch.int64)
        get_raw_stream(0)
        triton_poi_fused_add_max_0[grid(16)](arg0_1, arg1_1, arg2_1, buf0,
            buf1, 16, XBLOCK=16, num_warps=1, num_stages=1)
        del arg1_1
        buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        buf3 = empty_strided_cuda((4, 4), (4, 1), torch.int64)
        triton_poi_fused_add_max_1[grid(16)](buf0, arg0_1, arg2_1, buf2,
            buf3, 16, XBLOCK=16, num_warps=1, num_stages=1)
        buf4 = buf0
        del buf0
        buf5 = empty_strided_cuda((4, 4), (4, 1), torch.int64)
        triton_poi_fused_add_max_2[grid(16)](buf2, arg0_1, arg2_1, buf4,
            buf5, 16, XBLOCK=16, num_warps=1, num_stages=1)
        del arg2_1
        del buf2
        buf10 = empty_strided_cuda((4, 4), (4, 1), torch.int64)
        buf6 = reinterpret_tensor(buf10, (4, 1), (4, 1), 3)
        buf7 = reinterpret_tensor(buf10, (4, 1), (4, 1), 0)
        buf8 = reinterpret_tensor(buf10, (4, 1), (4, 1), 1)
        buf9 = reinterpret_tensor(buf10, (4, 1), (4, 1), 2)
        triton_poi_fused_add_gather_max_3[grid(4)](buf4, arg0_1, arg3_1,
            buf5, buf3, buf1, buf6, buf7, buf8, buf9, 4, XBLOCK=4,
            num_warps=1, num_stages=1)
        del arg0_1
        del arg3_1
        del buf1
        del buf3
        del buf4
        del buf5
    return buf10,


class CRFNew(nn.Module):
    """Implements Conditional Random Fields"""

    def __init__(self, num_tags):
        super(CRFNew, self).__init__()
        self.num_tags = num_tags
        self.transitions = nn.Parameter(torch.Tensor(num_tags, num_tags))
        self.start_transitions = nn.Parameter(torch.randn(num_tags))
        self.stop_transitions = nn.Parameter(torch.randn(num_tags))
        nn.init.xavier_normal_(self.transitions)

    def loss(self, feats, tags):
        """
        Computes negative log likelihood between features and tags.
        Essentially difference between individual sequence scores and 
        sum of all possible sequence scores (partition function)
        Parameters:
            feats: Input features [batch size, sequence length, number of tags]
            tags: Target tag indices [batch size, sequence length]. Should be between
                    0 and num_tags
        Returns:
            Negative log likelihood [a scalar] 
        """
        if len(feats.shape) != 3:
            raise ValueError('feats must be 3-d got {}-d'.format(feats.shape))
        if len(tags.shape) != 2:
            raise ValueError('tags must be 2-d but got {}-d'.format(tags.shape)
                )
        if feats.shape[:2] != tags.shape:
            raise ValueError(
                'First two dimensions of feats and tags must match')
        sequence_score = self._sequence_score(feats, tags)
        partition_function = self._partition_function(feats)
        log_probability = sequence_score - partition_function
        return -log_probability.mean()

    def _sequence_score(self, feats, tags):
        """
        Parameters:
            feats: Input features [batch size, sequence length, number of tags]
            tags: Target tag indices [batch size, sequence length]. Should be between
                    0 and num_tags
        Returns: Sequence score of shape [batch size]
        """
        feats.shape[0]
        feat_score = feats.gather(2, tags.unsqueeze(-1)).squeeze(-1).sum(dim=-1
            )
        tags_pairs = tags.unfold(1, 2, 1)
        indices = tags_pairs.permute(2, 0, 1).chunk(2)
        trans_score = self.transitions[indices].squeeze(0).sum(dim=-1)
        start_score = self.start_transitions[tags[:, 0]]
        stop_score = self.stop_transitions[tags[:, -1]]
        return feat_score + start_score + trans_score + stop_score

    def _partition_function(self, feats):
        """
        Computes the partition function for CRF using the forward algorithm.
        Basically calculate scores for all possible tag sequences for 
        the given feature vector sequence
        Parameters:
            feats: Input features [batch size, sequence length, number of tags]
        Returns:
            Total scores of shape [batch size]
        """
        _, seq_size, num_tags = feats.shape
        if self.num_tags != num_tags:
            raise ValueError('num_tags should be {} but got {}'.format(self
                .num_tags, num_tags))
        a = feats[:, 0] + self.start_transitions.unsqueeze(0)
        transitions = self.transitions.unsqueeze(0)
        for i in range(1, seq_size):
            feat = feats[:, i].unsqueeze(1)
            a = self._log_sum_exp(a.unsqueeze(-1) + transitions + feat, 1)
        return self._log_sum_exp(a + self.stop_transitions.unsqueeze(0), 1)

    def _viterbi(self, feats):
        """
        Uses Viterbi algorithm to predict the best sequence
        Parameters:
            feats: Input features [batch size, sequence length, number of tags]
        Returns: Best tag sequence [batch size, sequence length]
        """
        _, seq_size, num_tags = feats.shape
        if self.num_tags != num_tags:
            raise ValueError('num_tags should be {} but got {}'.format(self
                .num_tags, num_tags))
        v = feats[:, 0] + self.start_transitions.unsqueeze(0)
        transitions = self.transitions.unsqueeze(0)
        paths = []
        for i in range(1, seq_size):
            feat = feats[:, i]
            v, idx = (v.unsqueeze(-1) + transitions).max(1)
            paths.append(idx)
            v = v + feat
        v, tag = (v + self.stop_transitions.unsqueeze(0)).max(1, True)
        tags = [tag]
        for idx in reversed(paths):
            tag = idx.gather(1, tag)
            tags.append(tag)
        tags.reverse()
        return torch.cat(tags, 1)

    def _log_sum_exp(self, logits, dim):
        """
        Computes log-sum-exp in a stable way
        """
        max_val, _ = logits.max(dim)
        return max_val + (logits - max_val.unsqueeze(dim)).exp().sum(dim).log()

    def forward(self, input_0):
        arg2_1 = self.transitions
        arg1_1 = self.start_transitions
        arg3_1 = self.stop_transitions
        arg0_1 = input_0
        output = call([arg0_1, arg1_1, arg2_1, arg3_1])
        return output[0]
