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
import numpy as np
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_poi_fused_constant_pad_nd_0(in_ptr0, out_ptr0, xnumel, XBLOCK:
    tl.constexpr):
    xnumel = 2304
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex // 72 % 2
    x1 = xindex // 8 % 9
    x0 = xindex % 8
    x3 = xindex // 144
    x7 = xindex
    tmp0 = -1 + x2
    tmp1 = tl.full([1], 0, tl.int64)
    tmp2 = tmp0 >= tmp1
    tmp3 = -1 + x1
    tmp4 = tmp3 >= tmp1
    tmp5 = tmp2 & tmp4
    tmp6 = -1 + (-1 + x1) % 2
    tmp7 = tmp6 >= tmp1
    tmp8 = -1 + x0 % 2
    tmp9 = tmp8 >= tmp1
    tmp10 = tmp7 & tmp9
    tmp11 = tmp10 & tmp5
    tmp12 = tl.load(in_ptr0 + (4 * ((-1 + x1) // 2 % 4) + 16 * x3 + x0 // 2
        ), tmp11 & xmask, eviction_policy='evict_last', other=0.0)
    tmp13 = tl.full(tmp12.shape, 0.0, tmp12.dtype)
    tmp14 = tl.where(tmp5, tmp12, tmp13)
    tl.store(out_ptr0 + x7, tmp14, xmask)


@triton.jit
def triton_poi_fused_convolution_1(in_ptr0, out_ptr0, ynumel, xnumel,
    YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
    ynumel = 128
    xnumel = 8
    yoffset = tl.program_id(1) * YBLOCK
    yindex = yoffset + tl.arange(0, YBLOCK)[None, :]
    ymask = yindex < ynumel
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    x2 = xindex
    y0 = yindex % 8
    y1 = yindex // 8
    y3 = yindex
    tmp0 = tl.load(in_ptr0 + (y0 + 8 * x2 + 144 * y1), xmask & ymask,
        eviction_policy='evict_last')
    tl.store(out_ptr0 + (x2 + 8 * y3), tmp0, xmask & ymask)


@triton.jit
def triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_mul_sub_2(
    in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 1024
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x1 = xindex // 8 % 8
    x0 = xindex % 8
    x2 = xindex // 64
    x3 = xindex
    tmp0 = x1
    tmp1 = tmp0.to(tl.float32)
    tmp2 = 0.5
    tmp3 = tmp1 + tmp2
    tmp4 = 0.625
    tmp5 = tmp3 * tmp4
    tmp6 = tmp5 - tmp2
    tmp7 = 0.0
    tmp8 = triton_helpers.maximum(tmp6, tmp7)
    tmp9 = tmp8.to(tl.int32)
    tmp10 = tl.full([1], 1, tl.int64)
    tmp11 = tmp9 + tmp10
    tmp12 = tl.full([1], 4, tl.int64)
    tmp13 = triton_helpers.minimum(tmp11, tmp12)
    tmp14 = x0
    tmp15 = tmp14.to(tl.float32)
    tmp16 = tmp15 + tmp2
    tmp17 = tmp16 * tmp4
    tmp18 = tmp17 - tmp2
    tmp19 = triton_helpers.maximum(tmp18, tmp7)
    tmp20 = tmp19.to(tl.int32)
    tmp21 = tmp20 + tmp10
    tmp22 = triton_helpers.minimum(tmp21, tmp12)
    tmp23 = tl.load(in_ptr0 + (tmp22 + 5 * tmp13 + 25 * x2), xmask,
        eviction_policy='evict_last')
    tmp24 = tl.load(in_ptr0 + (tmp20 + 5 * tmp13 + 25 * x2), xmask,
        eviction_policy='evict_last')
    tmp25 = tmp23 - tmp24
    tmp26 = tmp20.to(tl.float32)
    tmp27 = tmp19 - tmp26
    tmp28 = triton_helpers.maximum(tmp27, tmp7)
    tmp29 = 1.0
    tmp30 = triton_helpers.minimum(tmp28, tmp29)
    tmp31 = tmp25 * tmp30
    tmp32 = tl.load(in_ptr0 + (tmp20 + 5 * tmp9 + 25 * x2), xmask,
        eviction_policy='evict_last')
    tmp33 = tl.load(in_ptr0 + (tmp22 + 5 * tmp9 + 25 * x2), xmask,
        eviction_policy='evict_last')
    tmp34 = tmp33 - tmp32
    tmp35 = tmp34 * tmp30
    tmp36 = tmp32 + tmp35
    tmp37 = tmp24 + tmp31
    tmp38 = tmp37 - tmp36
    tmp39 = tmp9.to(tl.float32)
    tmp40 = tmp8 - tmp39
    tmp41 = triton_helpers.maximum(tmp40, tmp7)
    tmp42 = triton_helpers.minimum(tmp41, tmp29)
    tmp43 = tmp38 * tmp42
    tmp44 = tmp36 + tmp43
    tl.store(in_out_ptr0 + x3, tmp44, xmask)


def call(args):
    arg0_1, arg1_1 = args
    args.clear()
    assert_size_stride(arg0_1, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(arg1_1, (1, 1, 4, 4), (16, 16, 4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((16, 2, 9, 8), (144, 72, 8, 1), torch.float32
            )
        get_raw_stream(0)
        triton_poi_fused_constant_pad_nd_0[grid(2304)](arg0_1, buf0, 2304,
            XBLOCK=128, num_warps=4, num_stages=1)
        del arg0_1
        buf1 = empty_strided_cuda((16, 1, 8, 8), (64, 1, 8, 1), torch.float32)
        triton_poi_fused_convolution_1[grid(128, 8)](buf0, buf1, 128, 8,
            XBLOCK=8, YBLOCK=128, num_warps=4, num_stages=1)
        del buf0
        buf2 = extern_kernels.convolution(buf1, arg1_1, stride=(1, 1),
            padding=(0, 0), dilation=(1, 1), transposed=False,
            output_padding=(0, 0), groups=1, bias=None)
        assert_size_stride(buf2, (16, 1, 5, 5), (25, 1, 5, 1))
        del arg1_1
        buf3 = reinterpret_tensor(buf1, (16, 1, 8, 8), (64, 1024, 8, 1), 0)
        del buf1
        buf5 = buf3
        del buf3
        buf6 = reinterpret_tensor(buf5, (16, 1, 8, 8), (64, 1, 8, 1), 0)
        del buf5
        triton_poi_fused__to_copy__unsafe_index_add_arange_clamp_mul_sub_2[grid
            (1024)](buf6, buf2, 1024, XBLOCK=256, num_warps=4, num_stages=1)
        del buf2
    return reinterpret_tensor(buf6, (4, 4, 8, 8), (256, 64, 8, 1), 0),


def _setup_kernel(k):
    k = np.asarray(k, dtype=np.float32)
    if k.ndim == 1:
        k = np.outer(k, k)
    k /= np.sum(k)
    assert k.ndim == 2
    assert k.shape[0] == k.shape[1]
    return k


class Upsample2dNew(nn.Module):

    def __init__(self, opts, k=[1, 3, 3, 1], factor=2, down=1, gain=1):
        """
            Upsample2d method in G_synthesis_stylegan2.
        :param k: FIR filter of the shape `[firH, firW]` or `[firN]` (separable).
                  The default is `[1] * factor`, which corresponds to average pooling.
        :param factor: Integer downsampling factor (default: 2).
        :param gain:   Scaling factor for signal magnitude (default: 1.0).

            Returns: Tensor of the shape `[N, C, H // factor, W // factor]`
        """
        super().__init__()
        assert isinstance(factor, int
            ) and factor >= 1, 'factor must be larger than 1! (default: 2)'
        self.gain = gain
        self.factor = factor
        self.opts = opts
        self.k = _setup_kernel(k) * (self.gain * factor ** 2)
        self.k = torch.FloatTensor(self.k).unsqueeze(0).unsqueeze(0)
        self.k = torch.flip(self.k, [2, 3])
        self.k = nn.Parameter(self.k, requires_grad=False)
        self.p = self.k.shape[0] - self.factor
        self.padx0, self.pady0 = (self.p + 1) // 2 + factor - 1, (self.p + 1
            ) // 2 + factor - 1
        self.padx1, self.pady1 = self.p // 2, self.p // 2
        self.kernelH, self.kernelW = self.k.shape[2:]
        self.down = down

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


Measured latency_ms: 0.026652