# 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_6/inductor_cache/hz/chzyhov2xqetpxutrr7zhuwi672sgyqlffwh7xov7v7t6b4o2gze.py
# Topologically Sorted Source Nodes: [ret], Original ATen: [aten.add, aten.tanh]
# Source node to ATen node mapping:
#   ret => add, tanh
# Graph fragment:
#   %add_tensor_1 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%mm_default_1, %primals_6), kwargs = {})
#   %add_tensor : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%mm_default, %primals_5), kwargs = {})
#   %add : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%add_tensor_1, %add_tensor), kwargs = {})
#   %tanh : [num_users=2] = call_function[target=torch.ops.aten.tanh.default](args = (%add,), kwargs = {})
triton_poi_fused_add_tanh_0 = async_compile.triton('triton_poi_fused_add_tanh_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=[16], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: '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, 4), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_add_tanh_0', '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_tanh_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2, xnumel, XBLOCK : tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x0 = xindex % 4
    tmp0 = tl.load(in_out_ptr0 + (x2), xmask)
    tmp1 = tl.load(in_ptr0 + (x0), xmask, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr1 + (x2), xmask)
    tmp4 = tl.load(in_ptr2 + (x0), xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp5 = tmp3 + tmp4
    tmp6 = tmp2 + tmp5
    tmp7 = libdevice.tanh(tmp6)
    tl.store(in_out_ptr0 + (x2), tmp7, xmask)
''', 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, primals_8 = 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, 4), (4, 1))
    assert_size_stride(primals_4, (4, 4), (4, 1))
    assert_size_stride(primals_5, (4, ), (1, ))
    assert_size_stride(primals_6, (4, ), (1, ))
    assert_size_stride(primals_7, (4, 4), (4, 1))
    assert_size_stride(primals_8, (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: [], Original ATen: []
        extern_kernels.mm(primals_2, reinterpret_tensor(primals_4, (4, 4), (1, 4), 0), out=buf0)
        del primals_4
        buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        # Topologically Sorted Source Nodes: [], Original ATen: []
        extern_kernels.mm(primals_1, reinterpret_tensor(primals_3, (4, 4), (1, 4), 0), out=buf1)
        del primals_3
        buf2 = buf0; del buf0  # reuse
        # Topologically Sorted Source Nodes: [ret], Original ATen: [aten.add, aten.tanh]
        stream0 = get_raw_stream(0)
        triton_poi_fused_add_tanh_0.run(buf2, primals_6, buf1, primals_5, 16, grid=grid(16), stream=stream0)
        del primals_5
        del primals_6
        buf3 = buf1; del buf1  # reuse
        # Topologically Sorted Source Nodes: [otp], Original ATen: [aten.addmm]
        extern_kernels.addmm(primals_8, buf2, reinterpret_tensor(primals_7, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf3)
        del primals_8
    return (buf3, buf2, primals_1, primals_2, buf2, primals_7, )


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, 4), (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, ), (1, ), device='cuda:0', dtype=torch.float32)
    primals_7 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    primals_8 = 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, primals_8])
    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 math
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F


def initialize(dims, connection_prob=1.0, shape=0.1, scale=1.0):
    w = np.random.gamma(shape, scale, size=dims)
    w *= np.random.rand(*dims) < connection_prob
    return np.float32(w)


class VanillaRNNCell(nn.Module):

    def __init__(self, input_size, hidden_size, nonlinearity='tanh', ct=False):
        super(VanillaRNNCell, self).__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.nonlinearity = nonlinearity
        self.ct = ct
        self.weight_ih = nn.Parameter(torch.zeros((input_size, hidden_size)))
        self.weight_hh = nn.Parameter(torch.zeros((hidden_size, hidden_size)))
        self.bias = nn.Parameter(torch.zeros(hidden_size))
        self.reset_parameters()
        if self.nonlinearity == 'tanh':
            self.act = F.tanh
        elif self.nonlinearity == 'relu':
            self.act = F.relu
        else:
            raise RuntimeError('Unknown nonlinearity: {}'.format(self.
                nonlinearity))

    def reset_parameters(self):
        stdv = 1.0 / math.sqrt(self.hidden_size)
        for weight in self.parameters():
            nn.init.uniform_(weight, -stdv, stdv)

    def forward(self, inp, hidden_in):
        if not self.ct:
            hidden_out = self.act(torch.matmul(inp, self.weight_ih) + torch
                .matmul(hidden_in, self.weight_hh) + self.bias)
        else:
            alpha = 0.1
            hidden_out = (1 - alpha) * hidden_in + alpha * self.act(torch.
                matmul(inp, self.weight_ih) + torch.matmul(hidden_in, self.
                weight_hh) + self.bias)
        return hidden_out

    def init_hidden(self, batch_s):
        return torch.zeros(batch_s, self.hidden_size)


class RNNSTSPConfig:

    def __init__(self, in_size, h_size):
        self.n_input = in_size
        self.n_hidden = h_size
        self.exc_inh_prop = 0.8
        self.balance_EI = True
        self.synapse_config = 'exc_dep_inh_fac'
        self.membrane_time_constant = 100
        self.tau_fast = 200
        self.tau_slow = 1500
        self.dt = 10
        self.dt_sec = self.dt / 1000
        self.trial_length = 2500
        self.num_time_steps = self.trial_length // self.dt
        if self.exc_inh_prop < 1:
            self.EI = True
        else:
            self.EI = False
        self.num_exc_units = int(np.round(self.n_hidden * self.exc_inh_prop))
        self.num_inh_units = self.n_hidden - self.num_exc_units
        self.EI_list = np.ones(self.n_hidden, dtype=np.float32)
        self.EI_list[-self.num_inh_units:] = -1.0
        self.ind_inh = np.where(self.EI_list == -1)[0]
        self.EI_matrix = np.diag(self.EI_list)
        self.alpha_neuron = np.float32(self.dt) / self.membrane_time_constant
        self.h0 = 0.1 * np.ones((1, self.n_hidden), dtype=np.float32)
        self.w_in0 = initialize([self.n_input, self.n_hidden], shape=0.2,
            scale=1.0)
        if self.EI:
            self.w_rnn0 = initialize([self.n_hidden, self.n_hidden])
            if self.balance_EI:
                self.w_rnn0[:, self.ind_inh] = initialize([self.n_hidden,
                    self.num_inh_units], shape=0.2, scale=1.0)
                self.w_rnn0[self.ind_inh, :] = initialize([self.
                    num_inh_units, self.n_hidden], shape=0.2, scale=1.0)
        else:
            self.w_rnn0 = 0.54 * np.eye(self.n_hidden)
        self.b_rnn0 = np.zeros(self.n_hidden, dtype=np.float32)
        self.w_rnn_mask = np.ones_like(self.w_rnn0)
        if self.EI:
            self.w_rnn_mask = np.ones((self.n_hidden, self.n_hidden), dtype
                =np.float32) - np.eye(self.n_hidden, dtype=np.float32)
        self.w_rnn0 *= self.w_rnn_mask
        synaptic_configurations = {'full': [('facilitating' if i % 2 == 0 else
            'depressing') for i in range(self.n_hidden)], 'fac': [
            'facilitating' for i in range(self.n_hidden)], 'dep': [
            'depressing' for i in range(self.n_hidden)], 'exc_fac': [(
            'facilitating' if self.EI_list[i] == 1 else 'static') for i in
            range(self.n_hidden)], 'exc_dep': [('depressing' if self.
            EI_list[i] == 1 else 'static') for i in range(self.n_hidden)],
            'inh_fac': [('facilitating' if self.EI_list[i] == -1 else
            'static') for i in range(self.n_hidden)], 'inh_dep': [(
            'depressing' if self.EI_list[i] == -1 else 'static') for i in
            range(self.n_hidden)], 'exc_dep_inh_fac': [('depressing' if 
            self.EI_list[i] == 1 else 'facilitating') for i in range(self.
            n_hidden)]}
        self.alpha_stf = np.ones((1, self.n_hidden), dtype=np.float32)
        self.alpha_std = np.ones((1, self.n_hidden), dtype=np.float32)
        self.U = np.ones((1, self.n_hidden), dtype=np.float32)
        self.syn_x_init = np.ones((1, self.n_hidden), dtype=np.float32)
        self.syn_u_init = 0.3 * np.ones((1, self.n_hidden), dtype=np.float32)
        self.dynamic_synapse = np.ones((1, self.n_hidden), dtype=np.float32)
        for i in range(self.n_hidden):
            if self.synapse_config not in synaptic_configurations.keys():
                self.dynamic_synapse[0, i] = 0
            elif synaptic_configurations[self.synapse_config][i
                ] == 'facilitating':
                self.alpha_stf[0, i] = self.dt / self.tau_slow
                self.alpha_std[0, i] = self.dt / self.tau_fast
                self.U[0, i] = 0.15
                self.syn_u_init[0, i] = self.U[0, i]
                self.dynamic_synapse[0, i] = 1
            elif synaptic_configurations[self.synapse_config][i
                ] == 'depressing':
                self.alpha_stf[0, i] = self.dt / self.tau_fast
                self.alpha_std[0, i] = self.dt / self.tau_slow
                self.U[0, i] = 0.45
                self.syn_u_init[0, i] = self.U[0, i]
                self.dynamic_synapse[0, i] = 1


class RNNSTSPCell(nn.Module):

    def __init__(self, input_size, hidden_size, nonlinearity='relu'):
        super(RNNSTSPCell, self).__init__()
        self.syncfg = RNNSTSPConfig(input_size, hidden_size)
        self.input_size = self.syncfg.n_input
        self.hidden_size = self.syncfg.n_hidden
        self.nonlinearity = nonlinearity
        self.weight_ih = nn.Parameter(torch.from_numpy(self.syncfg.w_in0))
        self.weight_hh = nn.Parameter(torch.from_numpy(self.syncfg.w_rnn0))
        self.bias = nn.Parameter(torch.from_numpy(self.syncfg.b_rnn0))
        self.EI = self.syncfg.EI
        if self.EI:
            self.EI_matrix = torch.from_numpy(self.syncfg.EI_matrix)
        self.w_rnn_mask = torch.from_numpy(self.syncfg.w_rnn_mask)
        self.alpha_stf = torch.from_numpy(self.syncfg.alpha_stf)
        self.alpha_std = torch.from_numpy(self.syncfg.alpha_std)
        self.U = torch.from_numpy(self.syncfg.U)
        self.dynamic_synapse = torch.from_numpy(self.syncfg.dynamic_synapse)
        if self.nonlinearity == 'tanh':
            self.act = F.tanh
        elif self.nonlinearity == 'relu':
            self.act = F.relu
        else:
            raise RuntimeError('Unknown nonlinearity: {}'.format(self.
                nonlinearity))

    def forward(self, inp, hidden_in):
        h_in, syn_x, syn_u = hidden_in
        syn_x = syn_x + (self.alpha_std * (1.0 - syn_x) - self.syncfg.
            dt_sec * syn_u * syn_x * h_in) * self.dynamic_synapse
        syn_u = syn_u + (self.alpha_stf * (self.U - syn_u) + self.syncfg.
            dt_sec * self.U * (1.0 - syn_u) * h_in) * self.dynamic_synapse
        syn_x = torch.clamp(syn_x, min=0.0, max=1.0)
        syn_u = torch.clamp(syn_u, min=0.0, max=1.0)
        h_post = syn_u * syn_x * h_in
        if self.EI:
            eff_rnn_w = self.w_rnn_mask * torch.matmul(self.EI_matrix, F.
                relu(self.weight_hh))
        else:
            eff_rnn_w = self.w_rnn_mask * self.weight_hh
        h_out = h_in * (1 - self.syncfg.alpha_neuron
            ) + self.syncfg.alpha_neuron * self.act(torch.matmul(inp, F.
            relu(self.weight_ih)) + torch.matmul(h_post, eff_rnn_w) + self.bias
            )
        hidden_out = h_out, syn_x, syn_u
        return hidden_out

    def init_hidden(self, batch_s):
        h_out_init = torch.from_numpy(self.syncfg.h0).repeat(batch_s, 1)
        syn_x_init = torch.from_numpy(self.syncfg.syn_x_init).repeat(batch_s, 1
            )
        syn_u_init = torch.from_numpy(self.syncfg.syn_u_init).repeat(batch_s, 1
            )
        hidden_init = h_out_init, syn_x_init, syn_u_init
        return hidden_init


class RNNModel(nn.Module):

    def __init__(self, input_size, hidden_size, output_size, rnn_type):
        super(RNNModel, self).__init__()
        assert rnn_type in ['plainRNN', 'VanillaRNN', 'CTRNN', 'LSTM',
            'GRU', 'RNNSTSP'], 'Given RNN type must be implemented'
        self.hidden_size = hidden_size
        self.rnn_type = rnn_type
        if self.rnn_type == 'plainRNN':
            self.rnn = nn.RNNCell(input_size, hidden_size)
        elif self.rnn_type == 'VanillaRNN':
            self.rnn = VanillaRNNCell(input_size, hidden_size)
        elif self.rnn_type == 'CTRNN':
            self.rnn = VanillaRNNCell(input_size, hidden_size, ct=True)
        elif self.rnn_type == 'LSTM':
            self.rnn = nn.LSTMCell(input_size, hidden_size)
        elif self.rnn_type == 'GRU':
            self.rnn = nn.GRUCell(input_size, hidden_size)
        elif self.rnn_type == 'RNNSTSP':
            self.rnn = RNNSTSPCell(input_size, hidden_size)
        else:
            raise NotImplementedError('RNN cell not implemented')
        self.out_layer = nn.Linear(hidden_size, output_size)

    def forward(self, inp, hidden_in):
        hid_out = self.rnn(inp, hidden_in)
        if self.rnn_type in ['LSTM', 'RNNSTSP']:
            rnn_out = hid_out[0]
        else:
            rnn_out = hid_out
        otp = self.out_layer(rnn_out)
        return otp, hid_out

    def init_hidden(self, batch_s):
        if self.rnn_type == 'LSTM':
            init_hid = torch.zeros(batch_s, self.hidden_size), torch.zeros(
                batch_s, self.hidden_size)
        elif self.rnn_type in ['plainRNN', 'GRU']:
            init_hid = torch.zeros(batch_s, self.hidden_size)
        elif self.rnn_type in ['VanillaRNN', 'CTRNN', 'RNNSTSP']:
            init_hid = self.rnn.init_hidden(batch_s)
        else:
            raise NotImplementedError('RNN init not implemented')
        return init_hid


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


def get_init_inputs():
    return [[], {'input_size': 4, 'hidden_size': 4, 'output_size': 4,
        'rnn_type': 'plainRNN'}]

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
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_tanh_0(in_out_ptr0, in_ptr0, in_ptr1, in_ptr2,
    xnumel, XBLOCK: tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x0 = xindex % 4
    tmp0 = tl.load(in_out_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
    tmp3 = tl.load(in_ptr1 + x2, xmask)
    tmp4 = tl.load(in_ptr2 + x0, xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp5 = tmp3 + tmp4
    tmp6 = tmp2 + tmp5
    tmp7 = libdevice.tanh(tmp6)
    tl.store(in_out_ptr0 + x2, tmp7, xmask)


def call(args):
    (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
        primals_7, primals_8) = 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, 4), (4, 1))
    assert_size_stride(primals_4, (4, 4), (4, 1))
    assert_size_stride(primals_5, (4,), (1,))
    assert_size_stride(primals_6, (4,), (1,))
    assert_size_stride(primals_7, (4, 4), (4, 1))
    assert_size_stride(primals_8, (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, reinterpret_tensor(primals_4, (4, 4),
            (1, 4), 0), out=buf0)
        del primals_4
        buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        extern_kernels.mm(primals_1, reinterpret_tensor(primals_3, (4, 4),
            (1, 4), 0), out=buf1)
        del primals_3
        buf2 = buf0
        del buf0
        get_raw_stream(0)
        triton_poi_fused_add_tanh_0[grid(16)](buf2, primals_6, buf1,
            primals_5, 16, XBLOCK=16, num_warps=1, num_stages=1)
        del primals_5
        del primals_6
        buf3 = buf1
        del buf1
        extern_kernels.addmm(primals_8, buf2, reinterpret_tensor(primals_7,
            (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf3)
        del primals_8
    return buf3, buf2, primals_1, primals_2, buf2, primals_7


def initialize(dims, connection_prob=1.0, shape=0.1, scale=1.0):
    w = np.random.gamma(shape, scale, size=dims)
    w *= np.random.rand(*dims) < connection_prob
    return np.float32(w)


class VanillaRNNCell(nn.Module):

    def __init__(self, input_size, hidden_size, nonlinearity='tanh', ct=False):
        super(VanillaRNNCell, self).__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.nonlinearity = nonlinearity
        self.ct = ct
        self.weight_ih = nn.Parameter(torch.zeros((input_size, hidden_size)))
        self.weight_hh = nn.Parameter(torch.zeros((hidden_size, hidden_size)))
        self.bias = nn.Parameter(torch.zeros(hidden_size))
        self.reset_parameters()
        if self.nonlinearity == 'tanh':
            self.act = F.tanh
        elif self.nonlinearity == 'relu':
            self.act = F.relu
        else:
            raise RuntimeError('Unknown nonlinearity: {}'.format(self.
                nonlinearity))

    def reset_parameters(self):
        stdv = 1.0 / math.sqrt(self.hidden_size)
        for weight in self.parameters():
            nn.init.uniform_(weight, -stdv, stdv)

    def forward(self, inp, hidden_in):
        if not self.ct:
            hidden_out = self.act(torch.matmul(inp, self.weight_ih) + torch
                .matmul(hidden_in, self.weight_hh) + self.bias)
        else:
            alpha = 0.1
            hidden_out = (1 - alpha) * hidden_in + alpha * self.act(torch.
                matmul(inp, self.weight_ih) + torch.matmul(hidden_in, self.
                weight_hh) + self.bias)
        return hidden_out

    def init_hidden(self, batch_s):
        return torch.zeros(batch_s, self.hidden_size)


class RNNSTSPConfig:

    def __init__(self, in_size, h_size):
        self.n_input = in_size
        self.n_hidden = h_size
        self.exc_inh_prop = 0.8
        self.balance_EI = True
        self.synapse_config = 'exc_dep_inh_fac'
        self.membrane_time_constant = 100
        self.tau_fast = 200
        self.tau_slow = 1500
        self.dt = 10
        self.dt_sec = self.dt / 1000
        self.trial_length = 2500
        self.num_time_steps = self.trial_length // self.dt
        if self.exc_inh_prop < 1:
            self.EI = True
        else:
            self.EI = False
        self.num_exc_units = int(np.round(self.n_hidden * self.exc_inh_prop))
        self.num_inh_units = self.n_hidden - self.num_exc_units
        self.EI_list = np.ones(self.n_hidden, dtype=np.float32)
        self.EI_list[-self.num_inh_units:] = -1.0
        self.ind_inh = np.where(self.EI_list == -1)[0]
        self.EI_matrix = np.diag(self.EI_list)
        self.alpha_neuron = np.float32(self.dt) / self.membrane_time_constant
        self.h0 = 0.1 * np.ones((1, self.n_hidden), dtype=np.float32)
        self.w_in0 = initialize([self.n_input, self.n_hidden], shape=0.2,
            scale=1.0)
        if self.EI:
            self.w_rnn0 = initialize([self.n_hidden, self.n_hidden])
            if self.balance_EI:
                self.w_rnn0[:, self.ind_inh] = initialize([self.n_hidden,
                    self.num_inh_units], shape=0.2, scale=1.0)
                self.w_rnn0[self.ind_inh, :] = initialize([self.
                    num_inh_units, self.n_hidden], shape=0.2, scale=1.0)
        else:
            self.w_rnn0 = 0.54 * np.eye(self.n_hidden)
        self.b_rnn0 = np.zeros(self.n_hidden, dtype=np.float32)
        self.w_rnn_mask = np.ones_like(self.w_rnn0)
        if self.EI:
            self.w_rnn_mask = np.ones((self.n_hidden, self.n_hidden), dtype
                =np.float32) - np.eye(self.n_hidden, dtype=np.float32)
        self.w_rnn0 *= self.w_rnn_mask
        synaptic_configurations = {'full': [('facilitating' if i % 2 == 0 else
            'depressing') for i in range(self.n_hidden)], 'fac': [
            'facilitating' for i in range(self.n_hidden)], 'dep': [
            'depressing' for i in range(self.n_hidden)], 'exc_fac': [(
            'facilitating' if self.EI_list[i] == 1 else 'static') for i in
            range(self.n_hidden)], 'exc_dep': [('depressing' if self.
            EI_list[i] == 1 else 'static') for i in range(self.n_hidden)],
            'inh_fac': [('facilitating' if self.EI_list[i] == -1 else
            'static') for i in range(self.n_hidden)], 'inh_dep': [(
            'depressing' if self.EI_list[i] == -1 else 'static') for i in
            range(self.n_hidden)], 'exc_dep_inh_fac': [('depressing' if 
            self.EI_list[i] == 1 else 'facilitating') for i in range(self.
            n_hidden)]}
        self.alpha_stf = np.ones((1, self.n_hidden), dtype=np.float32)
        self.alpha_std = np.ones((1, self.n_hidden), dtype=np.float32)
        self.U = np.ones((1, self.n_hidden), dtype=np.float32)
        self.syn_x_init = np.ones((1, self.n_hidden), dtype=np.float32)
        self.syn_u_init = 0.3 * np.ones((1, self.n_hidden), dtype=np.float32)
        self.dynamic_synapse = np.ones((1, self.n_hidden), dtype=np.float32)
        for i in range(self.n_hidden):
            if self.synapse_config not in synaptic_configurations.keys():
                self.dynamic_synapse[0, i] = 0
            elif synaptic_configurations[self.synapse_config][i
                ] == 'facilitating':
                self.alpha_stf[0, i] = self.dt / self.tau_slow
                self.alpha_std[0, i] = self.dt / self.tau_fast
                self.U[0, i] = 0.15
                self.syn_u_init[0, i] = self.U[0, i]
                self.dynamic_synapse[0, i] = 1
            elif synaptic_configurations[self.synapse_config][i
                ] == 'depressing':
                self.alpha_stf[0, i] = self.dt / self.tau_fast
                self.alpha_std[0, i] = self.dt / self.tau_slow
                self.U[0, i] = 0.45
                self.syn_u_init[0, i] = self.U[0, i]
                self.dynamic_synapse[0, i] = 1


class RNNSTSPCell(nn.Module):

    def __init__(self, input_size, hidden_size, nonlinearity='relu'):
        super(RNNSTSPCell, self).__init__()
        self.syncfg = RNNSTSPConfig(input_size, hidden_size)
        self.input_size = self.syncfg.n_input
        self.hidden_size = self.syncfg.n_hidden
        self.nonlinearity = nonlinearity
        self.weight_ih = nn.Parameter(torch.from_numpy(self.syncfg.w_in0))
        self.weight_hh = nn.Parameter(torch.from_numpy(self.syncfg.w_rnn0))
        self.bias = nn.Parameter(torch.from_numpy(self.syncfg.b_rnn0))
        self.EI = self.syncfg.EI
        if self.EI:
            self.EI_matrix = torch.from_numpy(self.syncfg.EI_matrix)
        self.w_rnn_mask = torch.from_numpy(self.syncfg.w_rnn_mask)
        self.alpha_stf = torch.from_numpy(self.syncfg.alpha_stf)
        self.alpha_std = torch.from_numpy(self.syncfg.alpha_std)
        self.U = torch.from_numpy(self.syncfg.U)
        self.dynamic_synapse = torch.from_numpy(self.syncfg.dynamic_synapse)
        if self.nonlinearity == 'tanh':
            self.act = F.tanh
        elif self.nonlinearity == 'relu':
            self.act = F.relu
        else:
            raise RuntimeError('Unknown nonlinearity: {}'.format(self.
                nonlinearity))

    def forward(self, inp, hidden_in):
        h_in, syn_x, syn_u = hidden_in
        syn_x = syn_x + (self.alpha_std * (1.0 - syn_x) - self.syncfg.
            dt_sec * syn_u * syn_x * h_in) * self.dynamic_synapse
        syn_u = syn_u + (self.alpha_stf * (self.U - syn_u) + self.syncfg.
            dt_sec * self.U * (1.0 - syn_u) * h_in) * self.dynamic_synapse
        syn_x = torch.clamp(syn_x, min=0.0, max=1.0)
        syn_u = torch.clamp(syn_u, min=0.0, max=1.0)
        h_post = syn_u * syn_x * h_in
        if self.EI:
            eff_rnn_w = self.w_rnn_mask * torch.matmul(self.EI_matrix, F.
                relu(self.weight_hh))
        else:
            eff_rnn_w = self.w_rnn_mask * self.weight_hh
        h_out = h_in * (1 - self.syncfg.alpha_neuron
            ) + self.syncfg.alpha_neuron * self.act(torch.matmul(inp, F.
            relu(self.weight_ih)) + torch.matmul(h_post, eff_rnn_w) + self.bias
            )
        hidden_out = h_out, syn_x, syn_u
        return hidden_out

    def init_hidden(self, batch_s):
        h_out_init = torch.from_numpy(self.syncfg.h0).repeat(batch_s, 1)
        syn_x_init = torch.from_numpy(self.syncfg.syn_x_init).repeat(batch_s, 1
            )
        syn_u_init = torch.from_numpy(self.syncfg.syn_u_init).repeat(batch_s, 1
            )
        hidden_init = h_out_init, syn_x_init, syn_u_init
        return hidden_init


class RNNModelNew(nn.Module):

    def __init__(self, input_size, hidden_size, output_size, rnn_type):
        super(RNNModelNew, self).__init__()
        assert rnn_type in ['plainRNN', 'VanillaRNN', 'CTRNN', 'LSTM',
            'GRU', 'RNNSTSP'], 'Given RNN type must be implemented'
        self.hidden_size = hidden_size
        self.rnn_type = rnn_type
        if self.rnn_type == 'plainRNN':
            self.rnn = nn.RNNCell(input_size, hidden_size)
        elif self.rnn_type == 'VanillaRNN':
            self.rnn = VanillaRNNCell(input_size, hidden_size)
        elif self.rnn_type == 'CTRNN':
            self.rnn = VanillaRNNCell(input_size, hidden_size, ct=True)
        elif self.rnn_type == 'LSTM':
            self.rnn = nn.LSTMCell(input_size, hidden_size)
        elif self.rnn_type == 'GRU':
            self.rnn = nn.GRUCell(input_size, hidden_size)
        elif self.rnn_type == 'RNNSTSP':
            self.rnn = RNNSTSPCell(input_size, hidden_size)
        else:
            raise NotImplementedError('RNN cell not implemented')
        self.out_layer = nn.Linear(hidden_size, output_size)

    def init_hidden(self, batch_s):
        if self.rnn_type == 'LSTM':
            init_hid = torch.zeros(batch_s, self.hidden_size), torch.zeros(
                batch_s, self.hidden_size)
        elif self.rnn_type in ['plainRNN', 'GRU']:
            init_hid = torch.zeros(batch_s, self.hidden_size)
        elif self.rnn_type in ['VanillaRNN', 'CTRNN', 'RNNSTSP']:
            init_hid = self.rnn.init_hidden(batch_s)
        else:
            raise NotImplementedError('RNN init not implemented')
        return init_hid

    def forward(self, input_0, input_1):
        primals_1 = self.rnn.weight_ih
        primals_2 = self.rnn.weight_hh
        primals_5 = self.rnn.bias_ih
        primals_6 = self.rnn.bias_hh
        primals_3 = self.out_layer.weight
        primals_8 = self.out_layer.bias
        primals_4 = input_0
        primals_7 = input_1
        output = call([primals_1, primals_2, primals_3, primals_4,
            primals_5, primals_6, primals_7, primals_8])
        return output[0], output[1]
