import torch
import warnings
import torch.nn as nn
import torch.nn.functional as F
from torch import optim as optim


class LayerNorm(nn.Module):
    """ LayerNorm that supports two data formats: channels_last (default) or channels_first. 
    The ordering of the dimensions in the inputs. channels_last corresponds to inputs with 
    shape (batch_size, height, width, channels) while channels_first corresponds to inputs 
    with shape (batch_size, channels, height, width).
    """

    def __init__(self, normalized_shape, eps=1e-06, data_format='channels_last'
        ):
        super().__init__()
        self.weight = nn.Parameter(torch.ones(normalized_shape))
        self.bias = nn.Parameter(torch.zeros(normalized_shape))
        self.eps = eps
        self.data_format = data_format
        if self.data_format not in ['channels_last', 'channels_first']:
            raise NotImplementedError
        self.normalized_shape = normalized_shape,

    def forward(self, x):
        if self.data_format == 'channels_last':
            return F.layer_norm(x, self.normalized_shape, self.weight, self
                .bias, self.eps)
        elif self.data_format == 'channels_first':
            u = x.mean(1, keepdim=True)
            s = (x - u).pow(2).mean(1, keepdim=True)
            x = (x - u) / torch.sqrt(s + self.eps)
            x = self.weight[:, None, None] * x + self.bias[:, None, None]
            return x


class Minimum(nn.Module):

    def forward(self, x, y):
        return torch.minimum(x, y)


class NextMinBlock(nn.Module):
    """ ConvNeXt Block. There are two equivalent implementations:
    (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)
    (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back
    We use (2) as we find it slightly faster in PyTorch

    Args:
        dim (int): Number of input channels.
        kernel_size (int): dws kernel_size
        drop_path (float): Stochastic depth rate. Default: 0.0
        layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
    """

    def __init__(self, dim, drop_path=0.0, layer_scale_init_value=1e-06,
        kernel_size=7):
        super().__init__()
        if kernel_size != 7:
            warnings.warn(f'Using kernel_size: {kernel_size}')
        self.dwconv_left = nn.Conv2d(dim, dim, kernel_size=kernel_size,
            padding=kernel_size // 2, groups=dim)
        self.dwconv_right = nn.Conv2d(dim, dim, kernel_size=kernel_size,
            padding=kernel_size // 2, groups=dim)
        self.instance_norm_relu = nn.Sequential(nn.InstanceNorm2d(dim), nn.
            ReLU())
        self.min = Minimum()
        self.norm = LayerNorm(dim, eps=1e-06)
        self.pwconv1 = nn.Linear(dim, 4 * dim)
        self.act = nn.GELU()
        self.pwconv2 = nn.Linear(4 * dim, dim)
        self.gamma = nn.Parameter(layer_scale_init_value * torch.ones(dim),
            requires_grad=True) if layer_scale_init_value > 0 else None
        self.drop_path = DropPath(drop_path
            ) if drop_path > 0.0 else nn.Identity()

    def forward(self, x):
        input = x
        x_left = self.dwconv_left(x)
        x_right = self.dwconv_right(x)
        x_left = self.instance_norm_relu(x_left)
        x_right = self.instance_norm_relu(x_right)
        x = self.min(x_left, x_right)
        x = x.permute(0, 2, 3, 1)
        x = self.norm(x)
        x = self.pwconv1(x)
        x = self.act(x)
        x = self.pwconv2(x)
        if self.gamma is not None:
            x = self.gamma * x
        x = x.permute(0, 3, 1, 2)
        x = input + self.drop_path(x)
        return x


class Abs(nn.Module):

    def forward(self, x):
        return torch.abs(x)


class NextMinMinusAbsBlockNoNorm(NextMinBlock):

    def __init__(self, dim, drop_path=0.0, layer_scale_init_value=1e-06,
        kernel_size=7):
        super().__init__(dim, drop_path=drop_path, layer_scale_init_value=
            layer_scale_init_value, kernel_size=kernel_size)
        self.lambda_ = 2.0
        self.abs = Abs()
        self.instance_norm_relu = nn.Sequential(nn.ReLU())

    def forward(self, x):
        input = x
        x_left = self.dwconv_left(x)
        x_right = self.dwconv_right(x)
        x_left = self.instance_norm_relu(x_left)
        x_right = self.instance_norm_relu(x_right)
        x = self.lambda_ * self.min(x_left, x_right) - self.abs(x_left -
            x_right)
        x = x.permute(0, 2, 3, 1)
        x = self.norm(x)
        x = self.pwconv1(x)
        x = self.act(x)
        x = self.pwconv2(x)
        if self.gamma is not None:
            x = self.gamma * x
        x = x.permute(0, 3, 1, 2)
        x = input + self.drop_path(x)
        return x


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


def get_init_inputs():
    return [[], {'dim': 4}]

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, math as tl_math
import warnings
import torch.nn as nn
import torch.nn.functional as F
from torch import optim as optim
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_convolution_0(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl
    .constexpr):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x3 = xindex
    x1 = xindex // 16 % 4
    tmp0 = tl.load(in_out_ptr0 + x3, xmask)
    tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tl.store(in_out_ptr0 + x3, tmp2, xmask)


@triton.jit
def triton_poi_fused_native_layer_norm_1(in_ptr0, in_ptr1, out_ptr0,
    out_ptr1, xnumel, XBLOCK: tl.constexpr):
    xnumel = 64
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 16
    x1 = xindex // 16
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
    tmp3 = tl.load(in_ptr1 + (x0 + 64 * x1), xmask)
    tmp11 = tl.load(in_ptr0 + (16 + x0 + 64 * x1), xmask)
    tmp13 = tl.load(in_ptr1 + (16 + x0 + 64 * x1), xmask)
    tmp21 = tl.load(in_ptr0 + (32 + x0 + 64 * x1), xmask)
    tmp23 = tl.load(in_ptr1 + (32 + x0 + 64 * x1), xmask)
    tmp31 = tl.load(in_ptr0 + (48 + x0 + 64 * x1), xmask)
    tmp33 = tl.load(in_ptr1 + (48 + x0 + 64 * x1), xmask)
    tmp1 = tl.full([1], 0, tl.int32)
    tmp2 = triton_helpers.maximum(tmp1, tmp0)
    tmp4 = triton_helpers.maximum(tmp1, tmp3)
    tmp5 = triton_helpers.minimum(tmp2, tmp4)
    tmp6 = 2.0
    tmp7 = tmp5 * tmp6
    tmp8 = tmp2 - tmp4
    tmp9 = tl_math.abs(tmp8)
    tmp10 = tmp7 - tmp9
    tmp12 = triton_helpers.maximum(tmp1, tmp11)
    tmp14 = triton_helpers.maximum(tmp1, tmp13)
    tmp15 = triton_helpers.minimum(tmp12, tmp14)
    tmp16 = tmp15 * tmp6
    tmp17 = tmp12 - tmp14
    tmp18 = tl_math.abs(tmp17)
    tmp19 = tmp16 - tmp18
    tmp20 = tmp10 + tmp19
    tmp22 = triton_helpers.maximum(tmp1, tmp21)
    tmp24 = triton_helpers.maximum(tmp1, tmp23)
    tmp25 = triton_helpers.minimum(tmp22, tmp24)
    tmp26 = tmp25 * tmp6
    tmp27 = tmp22 - tmp24
    tmp28 = tl_math.abs(tmp27)
    tmp29 = tmp26 - tmp28
    tmp30 = tmp20 + tmp29
    tmp32 = triton_helpers.maximum(tmp1, tmp31)
    tmp34 = triton_helpers.maximum(tmp1, tmp33)
    tmp35 = triton_helpers.minimum(tmp32, tmp34)
    tmp36 = tmp35 * tmp6
    tmp37 = tmp32 - tmp34
    tmp38 = tl_math.abs(tmp37)
    tmp39 = tmp36 - tmp38
    tmp40 = tmp30 + tmp39
    tmp41 = 4.0
    tmp42 = tmp40 / tmp41
    tmp43 = tmp10 - tmp42
    tmp44 = tmp43 * tmp43
    tmp45 = tmp19 - tmp42
    tmp46 = tmp45 * tmp45
    tmp47 = tmp44 + tmp46
    tmp48 = tmp29 - tmp42
    tmp49 = tmp48 * tmp48
    tmp50 = tmp47 + tmp49
    tmp51 = tmp39 - tmp42
    tmp52 = tmp51 * tmp51
    tmp53 = tmp50 + tmp52
    tmp54 = tmp53 / tmp41
    tl.store(out_ptr0 + x2, tmp42, xmask)
    tl.store(out_ptr1 + x2, tmp54, xmask)


@triton.jit
def triton_poi_fused_native_layer_norm_2(in_ptr0, in_ptr1, in_ptr2, in_ptr3,
    in_ptr4, in_ptr5, out_ptr0, ynumel, xnumel, YBLOCK: tl.constexpr,
    XBLOCK: tl.constexpr):
    ynumel = 16
    xnumel = 16
    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
    y3 = yindex
    y1 = yindex // 4
    y0 = yindex % 4
    tmp0 = tl.load(in_ptr0 + (x2 + 16 * y3), xmask & ymask)
    tmp3 = tl.load(in_ptr1 + (x2 + 16 * y3), xmask & ymask)
    tmp11 = tl.load(in_ptr2 + (x2 + 16 * y1), xmask & ymask,
        eviction_policy='evict_last')
    tmp13 = tl.load(in_ptr3 + (x2 + 16 * y1), xmask & ymask,
        eviction_policy='evict_last')
    tmp18 = tl.load(in_ptr4 + y0, ymask, eviction_policy='evict_last')
    tmp20 = tl.load(in_ptr5 + y0, ymask, eviction_policy='evict_last')
    tmp1 = tl.full([1, 1], 0, tl.int32)
    tmp2 = triton_helpers.maximum(tmp1, tmp0)
    tmp4 = triton_helpers.maximum(tmp1, tmp3)
    tmp5 = triton_helpers.minimum(tmp2, tmp4)
    tmp6 = 2.0
    tmp7 = tmp5 * tmp6
    tmp8 = tmp2 - tmp4
    tmp9 = tl_math.abs(tmp8)
    tmp10 = tmp7 - tmp9
    tmp12 = tmp10 - tmp11
    tmp14 = 1e-06
    tmp15 = tmp13 + tmp14
    tmp16 = libdevice.rsqrt(tmp15)
    tmp17 = tmp12 * tmp16
    tmp19 = tmp17 * tmp18
    tmp21 = tmp19 + tmp20
    tl.store(out_ptr0 + (y0 + 4 * x2 + 64 * y1), tmp21, xmask & ymask)


@triton.jit
def triton_poi_fused_gelu_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 1024
    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
    tmp3 = 0.7071067811865476
    tmp4 = tmp0 * tmp3
    tmp5 = libdevice.erf(tmp4)
    tmp6 = 1.0
    tmp7 = tmp5 + tmp6
    tmp8 = tmp2 * tmp7
    tl.store(out_ptr0 + x0, tmp8, xmask)


@triton.jit
def triton_poi_fused_add_4(in_ptr0, in_ptr1, in_ptr2, out_ptr0, ynumel,
    xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
    ynumel = 16
    xnumel = 16
    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
    y3 = yindex
    y0 = yindex % 4
    y1 = yindex // 4
    tmp0 = tl.load(in_ptr0 + (x2 + 16 * y3), xmask & ymask)
    tmp1 = tl.load(in_ptr1 + y0, ymask, eviction_policy='evict_last')
    tmp2 = tl.load(in_ptr2 + (y0 + 4 * x2 + 64 * y1), xmask & ymask)
    tmp3 = tmp1 * tmp2
    tmp4 = tmp0 + tmp3
    tl.store(out_ptr0 + (x2 + 16 * y3), tmp4, xmask & ymask)


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
        ) = args
    args.clear()
    assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_2, (4, 1, 7, 7), (49, 49, 7, 1))
    assert_size_stride(primals_3, (4,), (1,))
    assert_size_stride(primals_4, (4, 1, 7, 7), (49, 49, 7, 1))
    assert_size_stride(primals_5, (4,), (1,))
    assert_size_stride(primals_6, (4,), (1,))
    assert_size_stride(primals_7, (4,), (1,))
    assert_size_stride(primals_8, (16, 4), (4, 1))
    assert_size_stride(primals_9, (16,), (1,))
    assert_size_stride(primals_10, (4, 16), (16, 1))
    assert_size_stride(primals_11, (4,), (1,))
    assert_size_stride(primals_12, (4,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = extern_kernels.convolution(primals_1, primals_2, stride=(1, 
            1), padding=(3, 3), dilation=(1, 1), transposed=False,
            output_padding=(0, 0), groups=4, bias=None)
        assert_size_stride(buf0, (4, 4, 4, 4), (64, 16, 4, 1))
        buf1 = buf0
        del buf0
        get_raw_stream(0)
        triton_poi_fused_convolution_0[grid(256)](buf1, primals_3, 256,
            XBLOCK=256, num_warps=4, num_stages=1)
        del primals_3
        buf2 = extern_kernels.convolution(primals_1, primals_4, stride=(1, 
            1), padding=(3, 3), dilation=(1, 1), transposed=False,
            output_padding=(0, 0), groups=4, bias=None)
        assert_size_stride(buf2, (4, 4, 4, 4), (64, 16, 4, 1))
        buf3 = buf2
        del buf2
        triton_poi_fused_convolution_0[grid(256)](buf3, primals_5, 256,
            XBLOCK=256, num_warps=4, num_stages=1)
        del primals_5
        buf4 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
        buf5 = empty_strided_cuda((4, 4, 4, 1), (16, 4, 1, 64), torch.float32)
        triton_poi_fused_native_layer_norm_1[grid(64)](buf1, buf3, buf4,
            buf5, 64, XBLOCK=64, num_warps=1, num_stages=1)
        buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        triton_poi_fused_native_layer_norm_2[grid(16, 16)](buf1, buf3, buf4,
            buf5, primals_6, primals_7, buf6, 16, 16, XBLOCK=16, YBLOCK=16,
            num_warps=4, num_stages=1)
        del buf4
        del buf5
        del primals_7
        buf7 = empty_strided_cuda((64, 16), (16, 1), torch.float32)
        extern_kernels.addmm(primals_9, reinterpret_tensor(buf6, (64, 4), (
            4, 1), 0), reinterpret_tensor(primals_8, (4, 16), (1, 4), 0),
            alpha=1, beta=1, out=buf7)
        del primals_9
        buf8 = empty_strided_cuda((4, 4, 4, 16), (256, 64, 16, 1), torch.
            float32)
        triton_poi_fused_gelu_3[grid(1024)](buf7, buf8, 1024, XBLOCK=256,
            num_warps=4, num_stages=1)
        buf9 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
        extern_kernels.addmm(primals_11, reinterpret_tensor(buf8, (64, 16),
            (16, 1), 0), reinterpret_tensor(primals_10, (16, 4), (1, 16), 0
            ), alpha=1, beta=1, out=buf9)
        del primals_11
        buf10 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        triton_poi_fused_add_4[grid(16, 16)](primals_1, primals_12, buf9,
            buf10, 16, 16, XBLOCK=16, YBLOCK=16, num_warps=4, num_stages=1)
    return (buf10, primals_1, primals_2, primals_4, primals_6, primals_12,
        buf1, buf3, reinterpret_tensor(buf6, (64, 4), (4, 1), 0), buf7,
        reinterpret_tensor(buf8, (64, 16), (16, 1), 0), buf9, primals_10,
        primals_8)


class LayerNorm(nn.Module):
    """ LayerNorm that supports two data formats: channels_last (default) or channels_first. 
    The ordering of the dimensions in the inputs. channels_last corresponds to inputs with 
    shape (batch_size, height, width, channels) while channels_first corresponds to inputs 
    with shape (batch_size, channels, height, width).
    """

    def __init__(self, normalized_shape, eps=1e-06, data_format='channels_last'
        ):
        super().__init__()
        self.weight = nn.Parameter(torch.ones(normalized_shape))
        self.bias = nn.Parameter(torch.zeros(normalized_shape))
        self.eps = eps
        self.data_format = data_format
        if self.data_format not in ['channels_last', 'channels_first']:
            raise NotImplementedError
        self.normalized_shape = normalized_shape,

    def forward(self, x):
        if self.data_format == 'channels_last':
            return F.layer_norm(x, self.normalized_shape, self.weight, self
                .bias, self.eps)
        elif self.data_format == 'channels_first':
            u = x.mean(1, keepdim=True)
            s = (x - u).pow(2).mean(1, keepdim=True)
            x = (x - u) / torch.sqrt(s + self.eps)
            x = self.weight[:, None, None] * x + self.bias[:, None, None]
            return x


class Minimum(nn.Module):

    def forward(self, x, y):
        return torch.minimum(x, y)


class NextMinBlock(nn.Module):
    """ ConvNeXt Block. There are two equivalent implementations:
    (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)
    (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back
    We use (2) as we find it slightly faster in PyTorch

    Args:
        dim (int): Number of input channels.
        kernel_size (int): dws kernel_size
        drop_path (float): Stochastic depth rate. Default: 0.0
        layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
    """

    def __init__(self, dim, drop_path=0.0, layer_scale_init_value=1e-06,
        kernel_size=7):
        super().__init__()
        if kernel_size != 7:
            warnings.warn(f'Using kernel_size: {kernel_size}')
        self.dwconv_left = nn.Conv2d(dim, dim, kernel_size=kernel_size,
            padding=kernel_size // 2, groups=dim)
        self.dwconv_right = nn.Conv2d(dim, dim, kernel_size=kernel_size,
            padding=kernel_size // 2, groups=dim)
        self.instance_norm_relu = nn.Sequential(nn.InstanceNorm2d(dim), nn.
            ReLU())
        self.min = Minimum()
        self.norm = LayerNorm(dim, eps=1e-06)
        self.pwconv1 = nn.Linear(dim, 4 * dim)
        self.act = nn.GELU()
        self.pwconv2 = nn.Linear(4 * dim, dim)
        self.gamma = nn.Parameter(layer_scale_init_value * torch.ones(dim),
            requires_grad=True) if layer_scale_init_value > 0 else None
        self.drop_path = DropPath(drop_path
            ) if drop_path > 0.0 else nn.Identity()

    def forward(self, x):
        input = x
        x_left = self.dwconv_left(x)
        x_right = self.dwconv_right(x)
        x_left = self.instance_norm_relu(x_left)
        x_right = self.instance_norm_relu(x_right)
        x = self.min(x_left, x_right)
        x = x.permute(0, 2, 3, 1)
        x = self.norm(x)
        x = self.pwconv1(x)
        x = self.act(x)
        x = self.pwconv2(x)
        if self.gamma is not None:
            x = self.gamma * x
        x = x.permute(0, 3, 1, 2)
        x = input + self.drop_path(x)
        return x


class Abs(nn.Module):

    def forward(self, x):
        return torch.abs(x)


class NextMinMinusAbsBlockNoNormNew(NextMinBlock):

    def __init__(self, dim, drop_path=0.0, layer_scale_init_value=1e-06,
        kernel_size=7):
        super().__init__(dim, drop_path=drop_path, layer_scale_init_value=
            layer_scale_init_value, kernel_size=kernel_size)
        self.lambda_ = 2.0
        self.abs = Abs()
        self.instance_norm_relu = nn.Sequential(nn.ReLU())

    def forward(self, input_0):
        primals_3 = self.gamma
        primals_2 = self.dwconv_left.weight
        primals_5 = self.dwconv_left.bias
        primals_4 = self.dwconv_right.weight
        primals_6 = self.dwconv_right.bias
        primals_7 = self.norm.weight
        primals_11 = self.norm.bias
        primals_8 = self.pwconv1.weight
        primals_9 = self.pwconv1.bias
        primals_10 = self.pwconv2.weight
        primals_12 = self.pwconv2.bias
        primals_1 = input_0
        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])
        return output[0]
