import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime import triton_helpers
from torch._inductor.runtime.triton_helpers import libdevice
from torch.autograd import Function
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_helper_fn_add0(arg0_0, arg1_0):
    tmp0 = arg0_0 + arg1_0
    return tmp0


@triton.jit
def triton_per_fused_cumsum_div_max_pow_sort_sub_0(in_ptr0, out_ptr0,
    out_ptr1, out_ptr2, out_ptr3, xnumel, rnumel, XBLOCK: tl.constexpr):
    xnumel = 4
    RBLOCK: tl.constexpr = 4
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    rindex = tl.arange(0, RBLOCK)[None, :]
    tl.full([XBLOCK, RBLOCK], True, tl.int1)
    r1 = rindex
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + (r1 + 4 * x0), xmask, other=0.0)
    tmp1 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
    tmp2 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp4 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp3 = triton_helpers.maximum(tmp1, tmp2)
    tmp5 = triton_helpers.maximum(tmp3, tmp4)
    tmp7 = triton_helpers.maximum(tmp5, tmp6)
    tmp8 = tmp0 - tmp7
    tmp9 = 0.5
    tmp10 = tmp8 * tmp9
    tmp11 = r1
    tmp12 = tmp11.to(tl.int16)
    tmp13 = tl.broadcast_to(tmp10, [XBLOCK, RBLOCK])
    tmp14 = tl.broadcast_to(tmp12, [XBLOCK, RBLOCK])
    tmp15, _tmp16 = triton_helpers.sort_with_index(tmp13, tmp14, None, 1,
        stable=False, descending=True)
    tmp17 = tmp15.to(tl.float32)
    tmp18 = tl.broadcast_to(tmp17, [XBLOCK, RBLOCK])
    tmp19, = tl.associative_scan((tmp18,), 1, _triton_helper_fn_add0)
    tmp20 = tmp15 * tmp15
    tmp21 = tmp20.to(tl.float32)
    tmp22 = tl.broadcast_to(tmp21, [XBLOCK, RBLOCK])
    tmp23, = tl.associative_scan((tmp22,), 1, _triton_helper_fn_add0)
    tl.store(out_ptr0 + (r1 + 4 * x0), tmp10, xmask)
    tl.store(out_ptr1 + (r1 + 4 * x0), tmp15, xmask)
    tl.store(out_ptr2 + (r1 + 4 * x0), tmp19, xmask)
    tl.store(out_ptr3 + (r1 + 4 * x0), tmp23, xmask)


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


@triton.jit
def triton_poi_fused_clamp_div_gather_mul_pow_rsub_sqrt_sub_2(in_ptr0,
    in_ptr1, in_ptr2, in_ptr3, 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
    x2 = xindex
    x1 = xindex // 4
    tmp0 = tl.load(in_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
    tmp2 = tl.full([1], 1, tl.int64)
    tmp3 = tmp1 - tmp2
    tmp4 = tl.full([XBLOCK], 4, tl.int32)
    tmp5 = tmp3 + tmp4
    tmp6 = tmp3 < 0
    tmp7 = tl.where(tmp6, tmp5, tmp3)
    tl.device_assert((0 <= tmp7) & (tmp7 < 4) | ~xmask,
        'index out of bounds: 0 <= tmp7 < 4')
    tmp9 = tl.load(in_ptr2 + (tmp7 + 4 * x1), xmask, eviction_policy=
        'evict_last')
    tmp10 = 1 + tmp7
    tmp11 = tmp10.to(tl.float32)
    tmp12 = tmp9 / tmp11
    tmp13 = tl.load(in_ptr3 + (tmp7 + 4 * x1), xmask, eviction_policy=
        'evict_last')
    tmp14 = tmp13 / tmp11
    tmp15 = tmp12 * tmp12
    tmp16 = tmp14 - tmp15
    tmp17 = tmp11 * tmp16
    tmp18 = 1.0
    tmp19 = tmp18 - tmp17
    tmp20 = tmp19 / tmp11
    tmp21 = 0.0
    tmp22 = triton_helpers.maximum(tmp20, tmp21)
    tmp23 = libdevice.sqrt(tmp22)
    tmp24 = tmp12 - tmp23
    tmp25 = tmp0 - tmp24
    tmp26 = triton_helpers.maximum(tmp25, tmp21)
    tmp27 = tmp26 * tmp26
    tmp28 = libdevice.sqrt(tmp27)
    tl.store(out_ptr0 + x2, tmp27, xmask)
    tl.store(out_ptr1 + x2, tmp28, 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)
        buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        buf3 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        buf4 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        get_raw_stream(0)
        triton_per_fused_cumsum_div_max_pow_sort_sub_0[grid(4)](primals_1,
            buf0, buf1, buf3, buf4, 4, 4, XBLOCK=1, num_warps=2, num_stages=1)
        del primals_1
        buf5 = empty_strided_cuda((4,), (1,), torch.int64)
        triton_poi_fused_clamp_div_le_mul_pow_rsub_sqrt_sub_sum_1[grid(4)](buf3
            , buf4, buf1, buf5, 4, XBLOCK=4, num_warps=1, num_stages=1)
        buf6 = buf1
        del buf1
        buf8 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        triton_poi_fused_clamp_div_gather_mul_pow_rsub_sqrt_sub_2[grid(16)](
            buf0, buf5, buf3, buf4, buf6, buf8, 16, XBLOCK=16, num_warps=1,
            num_stages=1)
        del buf0
        del buf3
        del buf5
        buf7 = reinterpret_tensor(buf4, (1, 4, 4), (16, 4, 1), 0)
        del buf4
        extern_kernels.bmm(reinterpret_tensor(primals_2, (1, 4, 4), (16, 4,
            1), 0), reinterpret_tensor(buf6, (1, 4, 4), (0, 4, 1), 0), out=buf7
            )
        del buf6
    return reinterpret_tensor(buf7, (4, 4), (4, 1), 0), reinterpret_tensor(
        primals_2, (1, 4, 4), (16, 1, 4), 0), buf8


def _make_ix_like(input, dim=0):
    d = input.size(dim)
    rho = torch.arange(1, d + 1, device=input.device, dtype=input.dtype)
    view = [1] * input.dim()
    view[0] = -1
    return rho.view(view).transpose(0, dim)


def entmax15(input, dim=-1):
    return Entmax15Function.apply(input, dim)


class Entmax15Function(Function):
    """
    An implementation of exact Entmax with alpha=1.5 (B. Peters, V. Niculae, A. Martins). See
    :cite:`https://arxiv.org/abs/1905.05702 for detailed description.
    Source: https://github.com/deep-spin/entmax
    """

    @staticmethod
    def forward(ctx, input, dim=-1):
        ctx.dim = dim
        max_val, _ = input.max(dim=dim, keepdim=True)
        input = input - max_val
        input = input / 2
        tau_star, _ = Entmax15Function._threshold_and_support(input, dim)
        output = torch.clamp(input - tau_star, min=0) ** 2
        ctx.save_for_backward(output)
        return output

    @staticmethod
    def backward(ctx, grad_output):
        Y, = ctx.saved_tensors
        gppr = Y.sqrt()
        dX = grad_output * gppr
        q = dX.sum(ctx.dim) / gppr.sum(ctx.dim)
        q = q.unsqueeze(ctx.dim)
        dX -= q * gppr
        return dX, None

    @staticmethod
    def _threshold_and_support(input, dim=-1):
        Xsrt, _ = torch.sort(input, descending=True, dim=dim)
        rho = _make_ix_like(input, dim)
        mean = Xsrt.cumsum(dim) / rho
        mean_sq = (Xsrt ** 2).cumsum(dim) / rho
        ss = rho * (mean_sq - mean ** 2)
        delta = (1 - ss) / rho
        delta_nz = torch.clamp(delta, 0)
        tau = mean - torch.sqrt(delta_nz)
        support_size = (tau <= Xsrt).sum(dim).unsqueeze(dim)
        tau_star = tau.gather(dim, support_size - 1)
        return tau_star, support_size


class EntMaxSelectLayerNew(nn.Module):

    def __init__(self, in_features, out_features):
        super().__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.weight = torch.nn.Parameter(torch.empty(in_features,
            out_features), requires_grad=True)

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


Measured latency_ms: 0.058106