# AOT ID: ['0_forward']
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/xd/cxdwtygncgwjegadoo262dgmykjc5ooocufkdnt5on6exr5afkek.py
# Topologically Sorted Source Nodes: [linalg_norm], Original ATen: [aten.linalg_vector_norm]
# Source node to ATen node mapping:
#   linalg_norm => 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.0), kwargs = {})
#   %sum_1 : [num_users=1] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%pow_1, [-1]), kwargs = {})
#   %pow_2 : [num_users=1] = call_function[target=torch.ops.aten.pow.Tensor_Scalar](args = (%sum_1, 0.5), kwargs = {})
triton_poi_fused_linalg_vector_norm_0 = async_compile.triton('triton_poi_fused_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.pointwise(
    size_hints=[4], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '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), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_linalg_vector_norm_0', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 4, '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_linalg_vector_norm_0(in_ptr0, out_ptr0, 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')
    tmp2 = tl.load(in_ptr0 + (1 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr0 + (2 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr0 + (3 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp1 = tmp0 * tmp0
    tmp3 = tmp2 * tmp2
    tmp4 = tmp1 + tmp3
    tmp6 = tmp5 * tmp5
    tmp7 = tmp4 + tmp6
    tmp9 = tmp8 * tmp8
    tmp10 = tmp7 + tmp9
    tmp11 = libdevice.sqrt(tmp10)
    tl.store(out_ptr0 + (x0), tmp11, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_7/inductor_cache/ak/cakyvcloov6rg2vreena4te276nnenqdu5jg5xn5wkrhiykp2cxa.py
# Topologically Sorted Source Nodes: [setitem], Original ATen: [aten.lift_fresh, aten.index_put]
# Source node to ATen node mapping:
#   setitem => full_default, index_put
# Graph fragment:
#   %full_default : [num_users=1] = call_function[target=torch.ops.aten.full.default](args = ([], 9.99999993922529e-09), kwargs = {dtype: torch.float32, layout: torch.strided, device: cpu, pin_memory: False})
#   %index_put : [num_users=1] = call_function[target=torch.ops.aten.index_put_.default](args = (%mm_1, [%lt], %full_default), kwargs = {})
triton_poi_fused_index_put_lift_fresh_1 = async_compile.triton('triton_poi_fused_index_put_lift_fresh_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: '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), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_index_put_lift_fresh_1', 'mutated_arg_names': ['in_out_ptr0'], 'no_x_dim': False, 'num_load': 1, '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_index_put_lift_fresh_1(in_out_ptr0, xnumel, XBLOCK : tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_out_ptr0 + (x0), xmask)
    tmp1 = 1e-08
    tmp2 = tmp0 < tmp1
    tmp3 = 9.99999993922529e-09
    tmp4 = tl.where(tmp2, tmp3, tmp0)
    tl.store(in_out_ptr0 + (x0), tmp4, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_7/inductor_cache/gp/cgphmavd2tjnfbeg36gnziwfjg6ewkbj2aqzyizxvd5g4b7eb7pn.py
# Topologically Sorted Source Nodes: [cos_sim, neg, dist, q_idx], Original ATen: [aten.div, aten.neg, aten.add, aten.argmin]
# Source node to ATen node mapping:
#   cos_sim => div
#   dist => add
#   neg => neg
#   q_idx => argmin
# Graph fragment:
#   %div : [num_users=1] = call_function[target=torch.ops.aten.div.Tensor](args = (%mm, %index_put), kwargs = {})
#   %neg : [num_users=1] = call_function[target=torch.ops.aten.neg.default](args = (%div,), kwargs = {})
#   %add : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%neg, 1), kwargs = {})
#   %argmin : [num_users=2] = call_function[target=torch.ops.aten.argmin.default](args = (%add, -1), kwargs = {})
triton_poi_fused_add_argmin_div_neg_2 = async_compile.triton('triton_poi_fused_add_argmin_div_neg_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=[4], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*i64', 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, 2), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_add_argmin_div_neg_2', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 8, '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_argmin_div_neg_2(in_ptr0, in_ptr1, out_ptr0, 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 + (4*x0), xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr0 + (1 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp7 = tl.load(in_ptr1 + (1 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp26 = tl.load(in_ptr0 + (2 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp27 = tl.load(in_ptr1 + (2 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp45 = tl.load(in_ptr0 + (3 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp46 = tl.load(in_ptr1 + (3 + (4*x0)), xmask, eviction_policy='evict_last')
    tmp2 = tmp0 / tmp1
    tmp3 = -tmp2
    tmp4 = 1.0
    tmp5 = tmp3 + tmp4
    tmp8 = tmp6 / tmp7
    tmp9 = -tmp8
    tmp10 = tmp9 + tmp4
    tmp11 = tmp5 < tmp10
    tmp12 = tmp5 == tmp10
    tmp13 = tmp5 != tmp5
    tmp14 = tmp10 != tmp10
    tmp15 = tmp13 > tmp14
    tmp16 = tmp11 | tmp15
    tmp17 = tmp13 & tmp14
    tmp18 = tmp12 | tmp17
    tmp19 = tl.full([1], 0, tl.int64)
    tmp20 = tl.full([1], 1, tl.int64)
    tmp21 = tmp19 < tmp20
    tmp22 = tmp18 & tmp21
    tmp23 = tmp16 | tmp22
    tmp24 = tl.where(tmp23, tmp5, tmp10)
    tmp25 = tl.where(tmp23, tmp19, tmp20)
    tmp28 = tmp26 / tmp27
    tmp29 = -tmp28
    tmp30 = tmp29 + tmp4
    tmp31 = tmp24 < tmp30
    tmp32 = tmp24 == tmp30
    tmp33 = tmp24 != tmp24
    tmp34 = tmp30 != tmp30
    tmp35 = tmp33 > tmp34
    tmp36 = tmp31 | tmp35
    tmp37 = tmp33 & tmp34
    tmp38 = tmp32 | tmp37
    tmp39 = tl.full([1], 2, tl.int64)
    tmp40 = tmp25 < tmp39
    tmp41 = tmp38 & tmp40
    tmp42 = tmp36 | tmp41
    tmp43 = tl.where(tmp42, tmp24, tmp30)
    tmp44 = tl.where(tmp42, tmp25, tmp39)
    tmp47 = tmp45 / tmp46
    tmp48 = -tmp47
    tmp49 = tmp48 + tmp4
    tmp50 = tmp43 < tmp49
    tmp51 = tmp43 == tmp49
    tmp52 = tmp43 != tmp43
    tmp53 = tmp49 != tmp49
    tmp54 = tmp52 > tmp53
    tmp55 = tmp50 | tmp54
    tmp56 = tmp52 & tmp53
    tmp57 = tmp51 | tmp56
    tmp58 = tl.full([1], 3, tl.int64)
    tmp59 = tmp44 < tmp58
    tmp60 = tmp57 & tmp59
    tmp61 = tmp55 | tmp60
    tmp62 = tl.where(tmp61, tmp43, tmp49)
    tmp63 = tl.where(tmp61, tmp44, tmp58)
    tl.store(out_ptr0 + (x0), tmp63, xmask)
''', device_str='cuda')


# kernel path: runs/run_shard_7/inductor_cache/ws/cwsrzqov5o2drxqo3umuayacgc2kgorquhhcshtwpgfworzd4w5w.py
# Topologically Sorted Source Nodes: [q_data], Original ATen: [aten.index]
# Source node to ATen node mapping:
#   q_data => index
# Graph fragment:
#   %index : [num_users=1] = call_function[target=torch.ops.aten.index.Tensor](args = (%primals_2, [%argmin]), kwargs = {})
triton_poi_fused_index_3 = async_compile.triton('triton_poi_fused_index_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=[16], 
    filename=__file__,
    triton_meta={'signature': {0: '*i64', 1: '*fp32', 2: '*fp32', 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, 2, 3), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_index_3', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 1, '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_index_3(in_ptr0, in_ptr1, out_ptr0, 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 + (x1), xmask, eviction_policy='evict_last')
    tmp1 = tl.full([XBLOCK], 4, tl.int32)
    tmp2 = tmp0 + tmp1
    tmp3 = tmp0 < 0
    tmp4 = tl.where(tmp3, tmp2, tmp0)
    tl.device_assert(((0 <= tmp4) & (tmp4 < 4)) | ~(xmask), "index out of bounds: 0 <= tmp4 < 4")
    tmp6 = tl.load(in_ptr1 + (x0 + (4*tmp4)), xmask)
    tl.store(out_ptr0 + (x2), tmp6, xmask)
''', device_str='cuda')


async_compile.wait(globals())
del async_compile

def call(args):
    primals_1, primals_2 = args
    args.clear()
    assert_size_stride(primals_1, (4, 4), (4, 1))
    assert_size_stride(primals_2, (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: [dot], Original ATen: [aten.mm]
        extern_kernels.mm(primals_1, reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf0)
        buf1 = empty_strided_cuda((4, ), (1, ), torch.float32)
        # Topologically Sorted Source Nodes: [linalg_norm], Original ATen: [aten.linalg_vector_norm]
        stream0 = get_raw_stream(0)
        triton_poi_fused_linalg_vector_norm_0.run(primals_1, buf1, 4, grid=grid(4), stream=stream0)
        del primals_1
        buf2 = empty_strided_cuda((4, ), (1, ), torch.float32)
        # Topologically Sorted Source Nodes: [linalg_norm_1], Original ATen: [aten.linalg_vector_norm]
        triton_poi_fused_linalg_vector_norm_0.run(primals_2, buf2, 4, grid=grid(4), stream=stream0)
        buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [norm], Original ATen: [aten.mm]
        extern_kernels.mm(reinterpret_tensor(buf1, (4, 1), (1, 0), 0), reinterpret_tensor(buf2, (1, 4), (0, 1), 0), out=buf3)
        del buf1
        del buf2
        buf4 = buf3; del buf3  # reuse
        # Topologically Sorted Source Nodes: [setitem], Original ATen: [aten.lift_fresh, aten.index_put]
        triton_poi_fused_index_put_lift_fresh_1.run(buf4, 16, grid=grid(16), stream=stream0)
        buf5 = empty_strided_cuda((4, ), (1, ), torch.int64)
        # Topologically Sorted Source Nodes: [cos_sim, neg, dist, q_idx], Original ATen: [aten.div, aten.neg, aten.add, aten.argmin]
        triton_poi_fused_add_argmin_div_neg_2.run(buf0, buf4, buf5, 4, grid=grid(4), stream=stream0)
        del buf0
        buf6 = buf4; del buf4  # reuse
        # Topologically Sorted Source Nodes: [q_data], Original ATen: [aten.index]
        triton_poi_fused_index_3.run(buf5, primals_2, buf6, 16, grid=grid(16), stream=stream0)
        del primals_2
    return (buf6, buf5, buf5, )


def benchmark_compiled_module(times=10, repeat=10):
    from torch._dynamo.testing import rand_strided
    from torch._inductor.utils import print_performance
    primals_1 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    primals_2 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    fn = lambda: call([primals_1, primals_2])
    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
from typing import Tuple


class Quantizing_cossim(nn.Module):
    """
    This is quantizing layer.
    """
    __initialized: 'bool' = True

    def __init__(self, num_quantizing: 'int', quantizing_dim: 'int',
        _weight: 'torch.Tensor'=None, initialize_by_dataset: 'bool'=True,
        mean: 'float'=0.0, std: 'float'=1.0, eps: 'float'=1e-08, dtype:
        'torch.dtype'=None, device: 'torch.device'=None):
        super().__init__()
        assert num_quantizing > 0
        assert quantizing_dim > 0
        self.num_quantizing = num_quantizing
        self.quantizing_dim = quantizing_dim
        self.initialize_by_dataset = initialize_by_dataset
        self.mean, self.std = mean, std
        self.eps = eps
        if _weight is None:
            self.weight = nn.Parameter(torch.empty(num_quantizing,
                quantizing_dim, dtype=dtype, device=device))
            nn.init.normal_(self.weight, mean=mean, std=std)
            if initialize_by_dataset:
                self.__initialized = False
                self.__initialized_length = 0
        else:
            assert _weight.dim() == 2
            assert _weight.size(0) == num_quantizing
            assert _weight.size(1) == quantizing_dim
            self.weight = nn.Parameter(_weight.to(device))

    def forward(self, x: 'torch.Tensor') ->Tuple[torch.Tensor]:
        """
        x   : shape is (*, E), and weight shape is (Q, E). 
        return -> ( quantized : shape is (*, E), quantized_idx : shape is (*,) )
        """
        input_size = x.shape
        h = x.view(-1, self.quantizing_dim)
        if not self.__initialized and self.initialize_by_dataset:
            getting_len = self.num_quantizing - self.__initialized_length
            init_weight = h[torch.randperm(len(h))[:getting_len]]
            _until = self.__initialized_length + init_weight.size(0)
            self.weight.data[self.__initialized_length:_until] = init_weight
            self.__initialized_length = _until
            None
            if _until >= self.num_quantizing:
                self.__initialized = True
                None
        dist = self.calculate_distance(h)
        q_idx = torch.argmin(dist, dim=-1)
        q_data = self.weight[q_idx]
        return q_data.view(input_size), q_idx.view(input_size[:1])

    def from_idx(self, idx: 'torch.Tensor') ->torch.Tensor:
        """
        idx: shape is (*, ). int tensor.
        return -> (*, E) float tensor
        """
        input_size = idx.shape
        i = idx.view(-1)
        q_data = self.weight[i].view(*input_size, self.quantizing_dim)
        return q_data

    def load_state_dict(self, state_dict, strict: 'bool'):
        self.__initialized = True
        return super().load_state_dict(state_dict, strict=strict)

    def __repr__(self):
        s = f'Quantizing({self.num_quantizing}, {self.quantizing_dim})'
        return s

    def calculate_distance(self, x: 'torch.Tensor') ->torch.Tensor:
        """
        x: shape is (B, *), float tensor
        """
        assert x.dim() == 2
        dot = torch.matmul(x, self.weight.T)
        x_l2n = torch.linalg.norm(x, dim=-1)[:, None]
        w_l2n = torch.linalg.norm(self.weight, dim=-1)[None, :]
        norm = torch.matmul(x_l2n, w_l2n)
        norm[norm < self.eps] = self.eps
        cos_sim = dot / norm
        return -cos_sim + 1

    def isInitialized(self) ->bool:
        return self.__initialized


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


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

import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
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_poi_fused_linalg_vector_norm_0(in_ptr0, out_ptr0, 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')
    tmp2 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp1 = tmp0 * tmp0
    tmp3 = tmp2 * tmp2
    tmp4 = tmp1 + tmp3
    tmp6 = tmp5 * tmp5
    tmp7 = tmp4 + tmp6
    tmp9 = tmp8 * tmp8
    tmp10 = tmp7 + tmp9
    tmp11 = libdevice.sqrt(tmp10)
    tl.store(out_ptr0 + x0, tmp11, xmask)


@triton.jit
def triton_poi_fused_index_put_lift_fresh_1(in_out_ptr0, xnumel, XBLOCK: tl
    .constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_out_ptr0 + x0, xmask)
    tmp1 = 1e-08
    tmp2 = tmp0 < tmp1
    tmp3 = 9.99999993922529e-09
    tmp4 = tl.where(tmp2, tmp3, tmp0)
    tl.store(in_out_ptr0 + x0, tmp4, xmask)


@triton.jit
def triton_poi_fused_add_argmin_div_neg_2(in_ptr0, in_ptr1, out_ptr0,
    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 + 4 * x0, xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp7 = tl.load(in_ptr1 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp26 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp27 = tl.load(in_ptr1 + (2 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp45 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp46 = tl.load(in_ptr1 + (3 + 4 * x0), xmask, eviction_policy='evict_last'
        )
    tmp2 = tmp0 / tmp1
    tmp3 = -tmp2
    tmp4 = 1.0
    tmp5 = tmp3 + tmp4
    tmp8 = tmp6 / tmp7
    tmp9 = -tmp8
    tmp10 = tmp9 + tmp4
    tmp11 = tmp5 < tmp10
    tmp12 = tmp5 == tmp10
    tmp13 = tmp5 != tmp5
    tmp14 = tmp10 != tmp10
    tmp15 = tmp13 > tmp14
    tmp16 = tmp11 | tmp15
    tmp17 = tmp13 & tmp14
    tmp18 = tmp12 | tmp17
    tmp19 = tl.full([1], 0, tl.int64)
    tmp20 = tl.full([1], 1, tl.int64)
    tmp21 = tmp19 < tmp20
    tmp22 = tmp18 & tmp21
    tmp23 = tmp16 | tmp22
    tmp24 = tl.where(tmp23, tmp5, tmp10)
    tmp25 = tl.where(tmp23, tmp19, tmp20)
    tmp28 = tmp26 / tmp27
    tmp29 = -tmp28
    tmp30 = tmp29 + tmp4
    tmp31 = tmp24 < tmp30
    tmp32 = tmp24 == tmp30
    tmp33 = tmp24 != tmp24
    tmp34 = tmp30 != tmp30
    tmp35 = tmp33 > tmp34
    tmp36 = tmp31 | tmp35
    tmp37 = tmp33 & tmp34
    tmp38 = tmp32 | tmp37
    tmp39 = tl.full([1], 2, tl.int64)
    tmp40 = tmp25 < tmp39
    tmp41 = tmp38 & tmp40
    tmp42 = tmp36 | tmp41
    tmp43 = tl.where(tmp42, tmp24, tmp30)
    tmp44 = tl.where(tmp42, tmp25, tmp39)
    tmp47 = tmp45 / tmp46
    tmp48 = -tmp47
    tmp49 = tmp48 + tmp4
    tmp50 = tmp43 < tmp49
    tmp51 = tmp43 == tmp49
    tmp52 = tmp43 != tmp43
    tmp53 = tmp49 != tmp49
    tmp54 = tmp52 > tmp53
    tmp55 = tmp50 | tmp54
    tmp56 = tmp52 & tmp53
    tmp57 = tmp51 | tmp56
    tmp58 = tl.full([1], 3, tl.int64)
    tmp59 = tmp44 < tmp58
    tmp60 = tmp57 & tmp59
    tmp61 = tmp55 | tmp60
    tl.where(tmp61, tmp43, tmp49)
    tmp63 = tl.where(tmp61, tmp44, tmp58)
    tl.store(out_ptr0 + x0, tmp63, xmask)


@triton.jit
def triton_poi_fused_index_3(in_ptr0, in_ptr1, out_ptr0, 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 + x1, xmask, eviction_policy='evict_last')
    tmp1 = tl.full([XBLOCK], 4, tl.int32)
    tmp2 = tmp0 + tmp1
    tmp3 = tmp0 < 0
    tmp4 = tl.where(tmp3, tmp2, tmp0)
    tl.device_assert((0 <= tmp4) & (tmp4 < 4) | ~xmask,
        'index out of bounds: 0 <= tmp4 < 4')
    tmp6 = tl.load(in_ptr1 + (x0 + 4 * tmp4), xmask)
    tl.store(out_ptr0 + x2, tmp6, xmask)


def call(args):
    primals_1, primals_2 = args
    args.clear()
    assert_size_stride(primals_1, (4, 4), (4, 1))
    assert_size_stride(primals_2, (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(primals_1, reinterpret_tensor(primals_2, (4, 4),
            (1, 4), 0), out=buf0)
        buf1 = empty_strided_cuda((4,), (1,), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_linalg_vector_norm_0[grid(4)](primals_1, buf1, 4,
            XBLOCK=4, num_warps=1, num_stages=1)
        del primals_1
        buf2 = empty_strided_cuda((4,), (1,), torch.float32)
        triton_poi_fused_linalg_vector_norm_0[grid(4)](primals_2, buf2, 4,
            XBLOCK=4, num_warps=1, num_stages=1)
        buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        extern_kernels.mm(reinterpret_tensor(buf1, (4, 1), (1, 0), 0),
            reinterpret_tensor(buf2, (1, 4), (0, 1), 0), out=buf3)
        del buf1
        del buf2
        buf4 = buf3
        del buf3
        triton_poi_fused_index_put_lift_fresh_1[grid(16)](buf4, 16, XBLOCK=
            16, num_warps=1, num_stages=1)
        buf5 = empty_strided_cuda((4,), (1,), torch.int64)
        triton_poi_fused_add_argmin_div_neg_2[grid(4)](buf0, buf4, buf5, 4,
            XBLOCK=4, num_warps=1, num_stages=1)
        del buf0
        buf6 = buf4
        del buf4
        triton_poi_fused_index_3[grid(16)](buf5, primals_2, buf6, 16,
            XBLOCK=16, num_warps=1, num_stages=1)
        del primals_2
    return buf6, buf5, buf5


class Quantizing_cossimNew(nn.Module):
    """
    This is quantizing layer.
    """
    __initialized: 'bool' = True

    def __init__(self, num_quantizing: 'int', quantizing_dim: 'int',
        _weight: 'torch.Tensor'=None, initialize_by_dataset: 'bool'=True,
        mean: 'float'=0.0, std: 'float'=1.0, eps: 'float'=1e-08, dtype:
        'torch.dtype'=None, device: 'torch.device'=None):
        super().__init__()
        assert num_quantizing > 0
        assert quantizing_dim > 0
        self.num_quantizing = num_quantizing
        self.quantizing_dim = quantizing_dim
        self.initialize_by_dataset = initialize_by_dataset
        self.mean, self.std = mean, std
        self.eps = eps
        if _weight is None:
            self.weight = nn.Parameter(torch.empty(num_quantizing,
                quantizing_dim, dtype=dtype, device=device))
            nn.init.normal_(self.weight, mean=mean, std=std)
            if initialize_by_dataset:
                self.__initialized = False
                self.__initialized_length = 0
        else:
            assert _weight.dim() == 2
            assert _weight.size(0) == num_quantizing
            assert _weight.size(1) == quantizing_dim
            self.weight = nn.Parameter(_weight.to(device))

    def from_idx(self, idx: 'torch.Tensor') ->torch.Tensor:
        """
        idx: shape is (*, ). int tensor.
        return -> (*, E) float tensor
        """
        input_size = idx.shape
        i = idx.view(-1)
        q_data = self.weight[i].view(*input_size, self.quantizing_dim)
        return q_data

    def load_state_dict(self, state_dict, strict: 'bool'):
        self.__initialized = True
        return super().load_state_dict(state_dict, strict=strict)

    def __repr__(self):
        s = f'Quantizing({self.num_quantizing}, {self.quantizing_dim})'
        return s

    def calculate_distance(self, x: 'torch.Tensor') ->torch.Tensor:
        """
        x: shape is (B, *), float tensor
        """
        assert x.dim() == 2
        dot = torch.matmul(x, self.weight.T)
        x_l2n = torch.linalg.norm(x, dim=-1)[:, None]
        w_l2n = torch.linalg.norm(self.weight, dim=-1)[None, :]
        norm = torch.matmul(x_l2n, w_l2n)
        norm[norm < self.eps] = self.eps
        cos_sim = dot / norm
        return -cos_sim + 1

    def isInitialized(self) ->bool:
        return self.__initialized

    def forward(self, input_0):
        primals_1 = self.weight
        primals_2 = input_0
        output = call([primals_1, primals_2])
        return output[0], output[1]
