import torch
from typing import Optional
import torch.utils.data
import torch.nn


class MaskedTemporalPooling(torch.nn.Module):
    """
    Applies temporal pooling operations on masked inputs. For each pooling operation
    all masked values are ignored.
    """

    def __init__(self, method: 'str'):
        """
        method (str): the method of pooling to use. Options:
            'max': reduces temporal dimension to each valid max value.
            'avg': averages valid values in the temporal dimension.
            'sum': sums valid values in the temporal dimension.
            Note if all batch row elements are invalid, the temporal dimension is
            pooled to 0 values.
        """
        super().__init__()
        assert method in ('max', 'avg', 'sum')
        self._method = method

    def forward(self, x: 'torch.Tensor', mask: 'Optional[torch.Tensor]'=None
        ) ->torch.Tensor:
        """
        Args:
            x (torch.Tensor): tensor with shape (batch_size, seq_len, feature_dim)
            mask (torch.Tensor): bool tensor with shape (batch_size, seq_len).
                Sequence elements that are False are invalid.

        Returns:
            Tensor with shape (batch_size, feature_dim)
        """
        assert x.dim(
            ) == 3, 'Requires x shape (batch_size x seq_len x feature_dim)'
        b, t = x.shape[0], x.shape[1]
        if mask is None:
            mask = torch.ones((b, t), dtype=torch.bool)
        if self._method == 'max':
            x[~mask, :] = float('-inf')
            invalid_first_dim = ~mask.view(b, -1).any(dim=-1)
            x[invalid_first_dim, :] = 0
            x = torch.max(x, dim=1)[0]
        elif self._method == 'avg':
            x = x * mask.unsqueeze(-1).float()
            mask = mask.view(b, t, -1).any(dim=-1)
            valid_lengths = mask.float().sum(dim=-1).int()
            x = x.sum(dim=1)
            x = x.div(valid_lengths.clamp(min=1).unsqueeze(-1).expand(x.
                size()).float())
        elif self._method == 'sum':
            x = x * mask.unsqueeze(-1).float()
            x = x.sum(dim=1)
        else:
            raise NotImplementedError(
                f"{self._method} not available options are: 'max', 'avg', 'sum'"
                )
        return x


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


def get_init_inputs():
    return [[], {'method': 'max'}]

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
import torch.utils.data
import torch.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_index_put_lift_fresh_0(in_ptr0, 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)
    tmp1 = tl.full([1], False, tl.int1)
    tmp2 = float('-inf')
    tmp3 = tl.where(tmp1, tmp2, tmp0)
    tl.store(out_ptr0 + x0, tmp3, xmask)


@triton.jit
def triton_poi_fused_index_put_lift_fresh_1(in_ptr0, 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
    tmp5 = tl.load(in_ptr0 + x0, xmask)
    tmp0 = tl.full([1], True, tl.int1)
    tmp1 = tmp0 | tmp0
    tmp2 = tmp1 | tmp0
    tmp3 = tmp2 | tmp0
    tmp4 = tmp3 == 0
    tmp6 = 0.0
    tmp7 = tl.where(tmp4, tmp6, tmp5)
    tl.store(out_ptr0 + x0, tmp7, xmask)


@triton.jit
def triton_poi_fused_max_2(in_ptr0, 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 % 4
    x1 = xindex // 4
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + (x0 + 16 * x1), xmask)
    tmp1 = tl.load(in_ptr0 + (4 + x0 + 16 * x1), xmask)
    tmp3 = tl.load(in_ptr0 + (8 + x0 + 16 * x1), xmask)
    tmp5 = tl.load(in_ptr0 + (12 + x0 + 16 * x1), xmask)
    tmp2 = triton_helpers.maximum(tmp0, tmp1)
    tmp4 = triton_helpers.maximum(tmp2, tmp3)
    tmp6 = triton_helpers.maximum(tmp4, tmp5)
    tl.store(out_ptr0 + x2, tmp6, xmask)


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


class MaskedTemporalPoolingNew(torch.nn.Module):
    """
    Applies temporal pooling operations on masked inputs. For each pooling operation
    all masked values are ignored.
    """

    def __init__(self, method: 'str'):
        """
        method (str): the method of pooling to use. Options:
            'max': reduces temporal dimension to each valid max value.
            'avg': averages valid values in the temporal dimension.
            'sum': sums valid values in the temporal dimension.
            Note if all batch row elements are invalid, the temporal dimension is
            pooled to 0 values.
        """
        super().__init__()
        assert method in ('max', 'avg', 'sum')
        self._method = method

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