# 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/2q/c2qfftq24ton4cb76uuegdwiejatkiqpir6ng7evufq2rm2ldwbg.py
# Topologically Sorted Source Nodes: [min_value, neg, add_, max_value, sub, scale, scale_1, div_, output_1, clamp_, output_2, add__2, mul_, output_3], Original ATen: [aten.min, aten.neg, aten.add, aten.max, aten.sub, aten.div, aten.clamp, aten.round, aten.mul]
# Source node to ATen node mapping:
#   add_ => add
#   add__2 => add_2
#   clamp_ => clamp_max, clamp_min_1
#   div_ => div_1
#   max_value => max_1
#   min_value => min_1
#   mul_ => mul
#   neg => neg
#   output_1 => add_1
#   output_2 => round_1
#   output_3 => add_3
#   scale => div
#   scale_1 => clamp_min
#   sub => sub
# Graph fragment:
#   %min_1 : [num_users=3] = call_function[target=torch.ops.aten.min.default](args = (%arg0_1,), kwargs = {})
#   %neg : [num_users=1] = call_function[target=torch.ops.aten.neg.default](args = (%min_1,), kwargs = {})
#   %add : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%arg0_1, %neg), kwargs = {})
#   %max_1 : [num_users=1] = call_function[target=torch.ops.aten.max.default](args = (%arg0_1,), kwargs = {})
#   %sub : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%max_1, %min_1), kwargs = {})
#   %div : [num_users=1] = call_function[target=torch.ops.aten.div.Tensor](args = (%sub, 255.0), kwargs = {})
#   %clamp_min : [num_users=2] = call_function[target=torch.ops.aten.clamp_min.default](args = (%div, 1e-08), kwargs = {})
#   %div_1 : [num_users=1] = call_function[target=torch.ops.aten.div.Tensor](args = (%add, %clamp_min), kwargs = {})
#   %add_1 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%div_1, 0.0), kwargs = {})
#   %clamp_min_1 : [num_users=1] = call_function[target=torch.ops.aten.clamp_min.default](args = (%add_1, 0.0), kwargs = {})
#   %clamp_max : [num_users=1] = call_function[target=torch.ops.aten.clamp_max.default](args = (%clamp_min_1, 255.0), kwargs = {})
#   %round_1 : [num_users=1] = call_function[target=torch.ops.aten.round.default](args = (%clamp_max,), kwargs = {})
#   %add_2 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%round_1, -0.0), kwargs = {})
#   %mul : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%add_2, %clamp_min), kwargs = {})
#   %add_3 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%mul, %min_1), kwargs = {})
triton_per_fused_add_clamp_div_max_min_mul_neg_round_sub_0 = async_compile.triton('triton_per_fused_add_clamp_div_max_min_mul_neg_round_sub_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, 256],
    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_add_clamp_div_max_min_mul_neg_round_sub_0', 'mutated_arg_names': [], 'no_x_dim': True, 'num_load': 1, 'num_reduction': 2, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False}
)
@triton.jit
def triton_per_fused_add_clamp_div_max_min_mul_neg_round_sub_0(in_ptr0, out_ptr2, xnumel, rnumel):
    xnumel = 1
    XBLOCK: tl.constexpr = 1
    rnumel = 256
    RBLOCK: tl.constexpr = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = tl.full([1], xoffset, tl.int32)
    xmask = tl.full([RBLOCK], True, tl.int1)
    rindex = tl.arange(0, RBLOCK)[:]
    roffset = 0
    rmask = tl.full([RBLOCK], True, tl.int1)
    r0 = rindex
    tmp0 = tl.load(in_ptr0 + (r0), None)
    tmp1 = tl.broadcast_to(tmp0, [RBLOCK])
    tmp3 = triton_helpers.promote_to_tensor(triton_helpers.min2(tmp1, 0))
    tmp5 = triton_helpers.promote_to_tensor(triton_helpers.max2(tmp1, 0))
    tmp6 = -tmp3
    tmp7 = tmp0 + tmp6
    tmp8 = tmp5 - tmp3
    tmp9 = 0.00392156862745098
    tmp10 = tmp8 * tmp9
    tmp11 = 1e-08
    tmp12 = triton_helpers.maximum(tmp10, tmp11)
    tmp13 = tmp7 / tmp12
    tmp14 = 0.0
    tmp15 = tmp13 + tmp14
    tmp16 = triton_helpers.maximum(tmp15, tmp14)
    tmp17 = 255.0
    tmp18 = triton_helpers.minimum(tmp16, tmp17)
    tmp19 = libdevice.nearbyint(tmp18)
    tmp20 = -0.0
    tmp21 = tmp19 + tmp20
    tmp22 = tmp21 * tmp12
    tmp23 = tmp22 + tmp3
    tl.store(out_ptr2 + (tl.broadcast_to(r0, [RBLOCK])), tmp23, None)
''', device_str='cuda')


async_compile.wait(globals())
del async_compile

def call(args):
    arg0_1, = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [min_value, neg, add_, max_value, sub, scale, scale_1, div_, output_1, clamp_, output_2, add__2, mul_, output_3], Original ATen: [aten.min, aten.neg, aten.add, aten.max, aten.sub, aten.div, aten.clamp, aten.round, aten.mul]
        stream0 = get_raw_stream(0)
        triton_per_fused_add_clamp_div_max_min_mul_neg_round_sub_0.run(arg0_1, buf2, 1, 256, grid=grid(1), stream=stream0)
        del arg0_1
    return (buf2, )


def benchmark_compiled_module(times=10, repeat=10):
    from torch._dynamo.testing import rand_strided
    from torch._inductor.utils import print_performance
    arg0_1 = rand_strided((4, 4, 4, 4), (64, 16, 4, 1), device='cuda:0', dtype=torch.float32)
    fn = lambda: call([arg0_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
from torch.autograd.function import InplaceFunction


def quantize(x, num_bits=8, min_value=None, max_value=None, num_chunks=None,
    stochastic=False, inplace=False, quantize=False, layer_num=-1, multi=
    False, index=[], is_act=False):
    return UniformQuantize().apply(x, num_bits, min_value, max_value,
        stochastic, inplace, num_chunks, False, quantize, layer_num, multi,
        index, is_act)


class UniformQuantize(InplaceFunction):

    @classmethod
    def forward(cls, ctx, input, num_bits=8, min_value=None, max_value=None,
        stochastic=False, inplace=False, num_chunks=None, out_half=False,
        quantize=False, layer_num=-1, multi=False, index=[], is_act=False):
        if is_act:
            multi = False
        num_chunks = num_chunks = input.shape[0
            ] if num_chunks is None else num_chunks
        if min_value is None or max_value is None:
            B = input.shape[0]
            y = input.view(B // num_chunks, -1)
        if min_value is None:
            min_value = y.min(-1)[0].mean(-1)
        if max_value is None:
            max_value = y.max(-1)[0].mean(-1)
        ctx.inplace = inplace
        ctx.num_bits = num_bits
        ctx.min_value = min_value
        ctx.max_value = max_value
        ctx.stochastic = stochastic
        if ctx.inplace:
            ctx.mark_dirty(input)
            output = input
        else:
            output = input.clone()
        if multi:
            bit_max = 8
            for i in range(bit_max):
                if len(index[layer_num][i]) == 0:
                    continue
                else:
                    idx = index[layer_num][i]
                min_value = output[idx].min()
                max_value = output[idx].max()
                qmin = 0.0
                qmax = 2.0 ** (1 + i) - 1.0
                scale = (max_value - min_value) / (qmax - qmin)
                scale = max(scale, 1e-08)
                output[idx] = output[idx].add_(-min_value).div_(scale).add_(
                    qmin)
                output[idx] = output[idx].clamp_(qmin, qmax).round_()
                output[idx] = output[idx].add_(-qmin).mul_(scale).add_(
                    min_value)
        else:
            min_value = output.min()
            max_value = output.max()
            qmin = 0.0
            qmax = 2.0 ** num_bits - 1.0
            scale = (max_value - min_value) / (qmax - qmin)
            scale = max(scale, 1e-08)
            output = output.add_(-min_value).div_(scale).add_(qmin)
            output = output.clamp_(qmin, qmax).round_()
            output = output.add_(-qmin).mul_(scale).add_(min_value)
        return output

    @staticmethod
    def backward(ctx, grad_output):
        grad_input = grad_output
        return (grad_input, None, None, None, None, None, None, None, None,
            None, None, None, None)


class QuantMeasure(nn.Module):
    """docstring for QuantMeasure."""

    def __init__(self, num_bits=8, quantize=False, momentum=0.1):
        super(QuantMeasure, self).__init__()
        self.register_buffer('running_min', torch.zeros(1))
        self.register_buffer('running_max', torch.zeros(1))
        self.momentum = momentum
        self.num_bits = num_bits
        self.quantize = quantize

    def forward(self, input):
        if self.training:
            min_value = input.detach().view(input.size(0), -1).min(-1)[0].mean(
                )
            max_value = input.detach().view(input.size(0), -1).max(-1)[0].mean(
                )
            self.running_min.mul_(self.momentum).add_(min_value * (1 - self
                .momentum))
            self.running_max.mul_(self.momentum).add_(max_value * (1 - self
                .momentum))
        else:
            min_value = self.running_min
            max_value = self.running_max
        return quantize(input, self.num_bits, min_value=float(min_value),
            max_value=float(max_value), num_chunks=16, quantize=self.
            quantize, is_act=True)


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


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

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
from torch._inductor.runtime.triton_helpers import libdevice
from torch import nn
from torch.autograd.function import InplaceFunction
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_clamp_div_max_min_mul_neg_round_sub_0(in_ptr0,
    out_ptr2, xnumel, rnumel):
    XBLOCK: tl.constexpr = 1
    RBLOCK: tl.constexpr = 256
    xoffset = tl.program_id(0) * XBLOCK
    tl.full([1], xoffset, tl.int32)
    tl.full([RBLOCK], True, tl.int1)
    rindex = tl.arange(0, RBLOCK)[:]
    tl.full([RBLOCK], True, tl.int1)
    r0 = rindex
    tmp0 = tl.load(in_ptr0 + r0, None)
    tmp1 = tl.broadcast_to(tmp0, [RBLOCK])
    tmp3 = triton_helpers.promote_to_tensor(triton_helpers.min2(tmp1, 0))
    tmp5 = triton_helpers.promote_to_tensor(triton_helpers.max2(tmp1, 0))
    tmp6 = -tmp3
    tmp7 = tmp0 + tmp6
    tmp8 = tmp5 - tmp3
    tmp9 = 0.00392156862745098
    tmp10 = tmp8 * tmp9
    tmp11 = 1e-08
    tmp12 = triton_helpers.maximum(tmp10, tmp11)
    tmp13 = tmp7 / tmp12
    tmp14 = 0.0
    tmp15 = tmp13 + tmp14
    tmp16 = triton_helpers.maximum(tmp15, tmp14)
    tmp17 = 255.0
    tmp18 = triton_helpers.minimum(tmp16, tmp17)
    tmp19 = libdevice.nearbyint(tmp18)
    tmp20 = -0.0
    tmp21 = tmp19 + tmp20
    tmp22 = tmp21 * tmp12
    tmp23 = tmp22 + tmp3
    tl.store(out_ptr2 + tl.broadcast_to(r0, [RBLOCK]), tmp23, None)


def call(args):
    arg0_1, = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        get_raw_stream(0)
        triton_per_fused_add_clamp_div_max_min_mul_neg_round_sub_0[grid(1)](
            arg0_1, buf2, 1, 256, num_warps=2, num_stages=1)
        del arg0_1
    return buf2,


def quantize(x, num_bits=8, min_value=None, max_value=None, num_chunks=None,
    stochastic=False, inplace=False, quantize=False, layer_num=-1, multi=
    False, index=[], is_act=False):
    return UniformQuantize().apply(x, num_bits, min_value, max_value,
        stochastic, inplace, num_chunks, False, quantize, layer_num, multi,
        index, is_act)


class UniformQuantize(InplaceFunction):

    @classmethod
    def forward(cls, ctx, input, num_bits=8, min_value=None, max_value=None,
        stochastic=False, inplace=False, num_chunks=None, out_half=False,
        quantize=False, layer_num=-1, multi=False, index=[], is_act=False):
        if is_act:
            multi = False
        num_chunks = num_chunks = input.shape[0
            ] if num_chunks is None else num_chunks
        if min_value is None or max_value is None:
            B = input.shape[0]
            y = input.view(B // num_chunks, -1)
        if min_value is None:
            min_value = y.min(-1)[0].mean(-1)
        if max_value is None:
            max_value = y.max(-1)[0].mean(-1)
        ctx.inplace = inplace
        ctx.num_bits = num_bits
        ctx.min_value = min_value
        ctx.max_value = max_value
        ctx.stochastic = stochastic
        if ctx.inplace:
            ctx.mark_dirty(input)
            output = input
        else:
            output = input.clone()
        if multi:
            bit_max = 8
            for i in range(bit_max):
                if len(index[layer_num][i]) == 0:
                    continue
                else:
                    idx = index[layer_num][i]
                min_value = output[idx].min()
                max_value = output[idx].max()
                qmin = 0.0
                qmax = 2.0 ** (1 + i) - 1.0
                scale = (max_value - min_value) / (qmax - qmin)
                scale = max(scale, 1e-08)
                output[idx] = output[idx].add_(-min_value).div_(scale).add_(
                    qmin)
                output[idx] = output[idx].clamp_(qmin, qmax).round_()
                output[idx] = output[idx].add_(-qmin).mul_(scale).add_(
                    min_value)
        else:
            min_value = output.min()
            max_value = output.max()
            qmin = 0.0
            qmax = 2.0 ** num_bits - 1.0
            scale = (max_value - min_value) / (qmax - qmin)
            scale = max(scale, 1e-08)
            output = output.add_(-min_value).div_(scale).add_(qmin)
            output = output.clamp_(qmin, qmax).round_()
            output = output.add_(-qmin).mul_(scale).add_(min_value)
        return output

    @staticmethod
    def backward(ctx, grad_output):
        grad_input = grad_output
        return (grad_input, None, None, None, None, None, None, None, None,
            None, None, None, None)


class QuantMeasureNew(nn.Module):
    """docstring for QuantMeasure."""

    def __init__(self, num_bits=8, quantize=False, momentum=0.1):
        super(QuantMeasureNew, self).__init__()
        self.register_buffer('running_min', torch.zeros(1))
        self.register_buffer('running_max', torch.zeros(1))
        self.momentum = momentum
        self.num_bits = num_bits
        self.quantize = quantize

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