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 math as tl_math
import numpy as np
from itertools import product as product
from torch import nn
import torch.optim
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_per_fused_abs_add_div_gt_le_lift_fresh_lt_mul_neg_sum_where_0(
    in_ptr0, out_ptr1, xnumel, rnumel, XBLOCK: tl.constexpr):
    RBLOCK: tl.constexpr = 16
    xoffset = tl.program_id(0) * XBLOCK
    xoffset + tl.arange(0, XBLOCK)[:, None]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    rindex = tl.arange(0, RBLOCK)[None, :]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    r0 = rindex
    tmp0 = tl.load(in_ptr0 + r0, None)
    tmp1 = tl_math.abs(tmp0)
    tmp2 = tl.broadcast_to(tmp1, [XBLOCK, RBLOCK])
    tmp4 = tl.sum(tmp2, 1)[:, None]
    tmp5 = 0.0
    tmp6 = tmp4 + tmp5
    tmp7 = 0.0625
    tmp8 = tmp6 * tmp7
    tmp9 = 0.7
    tmp10 = tmp8 * tmp9
    tmp11 = -tmp10
    tmp12 = tmp0 < tmp11
    tmp13 = tmp1 <= tmp11
    tmp14 = tmp0 > tmp10
    tmp15 = 1.0
    tmp16 = tl.where(tmp14, tmp15, tmp5)
    tmp17 = tl.where(tmp13, tmp5, tmp16)
    tmp18 = -1.0
    tmp19 = tl.where(tmp12, tmp18, tmp17)
    tl.store(out_ptr1 + tl.broadcast_to(r0, [XBLOCK, RBLOCK]), tmp19, None)


def call(args):
    primals_1, primals_2, primals_3 = args
    args.clear()
    assert_size_stride(primals_1, (4, 4), (4, 1))
    assert_size_stride(primals_2, (4,), (1,))
    assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        get_raw_stream(0)
        triton_per_fused_abs_add_div_gt_le_lift_fresh_lt_mul_neg_sum_where_0[
            grid(1)](primals_1, buf1, 1, 16, XBLOCK=1, num_warps=2,
            num_stages=1)
        del primals_1
        buf2 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
        extern_kernels.addmm(primals_2, reinterpret_tensor(primals_3, (64, 
            4), (4, 1), 0), reinterpret_tensor(buf1, (4, 4), (1, 4), 0),
            alpha=1, beta=1, out=buf2)
        del primals_2
    return reinterpret_tensor(buf2, (4, 4, 4, 4), (64, 16, 4, 1), 0
        ), buf1, reinterpret_tensor(primals_3, (64, 4), (4, 1), 0)


def ternary_threshold(delta: 'float'=0.7, *ws):
    """Ternary threshold find in ws."""
    assert isinstance(delta, float)
    num_params = sum_w = 0
    if not ws:
        threshold = torch.tensor(np.nan)
    else:
        for w in ws:
            num_params += w.data.numel()
            sum_w += w.abs().sum()
        threshold = delta * (sum_w / num_params)
    return threshold


class TerQuant(torch.autograd.Function):
    """TeraryNet quantization function."""

    @staticmethod
    def forward(ctx, w, threshold):
        ctx.save_for_backward(w, threshold)
        w_ter = torch.where(w > threshold, torch.tensor(1.0), torch.tensor(0.0)
            )
        w_ter = torch.where(w.abs() <= -threshold, torch.tensor(0.0), w_ter)
        w_ter = torch.where(w < -threshold, torch.tensor(-1.0), w_ter)
        return w_ter

    @staticmethod
    def backward(ctx, grad_o):
        """Back propagation using same as identity function."""
        grad_i = grad_o.clone()
        return grad_i, None


class TerLinearNew(nn.Linear):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.delta = 0.7

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


Measured latency_ms: 0.033016