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.nn import Module
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_add_0(in_ptr0, out_ptr0, ynumel, xnumel, YBLOCK: tl.
    constexpr, XBLOCK: tl.constexpr):
    ynumel = 2
    xnumel = 2
    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 + (x1 + 2 * y0), xmask & ymask)
    tmp1 = tl.load(in_ptr0 + (y0 + 2 * x1), xmask & ymask)
    tmp2 = tmp0 + tmp1
    tl.store(out_ptr0 + (x1 + 2 * y0), tmp2, xmask & ymask)


@triton.jit
def triton_poi_fused_add_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 128
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 2
    x1 = xindex // 2
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + (x0 + 4 * x1), xmask)
    tmp1 = tl.load(in_out_ptr0 + x2, xmask)
    tmp2 = tmp0 + tmp1
    tl.store(in_out_ptr0 + x2, tmp2, xmask)


@triton.jit
def triton_poi_fused_add_mul_ones_like_2(in_out_ptr0, in_ptr0, in_ptr1,
    xnumel, XBLOCK: tl.constexpr):
    xnumel = 128
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x0 = xindex % 2
    x1 = xindex // 2
    tmp0 = tl.load(in_out_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr0 + (2 + x0 + 4 * x1), xmask)
    tmp3 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp4 = 1.0
    tmp5 = tmp3 * tmp4
    tmp6 = tmp2 + tmp5
    tl.store(in_out_ptr0 + x2, tmp6, xmask)


@triton.jit
def triton_poi_fused_add_mul_ones_like_sigmoid_3(in_out_ptr0, in_ptr0,
    in_ptr1, in_ptr2, in_ptr3, xnumel, XBLOCK: tl.constexpr):
    xnumel = 128
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x0 = xindex % 2
    tmp0 = tl.load(in_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr2 + x2, xmask)
    tmp7 = tl.load(in_ptr3 + x0, xmask, eviction_policy='evict_last')
    tmp10 = tl.load(in_out_ptr0 + x2, xmask)
    tmp2 = 1.0
    tmp3 = tmp1 * tmp2
    tmp4 = tmp0 + tmp3
    tmp6 = tl.sigmoid(tmp5)
    tmp8 = tmp6 * tmp7
    tmp9 = tmp4 + tmp8
    tmp11 = tmp9 + tmp10
    tl.store(in_out_ptr0 + x2, tmp11, xmask)


@triton.jit
def triton_poi_fused_add_mul_ones_like_sigmoid_4(in_out_ptr0, in_ptr0,
    in_ptr1, in_ptr2, in_ptr3, in_ptr4, out_ptr0, xnumel, XBLOCK: tl.constexpr
    ):
    xnumel = 128
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x0 = xindex % 2
    tmp0 = tl.load(in_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
    tmp6 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_out_ptr0 + x2, xmask)
    tmp9 = tl.load(in_ptr3 + x2, xmask)
    tmp11 = tl.load(in_ptr4 + x0, xmask, eviction_policy='evict_last')
    tmp2 = 1.0
    tmp3 = tmp1 * tmp2
    tmp4 = tmp0 + tmp3
    tmp5 = tl.sigmoid(tmp4)
    tmp7 = tmp5 * tmp6
    tmp10 = tmp8 + tmp9
    tmp12 = tmp11 * tmp2
    tmp13 = tmp10 + tmp12
    tmp14 = tmp7 + tmp13
    tl.store(out_ptr0 + x2, tmp5, xmask)
    tl.store(in_out_ptr0 + x2, tmp14, xmask)


@triton.jit
def triton_poi_fused_add_mul_ones_like_5(in_out_ptr0, in_ptr0, in_ptr1,
    xnumel, XBLOCK: tl.constexpr):
    xnumel = 128
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x0 = xindex % 2
    tmp0 = tl.load(in_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr1 + x0, xmask, eviction_policy='evict_last')
    tmp5 = tl.load(in_out_ptr0 + x2, xmask)
    tmp2 = 1.0
    tmp3 = tmp1 * tmp2
    tmp4 = tmp0 + tmp3
    tmp6 = tmp4 + tmp5
    tl.store(in_out_ptr0 + x2, tmp6, xmask)


@triton.jit
def triton_poi_fused_cat_6(in_ptr0, in_ptr1, in_ptr2, in_ptr3, in_ptr4,
    out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 4
    x1 = xindex // 4
    x2 = xindex
    tmp0 = x0
    tl.full([1], 0, tl.int64)
    tmp3 = tl.full([1], 2, tl.int64)
    tmp4 = tmp0 < tmp3
    tmp5 = tl.load(in_ptr0 + (2 * x1 + x0), tmp4 & xmask, eviction_policy=
        'evict_last', other=0.0)
    tmp6 = tl.load(in_ptr1 + x0, tmp4 & xmask, eviction_policy='evict_last',
        other=0.0)
    tmp7 = 1.0
    tmp8 = tmp6 * tmp7
    tmp9 = tmp5 + tmp8
    tmp10 = tl.full(tmp9.shape, 0.0, tmp9.dtype)
    tmp11 = tl.where(tmp4, tmp9, tmp10)
    tmp12 = tmp0 >= tmp3
    tl.full([1], 4, tl.int64)
    tmp15 = tl.load(in_ptr2 + (2 * x1 + (-2 + x0)), tmp12 & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp16 = tl.load(in_ptr3 + (2 * x1 + (-2 + x0)), tmp12 & xmask,
        eviction_policy='evict_last', other=0.0)
    tmp17 = tmp15 + tmp16
    tmp18 = tl.load(in_ptr4 + (-2 + x0), tmp12 & xmask, eviction_policy=
        'evict_last', other=0.0)
    tmp19 = tmp18 * tmp7
    tmp20 = tmp17 + tmp19
    tmp21 = tl.full(tmp20.shape, 0.0, tmp20.dtype)
    tmp22 = tl.where(tmp12, tmp20, tmp21)
    tmp23 = tl.where(tmp4, tmp11, tmp22)
    tl.store(out_ptr0 + x2, tmp23, 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) = args
    args.clear()
    assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_2, (2, 2), (2, 1))
    assert_size_stride(primals_3, (2, 2), (2, 1))
    assert_size_stride(primals_4, (2,), (1,))
    assert_size_stride(primals_5, (2,), (1,))
    assert_size_stride(primals_6, (2,), (1,))
    assert_size_stride(primals_7, (2, 2), (2, 1))
    assert_size_stride(primals_8, (2, 2), (2, 1))
    assert_size_stride(primals_9, (2,), (1,))
    assert_size_stride(primals_10, (2,), (1,))
    assert_size_stride(primals_11, (2,), (1,))
    assert_size_stride(primals_12, (2, 2), (2, 1))
    assert_size_stride(primals_13, (2, 2), (2, 1))
    assert_size_stride(primals_14, (2,), (1,))
    assert_size_stride(primals_15, (2,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((2, 2), (2, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_add_0[grid(2, 2)](primals_2, buf0, 2, 2, XBLOCK=2,
            YBLOCK=2, num_warps=1, num_stages=1)
        del primals_2
        buf1 = empty_strided_cuda((64, 2), (2, 1), torch.float32)
        extern_kernels.mm(reinterpret_tensor(primals_1, (64, 2), (4, 1), 2),
            buf0, out=buf1)
        buf2 = buf0
        del buf0
        triton_poi_fused_add_0[grid(2, 2)](primals_3, buf2, 2, 2, XBLOCK=2,
            YBLOCK=2, num_warps=1, num_stages=1)
        del primals_3
        buf3 = reinterpret_tensor(buf1, (4, 4, 4, 2), (32, 8, 2, 1), 0)
        del buf1
        triton_poi_fused_add_1[grid(128)](buf3, primals_1, 128, XBLOCK=128,
            num_warps=4, num_stages=1)
        buf4 = empty_strided_cuda((64, 2), (2, 1), torch.float32)
        extern_kernels.mm(reinterpret_tensor(buf3, (64, 2), (2, 1), 0),
            buf2, out=buf4)
        buf5 = reinterpret_tensor(buf4, (4, 4, 4, 2), (32, 8, 2, 1), 0)
        del buf4
        triton_poi_fused_add_mul_ones_like_2[grid(128)](buf5, primals_1,
            primals_5, 128, XBLOCK=128, num_warps=4, num_stages=1)
        del primals_5
        buf6 = empty_strided_cuda((2, 2), (2, 1), torch.float32)
        triton_poi_fused_add_0[grid(2, 2)](primals_7, buf6, 2, 2, XBLOCK=2,
            YBLOCK=2, num_warps=1, num_stages=1)
        del primals_7
        buf7 = empty_strided_cuda((64, 2), (2, 1), torch.float32)
        extern_kernels.mm(reinterpret_tensor(buf5, (64, 2), (2, 1), 0),
            buf6, out=buf7)
        buf8 = reinterpret_tensor(buf7, (4, 4, 4, 2), (32, 8, 2, 1), 0)
        del buf7
        triton_poi_fused_add_mul_ones_like_sigmoid_3[grid(128)](buf8, buf3,
            primals_4, buf5, primals_6, 128, XBLOCK=128, num_warps=4,
            num_stages=1)
        del primals_4
        buf9 = empty_strided_cuda((2, 2), (2, 1), torch.float32)
        triton_poi_fused_add_0[grid(2, 2)](primals_8, buf9, 2, 2, XBLOCK=2,
            YBLOCK=2, num_warps=1, num_stages=1)
        del primals_8
        buf10 = empty_strided_cuda((64, 2), (2, 1), torch.float32)
        extern_kernels.mm(reinterpret_tensor(buf8, (64, 2), (2, 1), 0),
            buf9, out=buf10)
        buf11 = empty_strided_cuda((4, 4, 4, 2), (32, 8, 2, 1), torch.float32)
        buf12 = reinterpret_tensor(buf10, (4, 4, 4, 2), (32, 8, 2, 1), 0)
        del buf10
        triton_poi_fused_add_mul_ones_like_sigmoid_4[grid(128)](buf12, buf8,
            primals_9, primals_11, buf5, primals_10, buf11, 128, XBLOCK=128,
            num_warps=4, num_stages=1)
        del primals_10
        buf13 = empty_strided_cuda((2, 2), (2, 1), torch.float32)
        triton_poi_fused_add_0[grid(2, 2)](primals_12, buf13, 2, 2, XBLOCK=
            2, YBLOCK=2, num_warps=1, num_stages=1)
        del primals_12
        buf14 = empty_strided_cuda((64, 2), (2, 1), torch.float32)
        extern_kernels.mm(reinterpret_tensor(buf12, (64, 2), (2, 1), 0),
            buf13, out=buf14)
        buf15 = empty_strided_cuda((2, 2), (2, 1), torch.float32)
        triton_poi_fused_add_0[grid(2, 2)](primals_13, buf15, 2, 2, XBLOCK=
            2, YBLOCK=2, num_warps=1, num_stages=1)
        del primals_13
        buf16 = reinterpret_tensor(buf14, (4, 4, 4, 2), (32, 8, 2, 1), 0)
        del buf14
        triton_poi_fused_add_mul_ones_like_5[grid(128)](buf16, buf8,
            primals_9, 128, XBLOCK=128, num_warps=4, num_stages=1)
        del primals_9
        buf17 = empty_strided_cuda((64, 2), (2, 1), torch.float32)
        extern_kernels.mm(reinterpret_tensor(buf16, (64, 2), (2, 1), 0),
            buf15, out=buf17)
        buf18 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        triton_poi_fused_cat_6[grid(256)](buf16, primals_14, buf17, buf12,
            primals_15, buf18, 256, XBLOCK=256, num_warps=4, num_stages=1)
        del buf17
        del primals_14
        del primals_15
    return buf18, primals_6, primals_11, buf5, buf11, reinterpret_tensor(buf16,
        (2, 64), (1, 2), 0), reinterpret_tensor(buf15, (2, 2), (1, 2), 0
        ), reinterpret_tensor(buf12, (2, 64), (1, 2), 0), reinterpret_tensor(
        buf13, (2, 2), (1, 2), 0), reinterpret_tensor(buf8, (2, 64), (1, 2), 0
        ), reinterpret_tensor(buf9, (2, 2), (1, 2), 0), reinterpret_tensor(buf6
        , (2, 2), (1, 2), 0), reinterpret_tensor(buf3, (2, 64), (1, 2), 0
        ), reinterpret_tensor(buf2, (2, 2), (1, 2), 0), reinterpret_tensor(
        primals_1, (2, 64), (1, 4), 2)


class Module(torch.nn.Module):
    """Standard module format. 
    """

    def __init__(self):
        super(Module, self).__init__()
        self.activation = None
        self.initializer = None
        self.__device = None
        self.__dtype = None

    @property
    def device(self):
        return self.__device

    @property
    def dtype(self):
        return self.__dtype

    @device.setter
    def device(self, d):
        if d == 'cpu':
            self.cpu()
        elif d == 'gpu':
            self
        else:
            raise ValueError
        self.__device = d

    @dtype.setter
    def dtype(self, d):
        if d == 'float':
            self
        elif d == 'double':
            self
        else:
            raise ValueError
        self.__dtype = d

    @property
    def Device(self):
        if self.__device == 'cpu':
            return torch.device('cpu')
        elif self.__device == 'gpu':
            return torch.device('cuda')

    @property
    def Dtype(self):
        if self.__dtype == 'float':
            return torch.float32
        elif self.__dtype == 'double':
            return torch.float64

    @property
    def act(self):
        if self.activation == 'sigmoid':
            return torch.sigmoid
        elif self.activation == 'relu':
            return torch.relu
        elif self.activation == 'tanh':
            return torch.tanh
        elif self.activation == 'elu':
            return torch.elu
        else:
            raise NotImplementedError

    @property
    def Act(self):
        if self.activation == 'sigmoid':
            return torch.nn.Sigmoid()
        elif self.activation == 'relu':
            return torch.nn.ReLU()
        elif self.activation == 'tanh':
            return torch.nn.Tanh()
        elif self.activation == 'elu':
            return torch.nn.ELU()
        else:
            raise NotImplementedError

    @property
    def weight_init_(self):
        if self.initializer == 'He normal':
            return torch.nn.init.kaiming_normal_
        elif self.initializer == 'He uniform':
            return torch.nn.init.kaiming_uniform_
        elif self.initializer == 'Glorot normal':
            return torch.nn.init.xavier_normal_
        elif self.initializer == 'Glorot uniform':
            return torch.nn.init.xavier_uniform_
        elif self.initializer == 'orthogonal':
            return torch.nn.init.orthogonal_
        elif self.initializer == 'default':
            if self.activation == 'relu':
                return torch.nn.init.kaiming_normal_
            elif self.activation == 'tanh':
                return torch.nn.init.orthogonal_
            else:
                return lambda x: None
        else:
            raise NotImplementedError


class StructureNN(Module):
    """Structure-oriented neural network used as a general map based on designing architecture.
    """

    def __init__(self):
        super(StructureNN, self).__init__()

    def predict(self, x, returnnp=False):
        if not isinstance(x, torch.Tensor):
            x = torch.tensor(x, dtype=self.Dtype, device=self.Device)
        return self(x).cpu().detach().numpy() if returnnp else self(x)


class LinearModule(Module):
    """Linear symplectic module.
    """

    def __init__(self, dim, layers):
        super(LinearModule, self).__init__()
        self.dim = dim
        self.layers = layers
        self.params = self.__init_params()

    def forward(self, pqh):
        p, q, h = pqh
        for i in range(self.layers):
            S = self.params['S{}'.format(i + 1)]
            if i % 2 == 0:
                p = p + q @ (S + S.t()) * h
            else:
                q = p @ (S + S.t()) * h + q
        return p + self.params['bp'] * h, q + self.params['bq'] * h

    def __init_params(self):
        """Si is distributed N(0, 0.01), and b is set to zero.
        """
        d = int(self.dim / 2)
        params = nn.ParameterDict()
        for i in range(self.layers):
            params['S{}'.format(i + 1)] = nn.Parameter((torch.randn([d, d]) *
                0.01).requires_grad_(True))
        params['bp'] = nn.Parameter(torch.zeros([d]).requires_grad_(True))
        params['bq'] = nn.Parameter(torch.zeros([d]).requires_grad_(True))
        return params


class ActivationModule(Module):
    """Activation symplectic module.
    """

    def __init__(self, dim, activation, mode):
        super(ActivationModule, self).__init__()
        self.dim = dim
        self.activation = activation
        self.mode = mode
        self.params = self.__init_params()

    def forward(self, pqh):
        p, q, h = pqh
        if self.mode == 'up':
            return p + self.act(q) * self.params['a'] * h, q
        elif self.mode == 'low':
            return p, self.act(p) * self.params['a'] * h + q
        else:
            raise ValueError

    def __init_params(self):
        d = int(self.dim / 2)
        params = nn.ParameterDict()
        params['a'] = nn.Parameter((torch.randn([d]) * 0.01).requires_grad_
            (True))
        return params


class SympNet(StructureNN):

    def __init__(self):
        super(SympNet, self).__init__()
        self.dim = None

    def predict(self, xh, steps=1, keepinitx=False, returnnp=False):
        dim = xh.size(-1)
        size = len(xh.size())
        if dim == self.dim:
            pred = [xh]
            for _ in range(steps):
                pred.append(self(pred[-1]))
        else:
            x0, h = xh[..., :-1], xh[..., -1:]
            pred = [x0]
            for _ in range(steps):
                pred.append(self(torch.cat([pred[-1], h], dim=-1)))
        if keepinitx:
            steps = steps + 1
        else:
            pred = pred[1:]
        res = torch.cat(pred, dim=-1).view([-1, steps, self.dim][2 - size:])
        return res.cpu().detach().numpy() if returnnp else res


class LASympNetNew(SympNet):
    """LA-SympNet.
    Input: [num, dim] or [num, dim + 1]
    Output: [num, dim]
    """

    def __init__(self, dim, layers=3, sublayers=2, activation='sigmoid'):
        super(LASympNetNew, self).__init__()
        self.dim = dim
        self.layers = layers
        self.sublayers = sublayers
        self.activation = activation
        self.modus = self.__init_modules()

    def __init_modules(self):
        modules = nn.ModuleDict()
        for i in range(self.layers - 1):
            modules['LinM{}'.format(i + 1)] = LinearModule(self.dim, self.
                sublayers)
            mode = 'up' if i % 2 == 0 else 'low'
            modules['ActM{}'.format(i + 1)] = ActivationModule(self.dim,
                self.activation, mode)
        modules['LinMout'] = LinearModule(self.dim, self.sublayers)
        return modules

    def forward(self, input_0):
        primals_2 = self.modus.LinM1.params.S1
        primals_3 = self.modus.LinM1.params.S2
        primals_4 = self.modus.LinM1.params.bp
        primals_5 = self.modus.LinM1.params.bq
        primals_6 = self.modus.ActM1.params.a
        primals_7 = self.modus.LinM2.params.S1
        primals_8 = self.modus.LinM2.params.S2
        primals_9 = self.modus.LinM2.params.bp
        primals_10 = self.modus.LinM2.params.bq
        primals_11 = self.modus.ActM2.params.a
        primals_12 = self.modus.LinMout.params.S1
        primals_13 = self.modus.LinMout.params.S2
        primals_14 = self.modus.LinMout.params.bp
        primals_15 = self.modus.LinMout.params.bq
        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, primals_13, primals_14,
            primals_15])
        return output[0]


Measured latency_ms: 0.228394