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.autograd import Function
import torch.nn.init
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


@triton.jit
def triton_poi_fused_max_sub_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
    ):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x0 = xindex % 64
    tmp0 = tl.load(in_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
    tmp2 = tl.load(in_ptr0 + (64 + x0), xmask, eviction_policy='evict_last')
    tmp4 = tl.load(in_ptr0 + (128 + x0), xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr0 + (192 + 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
    tl.store(out_ptr0 + x2, tmp8, xmask)


@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_sort_1(in_ptr0, out_ptr0, out_ptr1, xnumel,
    rnumel, XBLOCK: tl.constexpr):
    xnumel = 64
    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 + (x0 + 64 * r1), xmask, other=0.0)
    tmp1 = r1
    tmp2 = tmp1.to(tl.int16)
    tmp3 = tl.broadcast_to(tmp0, [XBLOCK, RBLOCK])
    tmp4 = tl.broadcast_to(tmp2, [XBLOCK, RBLOCK])
    tmp5, _tmp6 = triton_helpers.sort_with_index(tmp3, tmp4, None, 1,
        stable=False, descending=True)
    tmp7 = tmp5.to(tl.float32)
    tmp8 = tl.broadcast_to(tmp7, [XBLOCK, RBLOCK])
    tmp9, = tl.associative_scan((tmp8,), 1, _triton_helper_fn_add0)
    tl.store(out_ptr0 + (x0 + 64 * r1), tmp5, xmask)
    tl.store(out_ptr1 + (x0 + 64 * r1), tmp9, xmask)


@triton.jit
def triton_poi_fused_gt_mul_sub_sum_2(in_ptr0, in_ptr1, out_ptr0, xnumel,
    XBLOCK: tl.constexpr):
    xnumel = 64
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + x0, xmask)
    tmp3 = tl.load(in_ptr1 + x0, xmask)
    tmp7 = tl.load(in_ptr0 + (64 + x0), xmask)
    tmp10 = tl.load(in_ptr1 + (64 + x0), xmask)
    tmp15 = tl.load(in_ptr0 + (128 + x0), xmask)
    tmp18 = tl.load(in_ptr1 + (128 + x0), xmask)
    tmp23 = tl.load(in_ptr0 + (192 + x0), xmask)
    tmp26 = tl.load(in_ptr1 + (192 + x0), xmask)
    tmp1 = 1.0
    tmp2 = tmp1 * tmp0
    tmp4 = tmp3 - tmp1
    tmp5 = tmp2 > tmp4
    tmp6 = tmp5.to(tl.int64)
    tmp8 = 2.0
    tmp9 = tmp8 * tmp7
    tmp11 = tmp10 - tmp1
    tmp12 = tmp9 > tmp11
    tmp13 = tmp12.to(tl.int64)
    tmp14 = tmp6 + tmp13
    tmp16 = 3.0
    tmp17 = tmp16 * tmp15
    tmp19 = tmp18 - tmp1
    tmp20 = tmp17 > tmp19
    tmp21 = tmp20.to(tl.int64)
    tmp22 = tmp14 + tmp21
    tmp24 = 4.0
    tmp25 = tmp24 * tmp23
    tmp27 = tmp26 - tmp1
    tmp28 = tmp25 > tmp27
    tmp29 = tmp28.to(tl.int64)
    tmp30 = tmp22 + tmp29
    tl.store(out_ptr0 + x0, tmp30, xmask)


@triton.jit
def triton_poi_fused_clamp_div_gather_sub_3(in_ptr0, in_ptr1, in_ptr2,
    out_ptr0, out_ptr1, xnumel, XBLOCK: tl.constexpr):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x0 = xindex % 64
    tmp0 = tl.load(in_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr1 + x0, 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 + (x0 + 64 * tmp7), xmask)
    tmp10 = 1.0
    tmp11 = tmp9 - tmp10
    tmp12 = tmp1.to(tl.float32)
    tmp13 = tmp11 / tmp12
    tmp14 = tmp0 - tmp13
    tmp15 = 0.0
    tmp16 = triton_helpers.maximum(tmp14, tmp15)
    tl.store(out_ptr0 + x2, tmp16, xmask)
    tl.store(out_ptr1 + x2, tmp0, xmask)


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)
        buf0 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_max_sub_0[grid(256)](arg0_1, buf0, 256, XBLOCK=256,
            num_warps=4, num_stages=1)
        buf1 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        buf3 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        triton_per_fused_cumsum_sort_1[grid(64)](buf0, buf1, buf3, 64, 4,
            XBLOCK=32, num_warps=2, num_stages=1)
        buf4 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.int64)
        triton_poi_fused_gt_mul_sub_sum_2[grid(64)](buf1, buf3, buf4, 64,
            XBLOCK=64, num_warps=1, num_stages=1)
        buf5 = buf1
        del buf1
        triton_poi_fused_clamp_div_gather_sub_3[grid(256)](buf0, buf4, buf3,
            buf5, arg0_1, 256, XBLOCK=128, num_warps=4, num_stages=1)
        del arg0_1
        del buf0
        del buf3
        del buf4
    return buf5,


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 _threshold_and_support(input, dim=0):
    """Sparsemax building block: compute the threshold
    Args:
        input: any dimension
        dim: dimension along which to apply the sparsemax
    Returns:
        the threshold value
    """
    input_srt, _ = torch.sort(input, descending=True, dim=dim)
    input_cumsum = input_srt.cumsum(dim) - 1
    rhos = _make_ix_like(input, dim)
    support = rhos * input_srt > input_cumsum
    support_size = support.sum(dim=dim).unsqueeze(dim)
    tau = input_cumsum.gather(dim, support_size - 1)
    tau /= support_size
    return tau, support_size


def sparsemax(input, dim=0):
    return SparsemaxFunction.apply(input, dim)


class SparsemaxFunction(Function):

    @staticmethod
    def forward(ctx, input, dim=0):
        """sparsemax: normalizing sparse transform (a la softmax)
        Parameters:
            input (Tensor): any shape
            dim: dimension along which to apply sparsemax
        Returns:
            output (Tensor): same shape as input
        """
        ctx.dim = dim
        max_val, _ = input.max(dim=dim, keepdim=True)
        input -= max_val
        tau, supp_size = _threshold_and_support(input, dim=dim)
        output = torch.clamp(input - tau, min=0)
        ctx.save_for_backward(supp_size, output)
        return output

    @staticmethod
    def backward(ctx, grad_output):
        supp_size, output = ctx.saved_tensors
        dim = ctx.dim
        grad_input = grad_output.clone()
        grad_input[output == 0] = 0
        v_hat = grad_input.sum(dim=dim) / supp_size.squeeze()
        v_hat = v_hat.unsqueeze(dim)
        grad_input = torch.where(output != 0, grad_input - v_hat, grad_input)
        return grad_input, None


class SparsemaxNew(nn.Module):

    def __init__(self, dim=0):
        self.dim = dim
        super(SparsemaxNew, self).__init__()

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


Measured latency_ms: 0.055619