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 libdevice
import math
import numpy as np
from torch import nn
import torch.nn.functional as F
import torch.utils.data
import torch.nn.functional
from typing import List
from typing import Optional
import torch.autograd
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_mul_0(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
    tmp0 = tl.load(in_ptr0 + x0, xmask)
    tmp1 = 0.5
    tmp2 = tmp0 * tmp1
    tl.store(out_ptr0 + x0, tmp2, xmask)


@triton.jit
def triton_per_fused_add_mul_pow_rsqrt_sum_1(in_out_ptr0, in_ptr0, in_ptr1,
    out_ptr0, xnumel, rnumel, XBLOCK: tl.constexpr):
    xnumel = 16
    rnumel = 36
    RBLOCK: tl.constexpr = 64
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:, None]
    xmask = xindex < xnumel
    rindex = tl.arange(0, RBLOCK)[None, :]
    rmask = rindex < rnumel
    r5 = rindex
    x0 = xindex % 4
    r3 = rindex // 9
    x1 = xindex // 4
    x4 = xindex
    tmp0 = tl.load(in_ptr0 + (r5 + 36 * x0), rmask & xmask, eviction_policy
        ='evict_last', other=0.0)
    tmp3 = tl.load(in_ptr1 + (r3 + 4 * x1), rmask & xmask, eviction_policy=
        'evict_last', other=0.0)
    tmp1 = 0.16666666666666666
    tmp2 = tmp0 * tmp1
    tmp4 = tmp2 * tmp3
    tmp5 = tmp4 * tmp4
    tmp6 = tl.broadcast_to(tmp5, [XBLOCK, RBLOCK])
    tmp8 = tl.where(rmask & xmask, tmp6, 0)
    tmp9 = tl.sum(tmp8, 1)[:, None]
    tmp10 = 1e-08
    tmp11 = tmp9 + tmp10
    tmp12 = libdevice.rsqrt(tmp11)
    tmp13 = tmp4 * tmp12
    tl.debug_barrier()
    tl.store(in_out_ptr0 + x4, tmp12, xmask)
    tl.store(out_ptr0 + (r5 + 36 * x4), tmp13, rmask & xmask)


@triton.jit
def triton_poi_fused_add_leaky_relu_leaky_relu_backward_mul_2(in_out_ptr0,
    in_ptr0, in_ptr1, in_ptr2, out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x4 = xindex
    x0 = xindex % 4
    x2 = xindex // 16 % 4
    tmp0 = tl.load(in_out_ptr0 + x4, xmask)
    tmp1 = tl.load(in_ptr0 + 0)
    tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
    tmp3 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr2 + x2, xmask, eviction_policy='evict_last')
    tmp4 = tmp2 * tmp3
    tmp5 = tmp0 + tmp4
    tmp7 = tmp5 + tmp6
    tmp8 = 0.0
    tmp9 = tmp7 > tmp8
    tmp10 = 0.2
    tmp11 = tmp7 * tmp10
    tmp12 = tl.where(tmp9, tmp7, tmp11)
    tmp13 = tmp12 > tmp8
    tl.store(in_out_ptr0 + x4, tmp12, xmask)
    tl.store(out_ptr0 + x4, tmp13, xmask)


@triton.jit
def triton_poi_fused_add_leaky_relu_mul_3(in_out_ptr0, in_ptr0, in_ptr1,
    in_ptr2, xnumel, XBLOCK: tl.constexpr):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x4 = xindex
    x0 = xindex % 4
    x2 = xindex // 16 % 4
    tmp0 = tl.load(in_out_ptr0 + x4, xmask)
    tmp1 = tl.load(in_ptr0 + 0)
    tmp2 = tl.broadcast_to(tmp1, [XBLOCK])
    tmp3 = tl.load(in_ptr1 + (4 + x0), xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr2 + x2, xmask, eviction_policy='evict_last')
    tmp4 = tmp2 * tmp3
    tmp5 = tmp0 + tmp4
    tmp7 = tmp5 + tmp6
    tmp8 = 0.0
    tmp9 = tmp7 > tmp8
    tmp10 = 0.2
    tmp11 = tmp7 * tmp10
    tmp12 = tl.where(tmp9, tmp7, tmp11)
    tl.store(in_out_ptr0 + x4, tmp12, xmask)


@triton.jit
def triton_poi_fused_mul_4(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.
    constexpr):
    xnumel = 48
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex % 12
    x0 = xindex % 4
    x2 = xindex // 12
    x4 = xindex
    tmp0 = tl.load(in_ptr0 + x3, xmask, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr1 + (x0 + 4 * x2), xmask, eviction_policy='evict_last'
        )
    tmp1 = 0.5
    tmp2 = tmp0 * tmp1
    tmp4 = tmp2 * tmp3
    tl.store(out_ptr0 + x4, tmp4, xmask)


@triton.jit
def triton_poi_fused_add_leaky_relu_leaky_relu_backward_5(in_out_ptr0,
    in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 192
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex
    x1 = xindex // 16 % 3
    tmp0 = tl.load(in_out_ptr0 + x3, xmask)
    tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp3 = 0.0
    tmp4 = tmp2 > tmp3
    tmp5 = 0.2
    tmp6 = tmp2 * tmp5
    tmp7 = tl.where(tmp4, tmp2, tmp6)
    tmp8 = tmp7 > tmp3
    tl.store(in_out_ptr0 + x3, tmp7, xmask)
    tl.store(out_ptr0 + x3, tmp8, xmask)


def call(args):
    (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
        primals_7, primals_8, primals_9, primals_10, primals_11, primals_12,
        primals_13, primals_14, primals_15, primals_16, primals_17) = args
    args.clear()
    assert_size_stride(primals_1, (4, 4), (4, 1))
    assert_size_stride(primals_2, (4, 4), (4, 1))
    assert_size_stride(primals_3, (4,), (1,))
    assert_size_stride(primals_4, (4, 4), (4, 1))
    assert_size_stride(primals_5, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_6, (4, 4, 3, 3), (36, 9, 3, 1))
    assert_size_stride(primals_7, (1,), (1,))
    assert_size_stride(primals_8, (4,), (1,))
    assert_size_stride(primals_9, (4, 4), (4, 1))
    assert_size_stride(primals_10, (4,), (1,))
    assert_size_stride(primals_11, (4, 4, 3, 3), (36, 9, 3, 1))
    assert_size_stride(primals_12, (1,), (1,))
    assert_size_stride(primals_13, (4,), (1,))
    assert_size_stride(primals_14, (4, 4), (4, 1))
    assert_size_stride(primals_15, (4,), (1,))
    assert_size_stride(primals_16, (3, 4, 1, 1), (4, 1, 1, 1))
    assert_size_stride(primals_17, (3,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_mul_0[grid(16)](primals_2, buf0, 16, XBLOCK=16,
            num_warps=1, num_stages=1)
        del primals_2
        buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        extern_kernels.addmm(primals_3, primals_4, reinterpret_tensor(buf0,
            (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf1)
        del primals_3
        buf2 = reinterpret_tensor(buf0, (4, 4, 1, 1, 1), (4, 1, 16, 16, 16), 0)
        del buf0
        buf3 = reinterpret_tensor(buf2, (4, 4, 1, 1, 1), (4, 1, 1, 1, 1), 0)
        del buf2
        buf4 = empty_strided_cuda((4, 4, 4, 3, 3), (144, 36, 9, 3, 1),
            torch.float32)
        triton_per_fused_add_mul_pow_rsqrt_sum_1[grid(16)](buf3, primals_6,
            buf1, buf4, 16, 36, XBLOCK=1, num_warps=2, num_stages=1)
        buf5 = extern_kernels.convolution(reinterpret_tensor(primals_5, (1,
            16, 4, 4), (256, 16, 4, 1), 0), reinterpret_tensor(buf4, (16, 4,
            3, 3), (36, 9, 3, 1), 0), stride=(1, 1), padding=(1, 1),
            dilation=(1, 1), transposed=False, output_padding=(0, 0),
            groups=4, bias=None)
        assert_size_stride(buf5, (1, 16, 4, 4), (256, 16, 4, 1))
        buf6 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        triton_poi_fused_mul_0[grid(16)](primals_9, buf6, 16, XBLOCK=16,
            num_warps=1, num_stages=1)
        del primals_9
        buf7 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        extern_kernels.addmm(primals_10, primals_4, reinterpret_tensor(buf6,
            (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf7)
        del primals_10
        buf8 = reinterpret_tensor(buf6, (4, 4, 1, 1, 1), (4, 1, 16, 16, 16), 0)
        del buf6
        buf9 = reinterpret_tensor(buf8, (4, 4, 1, 1, 1), (4, 1, 1, 1, 1), 0)
        del buf8
        buf10 = empty_strided_cuda((4, 4, 4, 3, 3), (144, 36, 9, 3, 1),
            torch.float32)
        triton_per_fused_add_mul_pow_rsqrt_sum_1[grid(16)](buf9, primals_11,
            buf7, buf10, 16, 36, XBLOCK=1, num_warps=2, num_stages=1)
        buf11 = reinterpret_tensor(buf5, (4, 4, 4, 4), (64, 16, 4, 1), 0)
        del buf5
        buf20 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.bool)
        triton_poi_fused_add_leaky_relu_leaky_relu_backward_mul_2[grid(256)](
            buf11, primals_7, primals_1, primals_8, buf20, 256, XBLOCK=128,
            num_warps=4, num_stages=1)
        del primals_7
        del primals_8
        buf12 = extern_kernels.convolution(reinterpret_tensor(buf11, (1, 16,
            4, 4), (0, 16, 4, 1), 0), reinterpret_tensor(buf10, (16, 4, 3, 
            3), (36, 9, 3, 1), 0), stride=(1, 1), padding=(1, 1), dilation=
            (1, 1), transposed=False, output_padding=(0, 0), groups=4, bias
            =None)
        assert_size_stride(buf12, (1, 16, 4, 4), (256, 16, 4, 1))
        buf13 = reinterpret_tensor(buf12, (4, 4, 4, 4), (64, 16, 4, 1), 0)
        del buf12
        triton_poi_fused_add_leaky_relu_mul_3[grid(256)](buf13, primals_12,
            primals_1, primals_13, 256, XBLOCK=128, num_warps=4, num_stages=1)
        del primals_12
        del primals_13
        buf14 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        triton_poi_fused_mul_0[grid(16)](primals_14, buf14, 16, XBLOCK=16,
            num_warps=1, num_stages=1)
        del primals_14
        buf15 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        extern_kernels.addmm(primals_15, primals_4, reinterpret_tensor(
            buf14, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf15)
        del buf14
        del primals_15
        buf16 = empty_strided_cuda((4, 3, 4, 1, 1), (12, 4, 1, 1, 1), torch
            .float32)
        triton_poi_fused_mul_4[grid(48)](primals_16, buf15, buf16, 48,
            XBLOCK=64, num_warps=1, num_stages=1)
        buf17 = extern_kernels.convolution(reinterpret_tensor(buf13, (1, 16,
            4, 4), (256, 16, 4, 1), 0), reinterpret_tensor(buf16, (12, 4, 1,
            1), (4, 1, 0, 0), 0), stride=(1, 1), padding=(0, 0), dilation=(
            1, 1), transposed=False, output_padding=(0, 0), groups=4, bias=None
            )
        assert_size_stride(buf17, (1, 12, 4, 4), (192, 16, 4, 1))
        buf18 = reinterpret_tensor(buf17, (4, 3, 4, 4), (48, 16, 4, 1), 0)
        del buf17
        buf19 = empty_strided_cuda((4, 3, 4, 4), (48, 16, 4, 1), torch.bool)
        triton_poi_fused_add_leaky_relu_leaky_relu_backward_5[grid(192)](buf18,
            primals_17, buf19, 192, XBLOCK=128, num_warps=4, num_stages=1)
        del primals_17
    return (buf13, buf18, primals_4, primals_6, primals_11, primals_16,
        reinterpret_tensor(primals_1, (4,), (1,), 0), buf1, buf3,
        reinterpret_tensor(primals_5, (1, 16, 4, 4), (256, 16, 4, 1), 0),
        reinterpret_tensor(buf4, (16, 4, 3, 3), (36, 9, 3, 1), 0),
        reinterpret_tensor(primals_1, (4,), (1,), 4), buf7, buf9,
        reinterpret_tensor(buf10, (16, 4, 3, 3), (36, 9, 3, 1), 0),
        reinterpret_tensor(buf11, (1, 16, 4, 4), (256, 16, 4, 1), 0), buf13,
        buf15, reinterpret_tensor(buf16, (12, 4, 1, 1), (4, 1, 1, 1), 0),
        buf19, buf20)


class EqualizedWeight(nn.Module):
    """
    <a id="equalized_weight"></a>
    ## Learning-rate Equalized Weights Parameter

    This is based on equalized learning rate introduced in the Progressive GAN paper.
    Instead of initializing weights at $\\mathcal{N}(0,c)$ they initialize weights
    to $\\mathcal{N}(0, 1)$ and then multiply them by $c$ when using it.
    $$w_i = c \\hat{w}_i$$

    The gradients on stored parameters $\\hat{w}$ get multiplied by $c$ but this doesn't have
    an affect since optimizers such as Adam normalize them by a running mean of the squared gradients.

    The optimizer updates on $\\hat{w}$ are proportionate to the learning rate $\\lambda$.
    But the effective weights $w$ get updated proportionately to $c \\lambda$.
    Without equalized learning rate, the effective weights will get updated proportionately to just $\\lambda$.

    So we are effectively scaling the learning rate by $c$ for these weight parameters.
    """

    def __init__(self, shape: 'List[int]'):
        """
        * `shape` is the shape of the weight parameter
        """
        super().__init__()
        self.c = 1 / math.sqrt(np.prod(shape[1:]))
        self.weight = nn.Parameter(torch.randn(shape))

    def forward(self):
        return self.weight * self.c


class EqualizedLinear(nn.Module):
    """
    <a id="equalized_linear"></a>
    ## Learning-rate Equalized Linear Layer

    This uses [learning-rate equalized weights]($equalized_weights) for a linear layer.
    """

    def __init__(self, in_features: 'int', out_features: 'int', bias:
        'float'=0.0):
        """
        * `in_features` is the number of features in the input feature map
        * `out_features` is the number of features in the output feature map
        * `bias` is the bias initialization constant
        """
        super().__init__()
        self.weight = EqualizedWeight([out_features, in_features])
        self.bias = nn.Parameter(torch.ones(out_features) * bias)

    def forward(self, x: 'torch.Tensor'):
        return F.linear(x, self.weight(), bias=self.bias)


class Conv2dWeightModulate(nn.Module):
    """
    ### Convolution with Weight Modulation and Demodulation

    This layer scales the convolution weights by the style vector and demodulates by normalizing it.
    """

    def __init__(self, in_features: 'int', out_features: 'int', kernel_size:
        'int', demodulate: 'float'=True, eps: 'float'=1e-08):
        """
        * `in_features` is the number of features in the input feature map
        * `out_features` is the number of features in the output feature map
        * `kernel_size` is the size of the convolution kernel
        * `demodulate` is flag whether to normalize weights by its standard deviation
        * `eps` is the $\\epsilon$ for normalizing
        """
        super().__init__()
        self.out_features = out_features
        self.demodulate = demodulate
        self.padding = (kernel_size - 1) // 2
        self.weight = EqualizedWeight([out_features, in_features,
            kernel_size, kernel_size])
        self.eps = eps

    def forward(self, x: 'torch.Tensor', s: 'torch.Tensor'):
        """
        * `x` is the input feature map of shape `[batch_size, in_features, height, width]`
        * `s` is style based scaling tensor of shape `[batch_size, in_features]`
        """
        b, _, h, w = x.shape
        s = s[:, None, :, None, None]
        weights = self.weight()[None, :, :, :, :]
        weights = weights * s
        if self.demodulate:
            sigma_inv = torch.rsqrt((weights ** 2).sum(dim=(2, 3, 4),
                keepdim=True) + self.eps)
            weights = weights * sigma_inv
        x = x.reshape(1, -1, h, w)
        _, _, *ws = weights.shape
        weights = weights.reshape(b * self.out_features, *ws)
        x = F.conv2d(x, weights, padding=self.padding, groups=b)
        return x.reshape(-1, self.out_features, h, w)


class StyleBlock(nn.Module):
    """
    <a id="style_block"></a>
    ### Style Block

    ![Style block](style_block.svg)

    *<small>$A$ denotes a linear layer.
    $B$ denotes a broadcast and scaling operation (noise is single channel).</small>*

    Style block has a weight modulation convolution layer.
    """

    def __init__(self, d_latent: 'int', in_features: 'int', out_features: 'int'
        ):
        """
        * `d_latent` is the dimensionality of $w$
        * `in_features` is the number of features in the input feature map
        * `out_features` is the number of features in the output feature map
        """
        super().__init__()
        self.to_style = EqualizedLinear(d_latent, in_features, bias=1.0)
        self.conv = Conv2dWeightModulate(in_features, out_features,
            kernel_size=3)
        self.scale_noise = nn.Parameter(torch.zeros(1))
        self.bias = nn.Parameter(torch.zeros(out_features))
        self.activation = nn.LeakyReLU(0.2, True)

    def forward(self, x: 'torch.Tensor', w: 'torch.Tensor', noise:
        'Optional[torch.Tensor]'):
        """
        * `x` is the input feature map of shape `[batch_size, in_features, height, width]`
        * `w` is $w$ with shape `[batch_size, d_latent]`
        * `noise` is a tensor of shape `[batch_size, 1, height, width]`
        """
        s = self.to_style(w)
        x = self.conv(x, s)
        if noise is not None:
            x = x + self.scale_noise[None, :, None, None] * noise
        return self.activation(x + self.bias[None, :, None, None])


class ToRGB(nn.Module):
    """
    <a id="to_rgb"></a>
    ### To RGB

    ![To RGB](to_rgb.svg)

    *<small>$A$ denotes a linear layer.</small>*

    Generates an RGB image from a feature map using $1 	imes 1$ convolution.
    """

    def __init__(self, d_latent: 'int', features: 'int'):
        """
        * `d_latent` is the dimensionality of $w$
        * `features` is the number of features in the feature map
        """
        super().__init__()
        self.to_style = EqualizedLinear(d_latent, features, bias=1.0)
        self.conv = Conv2dWeightModulate(features, 3, kernel_size=1,
            demodulate=False)
        self.bias = nn.Parameter(torch.zeros(3))
        self.activation = nn.LeakyReLU(0.2, True)

    def forward(self, x: 'torch.Tensor', w: 'torch.Tensor'):
        """
        * `x` is the input feature map of shape `[batch_size, in_features, height, width]`
        * `w` is $w$ with shape `[batch_size, d_latent]`
        """
        style = self.to_style(w)
        x = self.conv(x, style)
        return self.activation(x + self.bias[None, :, None, None])


class GeneratorBlockNew(nn.Module):
    """
    <a id="generator_block"></a>
    ### Generator Block

    ![Generator block](generator_block.svg)

    *<small>$A$ denotes a linear layer.
    $B$ denotes a broadcast and scaling operation (noise is a single channel).
    [*toRGB*](#to_rgb) also has a style modulation which is not shown in the diagram to keep it simple.</small>*

    The generator block consists of two [style blocks](#style_block) ($3 	imes 3$ convolutions with style modulation)
    and an RGB output.
    """

    def __init__(self, d_latent: 'int', in_features: 'int', out_features: 'int'
        ):
        """
        * `d_latent` is the dimensionality of $w$
        * `in_features` is the number of features in the input feature map
        * `out_features` is the number of features in the output feature map
        """
        super().__init__()
        self.style_block1 = StyleBlock(d_latent, in_features, out_features)
        self.style_block2 = StyleBlock(d_latent, out_features, out_features)
        self.to_rgb = ToRGB(d_latent, out_features)

    def forward(self, input_0, input_1, input_2):
        primals_7 = self.style_block1.scale_noise
        primals_3 = self.style_block1.bias
        primals_8 = self.style_block1.to_style.bias
        primals_1 = self.style_block1.to_style.weight.weight
        primals_6 = self.style_block1.conv.weight.weight
        primals_12 = self.style_block2.scale_noise
        primals_10 = self.style_block2.bias
        primals_13 = self.style_block2.to_style.bias
        primals_2 = self.style_block2.to_style.weight.weight
        primals_11 = self.style_block2.conv.weight.weight
        primals_17 = self.to_rgb.bias
        primals_15 = self.to_rgb.to_style.bias
        primals_4 = self.to_rgb.to_style.weight.weight
        primals_16 = self.to_rgb.conv.weight.weight
        primals_5 = input_0
        primals_9 = input_1
        primals_14 = input_2
        output = call([primals_1, primals_2, primals_3, primals_4,
            primals_5, primals_6, primals_7, primals_8, primals_9,
            primals_10, primals_11, primals_12, primals_13, primals_14,
            primals_15, primals_16, primals_17])
        return output[0], output[1]


Measured latency_ms: 0.035359