# AOT ID: ['0_forward']
from ctypes import c_void_p, c_long, c_int
import torch
import math
import random
import os
import tempfile
from math import inf, nan
from torch._inductor.hooks import run_intermediate_hooks
from torch._inductor.utils import maybe_profile
from torch._inductor.codegen.memory_planning import _align as align
from torch import device, empty_strided
from torch._inductor.async_compile import AsyncCompile
from torch._inductor.select_algorithm import extern_kernels
from torch._inductor.codegen.multi_kernel import MultiKernelCall
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid, split_scan_grid, grid_combo_kernels, start_graph, end_graph
from torch._C import _cuda_getCurrentRawStream as get_raw_stream

aten = torch.ops.aten
inductor_ops = torch.ops.inductor
_quantized = torch.ops._quantized
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cpu = torch._C._dynamo.guards._empty_strided_cpu
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
empty_strided_xpu = torch._C._dynamo.guards._empty_strided_xpu
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
alloc_from_pool = torch.ops.inductor._alloc_from_pool
async_compile = AsyncCompile()


# kernel path: runs/run_shard_4/inductor_cache/nn/cnn2whoh3oh4jprgokfuxayniolcdfffxezzblenezehrpkn2f5i.py
# Topologically Sorted Source Nodes: [add_1, relu], Original ATen: [aten.add, aten.relu, aten.threshold_backward]
# Source node to ATen node mapping:
#   add_1 => add_1
#   relu => relu
# Graph fragment:
#   %add_1 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%permute_1, %primals_5), kwargs = {})
#   %relu : [num_users=2] = call_function[target=torch.ops.aten.relu.default](args = (%add_1,), kwargs = {})
#   %le : [num_users=1] = call_function[target=torch.ops.aten.le.Scalar](args = (%relu, 0), kwargs = {})
triton_poi_fused_add_relu_threshold_backward_0 = async_compile.triton('triton_poi_fused_add_relu_threshold_backward_0', '''
import triton
import triton.language as tl
from triton.compiler.compiler import AttrsDescriptor

from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, instance_descriptor, DeviceProperties

@triton_heuristics.pointwise(
    size_hints=[4, 4], tile_hint=TileHint.DEFAULT,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*i1', 4: 'i32', 5: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_add_relu_threshold_backward_0', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 2, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False},
    min_elem_per_thread=0
)
@triton.jit
def triton_poi_fused_add_relu_threshold_backward_0(in_ptr0, in_ptr1, out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK : tl.constexpr, XBLOCK : tl.constexpr):
    ynumel = 4
    xnumel = 4
    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
    x1 = xindex
    y0 = yindex
    tmp0 = tl.load(in_ptr0 + (y0 + (4*x1)), xmask & ymask)
    tmp1 = tl.load(in_ptr1 + (x1), xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp3 = tl.full([1, 1], 0, tl.int32)
    tmp4 = triton_helpers.maximum(tmp3, tmp2)
    tmp5 = 0.0
    tmp6 = tmp4 <= tmp5
    tl.store(out_ptr0 + (x1 + (4*y0)), tmp4, xmask & ymask)
    tl.store(out_ptr1 + (y0 + (4*x1)), tmp6, xmask & ymask)
''', device_str='cuda')


# kernel path: runs/run_shard_4/inductor_cache/ss/cssiek35x2y7bd4xoj4rgriv2mj6jasrlifhbfd56x7ev3iwsyqj.py
# Topologically Sorted Source Nodes: [add_1, relu, hidden1], Original ATen: [aten.add, aten.relu, aten.t]
# Source node to ATen node mapping:
#   add_1 => add_1
#   hidden1 => permute_2
#   relu => relu
# Graph fragment:
#   %add_1 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%permute_1, %primals_5), kwargs = {})
#   %relu : [num_users=2] = call_function[target=torch.ops.aten.relu.default](args = (%add_1,), kwargs = {})
#   %permute_2 : [num_users=2] = call_function[target=torch.ops.aten.permute.default](args = (%relu, [1, 0]), kwargs = {})
triton_poi_fused_add_relu_t_1 = async_compile.triton('triton_poi_fused_add_relu_t_1', '''
import triton
import triton.language as tl
from triton.compiler.compiler import AttrsDescriptor

from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, instance_descriptor, DeviceProperties

@triton_heuristics.pointwise(
    size_hints=[4, 4], tile_hint=TileHint.SQUARE,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: 'i32', 3: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_add_relu_t_1', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 1, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False},
    min_elem_per_thread=0
)
@triton.jit
def triton_poi_fused_add_relu_t_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK : tl.constexpr, XBLOCK : tl.constexpr):
    ynumel = 4
    xnumel = 4
    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
    x1 = xindex
    y0 = yindex
    tmp0 = tl.load(in_ptr0 + (y0 + (4*x1)), xmask & ymask)
    tl.store(out_ptr0 + (x1 + (4*y0)), tmp0, xmask & ymask)
''', device_str='cuda')


# kernel path: runs/run_shard_4/inductor_cache/4u/c4u7rjkzibe2qym3skbdctsopc5pi7qxvmf7mrqrjpvmds2rtiqm.py
# Topologically Sorted Source Nodes: [base_output, add_2, add_3], Original ATen: [aten.add]
# Source node to ATen node mapping:
#   add_2 => add_2
#   add_3 => add_3
#   base_output => add
# Graph fragment:
#   %add : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%mm, %primals_3), kwargs = {})
#   %add_2 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%permute_3, %primals_7), kwargs = {})
#   %add_3 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%add, %add_2), kwargs = {})
triton_poi_fused_add_2 = async_compile.triton('triton_poi_fused_add_2', '''
import triton
import triton.language as tl
from triton.compiler.compiler import AttrsDescriptor

from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, instance_descriptor, DeviceProperties

@triton_heuristics.pointwise(
    size_hints=[4, 4], tile_hint=TileHint.DEFAULT,
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: 'i32', 5: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_add_2', 'mutated_arg_names': ['in_out_ptr0'], 'no_x_dim': False, 'num_load': 4, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False},
    min_elem_per_thread=0
)
@triton.jit
def triton_poi_fused_add_2(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, ynumel, xnumel, YBLOCK : tl.constexpr, XBLOCK : tl.constexpr):
    ynumel = 4
    xnumel = 4
    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
    x1 = xindex
    y0 = yindex
    tmp0 = tl.load(in_out_ptr0 + (x1 + (4*y0)), xmask & ymask)
    tmp1 = tl.load(in_ptr0 + (x1), xmask, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr1 + (y0 + (4*x1)), xmask & ymask)
    tmp4 = tl.load(in_ptr2 + (x1), xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp5 = tmp3 + tmp4
    tmp6 = tmp2 + tmp5
    tl.store(in_out_ptr0 + (x1 + (4*y0)), tmp6, xmask & ymask)
''', device_str='cuda')


async_compile.wait(globals())
del async_compile

def call(args):
    primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7 = 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, ), (1, ))
    assert_size_stride(primals_6, (4, 4), (4, 1))
    assert_size_stride(primals_7, (4, ), (1, ))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [matmul], Original ATen: [aten.mm]
        extern_kernels.mm(primals_2, primals_1, out=buf0)
        del primals_1
        buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [matmul_1], Original ATen: [aten.mm]
        extern_kernels.mm(primals_4, reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf1)
        del primals_4
        buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        buf6 = empty_strided_cuda((4, 4), (1, 4), torch.bool)
        # Topologically Sorted Source Nodes: [add_1, relu], Original ATen: [aten.add, aten.relu, aten.threshold_backward]
        stream0 = get_raw_stream(0)
        triton_poi_fused_add_relu_threshold_backward_0.run(buf1, primals_5, buf2, buf6, 4, 4, grid=grid(4, 4), stream=stream0)
        del primals_5
        buf3 = buf1; del buf1  # reuse
        # Topologically Sorted Source Nodes: [add_1, relu, hidden1], Original ATen: [aten.add, aten.relu, aten.t]
        triton_poi_fused_add_relu_t_1.run(buf2, buf3, 4, 4, grid=grid(4, 4), stream=stream0)
        buf4 = buf2; del buf2  # reuse
        # Topologically Sorted Source Nodes: [matmul_2], Original ATen: [aten.mm]
        extern_kernels.mm(primals_6, buf3, out=buf4)
        buf5 = buf0; del buf0  # reuse
        # Topologically Sorted Source Nodes: [base_output, add_2, add_3], Original ATen: [aten.add]
        triton_poi_fused_add_2.run(buf5, primals_3, buf4, primals_7, 4, 4, grid=grid(4, 4), stream=stream0)
        del buf4
        del primals_3
        del primals_7
    return (buf5, reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), reinterpret_tensor(buf3, (4, 4), (1, 4), 0), buf6, )


def benchmark_compiled_module(times=10, repeat=10):
    from torch._dynamo.testing import rand_strided
    from torch._inductor.utils import print_performance
    primals_1 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    primals_2 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    primals_3 = rand_strided((4, ), (1, ), device='cuda:0', dtype=torch.float32)
    primals_4 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    primals_5 = rand_strided((4, ), (1, ), device='cuda:0', dtype=torch.float32)
    primals_6 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    primals_7 = rand_strided((4, ), (1, ), device='cuda:0', dtype=torch.float32)
    fn = lambda: call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7])
    return print_performance(fn, times=times, repeat=repeat)


if __name__ == "__main__":
    from torch._inductor.wrapper_benchmark import compiled_module_main
    compiled_module_main('None', benchmark_compiled_module)

import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F


class AdvLinearNet(nn.Module):
    """
    Adversarial linear network.
    """

    def __init__(self, n_inputs: 'int', n_outputs: 'int', epsilon: 'float'=
        0.0, q: 'int'=1):
        """
        Initialize a linear network.

        Inputs:
            n_inputs: int
                Dimension of input.

            n_outputs: int
                Dimension of output.

            epsilon: float
                Adversarial noise magnitude.

            q: int
                Adversarial norm.
        """
        super(AdvLinearNet, self).__init__()
        self.n_inputs = n_inputs
        self.n_outputs = n_outputs
        self.epsilon = torch.tensor(epsilon)
        self.q = q
        self.beta = nn.Parameter(torch.rand((n_inputs, n_outputs),
            requires_grad=True) / np.sqrt(n_outputs))
        self.bias = nn.Parameter(torch.zeros(n_outputs, requires_grad=True))

    def adv_norm(self) ->torch.Tensor:
        """
        Calculate the adversarial norm, i.e., the perturbation size.

        Outputs:
            pert: torch.Tensor
                Size of adversarial perturbation.
        """
        return torch.norm(self.beta, dim=0, p=self.q)

    def forward(self, x: 'torch.Tensor', y: 'torch.Tensor', adv: 'bool'
        ) ->torch.Tensor:
        """
        Apply the linear network.

        Inputs:
            x: torch.Tensor
                Predictor tensor.

            y: torch.Tensor
                Target tensor.

            adv: bool
                Adversarial perturbation or not.

        Output:
            y_hat: torch.Tensor
                Predicted value of y.
        """
        base_output = torch.matmul(x, self.beta) + self.bias
        if adv:
            return base_output - self.epsilon * y * self.adv_norm()
        return base_output

    def get_epsilon(self) ->float:
        """
        Get the adversarial perturbation magnitude.

        Outputs:
            epsilon: float
                Magnitude of adversarial perturbation.
        """
        return self.epsilon

    def extra_repr(self) ->str:
        """
        Extra representation for the adversarial linear predictor.

        Output:
            info: str
                String providing number of inputs and outputs.
        """
        return 'n_inputs={0}, n_outputs={1}'.format(self.n_inputs, self.
            n_outputs)


class AdvOneLayer(nn.Module):
    """
    One hidden layer tree-transformed neural network.
    """

    def __init__(self, n_inputs: 'int', n_outputs: 'int', n_hidden1: 'int',
        epsilon: 'float'=0.0, q: 'int'=1, gamma: 'float'=1.0):
        """
        Initialize a one hidden layer neural network.

        Inputs:
            n_inputs: int
                Number of inputs.

            n_outputs: int
                Number of outputs.

            n_hidden1: int
                Number of hidden nodes.

            epsilon: float
                Adversarial perturbation size

            q: int
                Adversarial perturbation norm.

            gamma: float
                Normalizing factor.
        """
        super(AdvOneLayer, self).__init__()
        self.n_inputs = n_inputs
        self.n_outputs = n_outputs
        self.n_hidden1 = n_hidden1
        self.epsilon = torch.tensor(epsilon)
        self.q = q
        self.W1 = nn.Parameter(-torch.rand((n_hidden1, n_inputs),
            requires_grad=True) / (gamma * n_hidden1))
        self.W2 = nn.Parameter(torch.rand((n_outputs, n_hidden1),
            requires_grad=True) / (gamma * n_outputs))
        self.bias1 = nn.Parameter(torch.zeros(n_hidden1, requires_grad=True))
        self.bias2 = nn.Parameter(torch.zeros(n_outputs, requires_grad=True))
        self.pert = None
        self.output = None

    def adv_norm_W1(self) ->torch.Tensor:
        """
        Compute the adversarial norm the first layer weights.

        Outputs:
            W1_norm: torch.Tensor
                Norm of first layer of weights.
        """
        return torch.norm(self.W1, p=self.q, dim=1)

    def forward(self, x: 'torch.Tensor', y: 'torch.Tensor'=None, adv:
        'bool'=False) ->torch.Tensor:
        """
        Evaluate the network on data.

        Inputs:
            x: torch.Tensor
                Predictor tensor.

            y: torch.Tensor
                Target tensor. Unnecessary if not adversarial.

            adv: bool
                Whether or not to use an adversarial perturbation.

        Outputs:
            nn_output: torch.Tensor
                The predicted values of y.
        """
        if adv:
            batch_size = x.shape[0]
            W1_norm = self.adv_norm_W1()
            output = torch.zeros((batch_size, self.n_outputs, self.n_hidden1))
            pert_tensor = torch.zeros((batch_size, self.n_outputs, self.
                n_hidden1))
            for i in range(self.n_outputs):
                for j in range(self.n_hidden1):
                    adv_pert = -self.epsilon * y.float()[:, i] * self.W2[i, j
                        ].sign() * W1_norm[j]
                    hidden1 = F.relu(torch.t(torch.matmul(self.W1[j, :],
                        torch.t(x))) + self.bias1[j] + adv_pert.float())
                    summand = self.W2[i, j] * self.n_hidden1
                    output[:, i, j] = summand
                    pert_tensor[:, i, j] = adv_pert
            self.pert = pert_tensor
            self.output = output
            return torch.sum(output, dim=2) + self.bias2
        hidden1 = torch.t(F.relu(torch.t(torch.matmul(self.W1, torch.t(x))) +
            self.bias1))
        return torch.t(torch.matmul(self.W2, hidden1)) + self.bias2

    def get_epsilon(self) ->float:
        """
        Get adversarial perturbation magnitude.

        Outputs:
            epsilon: float
                Input perturbation magnitude.
        """
        return self.epsilon

    def extra_repr(self):
        """
        Extra representation for the network.

        Outputs:
            output: str
                String containing number of inputs, number of outputs,
                number of hidden layers, perturbation size, and
                perturbation norm.
        """
        output = 'n_inputs={}, n_outputs={}, n_hidden1={}, epsilon={}, p={}'
        return output.format(self.n_inputs, self.n_outputs, self.n_hidden1,
            self.epsilon, self.p)


class AdvResNet(nn.Module):
    """
    Adversarial resnet, i.e., a one hidden layer neural network and
    a linear component.
    """

    def __init__(self, n_inputs: 'int', n_outputs: 'int', n_hidden1: 'int',
        epsilon: 'float'=0.0, p: 'int'=1, gamma: 'float'=1.0):
        """
        Initialize an adversarial resnet.

        Inputs:
            n_inputs: int
                Number of inputs.

            n_outputs: int
                Number of outputs.

            n_hidden1: int
                Number of hidden nodes.

            epsilon: float
                Adversarial perturbation size

            q: int
                Adversarial perturbation norm.

            gamma: float
                Normalizing factor.
        """
        super(AdvResNet, self).__init__()
        self.n_inputs = n_inputs
        self.n_outputs = n_outputs
        self.n_hidden1 = n_hidden1
        self.epsilon = torch.tensor(epsilon)
        self.p = p
        self.one_layer = AdvOneLayer(n_inputs, n_outputs, n_hidden1,
            epsilon, p, gamma)
        self.linear = AdvLinearNet(n_inputs, n_outputs, epsilon, p)

    def forward(self, x: 'torch.Tensor', y: 'torch.Tensor'=None, adv:
        'bool'=False) ->torch.Tensor:
        """
        Forward evalution of network.

        Inputs:
            x: torch.Tensor
                Predictor tensor.

            y: torch.Tensor
                Target tensor. Unnecessary if not adversarial.

            adv: bool
                Whether or not to use an adversarial perturbation.

        Outputs:
            nn_output: torch.Tensor
                The predicted values of y.
        """
        return self.linear(x, y, adv) + self.one_layer(x, y, adv)

    def get_epsilon(self) ->float:
        """
        Get the adversarial perturbation magnitude.

        Outputs:
            epsilon: float
                Magnitude of adversarial perturbation.
        """
        return self.epsilon


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


def get_init_inputs():
    return [[], {'n_inputs': 4, 'n_outputs': 4, 'n_hidden1': 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
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
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_add_relu_threshold_backward_0(in_ptr0, in_ptr1,
    out_ptr0, out_ptr1, ynumel, xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.
    constexpr):
    ynumel = 4
    xnumel = 4
    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
    x1 = xindex
    y0 = yindex
    tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask)
    tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp3 = tl.full([1, 1], 0, tl.int32)
    tmp4 = triton_helpers.maximum(tmp3, tmp2)
    tmp5 = 0.0
    tmp6 = tmp4 <= tmp5
    tl.store(out_ptr0 + (x1 + 4 * y0), tmp4, xmask & ymask)
    tl.store(out_ptr1 + (y0 + 4 * x1), tmp6, xmask & ymask)


@triton.jit
def triton_poi_fused_add_relu_t_1(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK:
    tl.constexpr, XBLOCK: tl.constexpr):
    ynumel = 4
    xnumel = 4
    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
    x1 = xindex
    y0 = yindex
    tmp0 = tl.load(in_ptr0 + (y0 + 4 * x1), xmask & ymask)
    tl.store(out_ptr0 + (x1 + 4 * y0), tmp0, xmask & ymask)


@triton.jit
def triton_poi_fused_add_2(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, ynumel,
    xnumel, YBLOCK: tl.constexpr, XBLOCK: tl.constexpr):
    ynumel = 4
    xnumel = 4
    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
    x1 = xindex
    y0 = yindex
    tmp0 = tl.load(in_out_ptr0 + (x1 + 4 * y0), xmask & ymask)
    tmp1 = tl.load(in_ptr0 + x1, xmask, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr1 + (y0 + 4 * x1), xmask & ymask)
    tmp4 = tl.load(in_ptr2 + x1, xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp5 = tmp3 + tmp4
    tmp6 = tmp2 + tmp5
    tl.store(in_out_ptr0 + (x1 + 4 * y0), tmp6, xmask & ymask)


def call(args):
    (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
        primals_7) = 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,), (1,))
    assert_size_stride(primals_6, (4, 4), (4, 1))
    assert_size_stride(primals_7, (4,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        extern_kernels.mm(primals_2, primals_1, out=buf0)
        del primals_1
        buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        extern_kernels.mm(primals_4, reinterpret_tensor(primals_2, (4, 4),
            (1, 4), 0), out=buf1)
        del primals_4
        buf2 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        buf6 = empty_strided_cuda((4, 4), (1, 4), torch.bool)
        get_raw_stream(0)
        triton_poi_fused_add_relu_threshold_backward_0[grid(4, 4)](buf1,
            primals_5, buf2, buf6, 4, 4, XBLOCK=4, YBLOCK=4, num_warps=1,
            num_stages=1)
        del primals_5
        buf3 = buf1
        del buf1
        triton_poi_fused_add_relu_t_1[grid(4, 4)](buf2, buf3, 4, 4, XBLOCK=
            4, YBLOCK=4, num_warps=1, num_stages=1)
        buf4 = buf2
        del buf2
        extern_kernels.mm(primals_6, buf3, out=buf4)
        buf5 = buf0
        del buf0
        triton_poi_fused_add_2[grid(4, 4)](buf5, primals_3, buf4, primals_7,
            4, 4, XBLOCK=4, YBLOCK=4, num_warps=1, num_stages=1)
        del buf4
        del primals_3
        del primals_7
    return buf5, reinterpret_tensor(primals_2, (4, 4), (1, 4), 0
        ), reinterpret_tensor(primals_6, (4, 4), (1, 4), 0
        ), reinterpret_tensor(buf3, (4, 4), (1, 4), 0), buf6


class AdvLinearNet(nn.Module):
    """
    Adversarial linear network.
    """

    def __init__(self, n_inputs: 'int', n_outputs: 'int', epsilon: 'float'=
        0.0, q: 'int'=1):
        """
        Initialize a linear network.

        Inputs:
            n_inputs: int
                Dimension of input.

            n_outputs: int
                Dimension of output.

            epsilon: float
                Adversarial noise magnitude.

            q: int
                Adversarial norm.
        """
        super(AdvLinearNet, self).__init__()
        self.n_inputs = n_inputs
        self.n_outputs = n_outputs
        self.epsilon = torch.tensor(epsilon)
        self.q = q
        self.beta = nn.Parameter(torch.rand((n_inputs, n_outputs),
            requires_grad=True) / np.sqrt(n_outputs))
        self.bias = nn.Parameter(torch.zeros(n_outputs, requires_grad=True))

    def adv_norm(self) ->torch.Tensor:
        """
        Calculate the adversarial norm, i.e., the perturbation size.

        Outputs:
            pert: torch.Tensor
                Size of adversarial perturbation.
        """
        return torch.norm(self.beta, dim=0, p=self.q)

    def forward(self, x: 'torch.Tensor', y: 'torch.Tensor', adv: 'bool'
        ) ->torch.Tensor:
        """
        Apply the linear network.

        Inputs:
            x: torch.Tensor
                Predictor tensor.

            y: torch.Tensor
                Target tensor.

            adv: bool
                Adversarial perturbation or not.

        Output:
            y_hat: torch.Tensor
                Predicted value of y.
        """
        base_output = torch.matmul(x, self.beta) + self.bias
        if adv:
            return base_output - self.epsilon * y * self.adv_norm()
        return base_output

    def get_epsilon(self) ->float:
        """
        Get the adversarial perturbation magnitude.

        Outputs:
            epsilon: float
                Magnitude of adversarial perturbation.
        """
        return self.epsilon

    def extra_repr(self) ->str:
        """
        Extra representation for the adversarial linear predictor.

        Output:
            info: str
                String providing number of inputs and outputs.
        """
        return 'n_inputs={0}, n_outputs={1}'.format(self.n_inputs, self.
            n_outputs)


class AdvOneLayer(nn.Module):
    """
    One hidden layer tree-transformed neural network.
    """

    def __init__(self, n_inputs: 'int', n_outputs: 'int', n_hidden1: 'int',
        epsilon: 'float'=0.0, q: 'int'=1, gamma: 'float'=1.0):
        """
        Initialize a one hidden layer neural network.

        Inputs:
            n_inputs: int
                Number of inputs.

            n_outputs: int
                Number of outputs.

            n_hidden1: int
                Number of hidden nodes.

            epsilon: float
                Adversarial perturbation size

            q: int
                Adversarial perturbation norm.

            gamma: float
                Normalizing factor.
        """
        super(AdvOneLayer, self).__init__()
        self.n_inputs = n_inputs
        self.n_outputs = n_outputs
        self.n_hidden1 = n_hidden1
        self.epsilon = torch.tensor(epsilon)
        self.q = q
        self.W1 = nn.Parameter(-torch.rand((n_hidden1, n_inputs),
            requires_grad=True) / (gamma * n_hidden1))
        self.W2 = nn.Parameter(torch.rand((n_outputs, n_hidden1),
            requires_grad=True) / (gamma * n_outputs))
        self.bias1 = nn.Parameter(torch.zeros(n_hidden1, requires_grad=True))
        self.bias2 = nn.Parameter(torch.zeros(n_outputs, requires_grad=True))
        self.pert = None
        self.output = None

    def adv_norm_W1(self) ->torch.Tensor:
        """
        Compute the adversarial norm the first layer weights.

        Outputs:
            W1_norm: torch.Tensor
                Norm of first layer of weights.
        """
        return torch.norm(self.W1, p=self.q, dim=1)

    def forward(self, x: 'torch.Tensor', y: 'torch.Tensor'=None, adv:
        'bool'=False) ->torch.Tensor:
        """
        Evaluate the network on data.

        Inputs:
            x: torch.Tensor
                Predictor tensor.

            y: torch.Tensor
                Target tensor. Unnecessary if not adversarial.

            adv: bool
                Whether or not to use an adversarial perturbation.

        Outputs:
            nn_output: torch.Tensor
                The predicted values of y.
        """
        if adv:
            batch_size = x.shape[0]
            W1_norm = self.adv_norm_W1()
            output = torch.zeros((batch_size, self.n_outputs, self.n_hidden1))
            pert_tensor = torch.zeros((batch_size, self.n_outputs, self.
                n_hidden1))
            for i in range(self.n_outputs):
                for j in range(self.n_hidden1):
                    adv_pert = -self.epsilon * y.float()[:, i] * self.W2[i, j
                        ].sign() * W1_norm[j]
                    hidden1 = F.relu(torch.t(torch.matmul(self.W1[j, :],
                        torch.t(x))) + self.bias1[j] + adv_pert.float())
                    summand = self.W2[i, j] * self.n_hidden1
                    output[:, i, j] = summand
                    pert_tensor[:, i, j] = adv_pert
            self.pert = pert_tensor
            self.output = output
            return torch.sum(output, dim=2) + self.bias2
        hidden1 = torch.t(F.relu(torch.t(torch.matmul(self.W1, torch.t(x))) +
            self.bias1))
        return torch.t(torch.matmul(self.W2, hidden1)) + self.bias2

    def get_epsilon(self) ->float:
        """
        Get adversarial perturbation magnitude.

        Outputs:
            epsilon: float
                Input perturbation magnitude.
        """
        return self.epsilon

    def extra_repr(self):
        """
        Extra representation for the network.

        Outputs:
            output: str
                String containing number of inputs, number of outputs,
                number of hidden layers, perturbation size, and
                perturbation norm.
        """
        output = 'n_inputs={}, n_outputs={}, n_hidden1={}, epsilon={}, p={}'
        return output.format(self.n_inputs, self.n_outputs, self.n_hidden1,
            self.epsilon, self.p)


class AdvResNetNew(nn.Module):
    """
    Adversarial resnet, i.e., a one hidden layer neural network and
    a linear component.
    """

    def __init__(self, n_inputs: 'int', n_outputs: 'int', n_hidden1: 'int',
        epsilon: 'float'=0.0, p: 'int'=1, gamma: 'float'=1.0):
        """
        Initialize an adversarial resnet.

        Inputs:
            n_inputs: int
                Number of inputs.

            n_outputs: int
                Number of outputs.

            n_hidden1: int
                Number of hidden nodes.

            epsilon: float
                Adversarial perturbation size

            q: int
                Adversarial perturbation norm.

            gamma: float
                Normalizing factor.
        """
        super(AdvResNetNew, self).__init__()
        self.n_inputs = n_inputs
        self.n_outputs = n_outputs
        self.n_hidden1 = n_hidden1
        self.epsilon = torch.tensor(epsilon)
        self.p = p
        self.one_layer = AdvOneLayer(n_inputs, n_outputs, n_hidden1,
            epsilon, p, gamma)
        self.linear = AdvLinearNet(n_inputs, n_outputs, epsilon, p)

    def get_epsilon(self) ->float:
        """
        Get the adversarial perturbation magnitude.

        Outputs:
            epsilon: float
                Magnitude of adversarial perturbation.
        """
        return self.epsilon

    def forward(self, input_0):
        primals_1 = self.one_layer.W1
        primals_2 = self.one_layer.W2
        primals_3 = self.one_layer.bias1
        primals_5 = self.one_layer.bias2
        primals_4 = self.linear.beta
        primals_7 = self.linear.bias
        primals_6 = input_0
        output = call([primals_1, primals_2, primals_3, primals_4,
            primals_5, primals_6, primals_7])
        return output[0]
