id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
7,570
import numpy as np import torch import torch.nn as nn def combined_shape(length, shape=None): if shape is None: return (length,) return (length, shape) if np.isscalar(shape) else (length, *shape)
null
7,571
import numpy as np import torch import torch.nn as nn def mlp(sizes, activation, output_activation=nn.Identity): layers = [] for j in range(len(sizes)-1): act = activation if j < len(sizes)-2 else output_activation layers += [nn.Linear(sizes[j], sizes[j+1]), act()] return nn.Sequential(*lay...
null
7,572
import numpy as np import torch import torch.nn as nn def count_vars(module): return sum([np.prod(p.shape) for p in module.parameters()])
null
7,573
from copy import deepcopy import itertools import numpy as np import random import torch import torch.nn as nn from torch.optim import Adam import gym import pickle import os from spikingjelly.activation_based import functional from replay_buffer_norm import ReplayBuffer from ilcsan import PopSpikeActor from core_cuda ...
null
7,574
import gym import math import random import numpy as np from collections import namedtuple from itertools import count import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torchvision.transforms as T from torch.utils.tensorboard import SummaryWriter import argparse def ...
null
7,575
import gym import math import random import numpy as np from collections import namedtuple from itertools import count import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torchvision.transforms as T from torch.utils.tensorboard import SummaryWriter import argparse def ...
null
7,576
import gym import math import random import numpy as np from collections import namedtuple from itertools import count import matplotlib import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from spikingjelly.activation_based import monitor, neuro...
null
7,577
import gym import math import random import numpy as np from collections import namedtuple from itertools import count import matplotlib import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from spikingjelly.activation_based import monitor, neuro...
null
7,578
import torch import torch.nn as nn from spikingjelly.activation_based import neuron, layer, learning from matplotlib import pyplot as plt torch.manual_seed(0) def f_weight(x): return torch.clamp(x, -1, 1.)
null
7,581
import torch from torch import Tensor, nn from torch.optim import Adam from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter import torchvision.transforms from torchaudio.transforms import Spectrogram from spikingjelly.activation_based import neuron, surrogate from spikingjelly.datas...
null
7,582
import torch from torch import Tensor, nn from torch.optim import Adam from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter import torchvision.transforms from torchaudio.transforms import Spectrogram from spikingjelly.activation_based import neuron, surrogate from spikingjelly.datas...
null
7,583
import numpy as np from multiprocessing import Process, Pipe def worker(remote, parent_remote, env_fn_wrapper): parent_remote.close() env = env_fn_wrapper.x() while True: cmd, data = remote.recv() if cmd == 'step': ob, reward, done, info = env.step(data) if done: ...
null
7,584
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from spikingjelly.activation_based import rnn import matplotlib.pyplot as plt import matplotlib.ticker as ticker import glob import unicodedata import string import random import time import math def findFiles(path): return g...
null
7,585
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from spikingjelly.activation_based import rnn import matplotlib.pyplot as plt import matplotlib.ticker as ticker import glob import unicodedata import string import random import time import math if __name__ == '__main__': all_let...
null
7,586
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from spikingjelly.activation_based import rnn import matplotlib.pyplot as plt import matplotlib.ticker as ticker import glob import unicodedata import string import random import time import math def categoryFromOutput(output): ...
null
7,587
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from spikingjelly.activation_based import rnn import matplotlib.pyplot as plt import matplotlib.ticker as ticker import glob import unicodedata import string import random import time import math if __name__ == '__main__': all_let...
Args: sampleSource: 'train', 'test', 'all' Returns: category, line, category_tensor, line_tensor
7,588
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from spikingjelly.activation_based import rnn import matplotlib.pyplot as plt import matplotlib.ticker as ticker import glob import unicodedata import string import random import time import math def timeSince(since): now = t...
null
7,589
import gym import math import random import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.distributions import Categorical from torch.utils.tensorboard import SummaryWriter from spikingjelly.activation_based.examples.common.multiprocessing_env impo...
null
7,590
import gym import math import random import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.distributions import Categorical from torch.utils.tensorboard import SummaryWriter from spikingjelly.activation_based.examples.common.multiprocessing_env impo...
null
7,591
import gym import math import random import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.distributions import Categorical from torch.utils.tensorboard import SummaryWriter from spikingjelly.activation_based.examples.common.multiprocessing_env impo...
null
7,594
from copy import deepcopy import itertools import numpy as np import random import gym import pickle import os import torch import torch.nn as nn from torch.optim import Adam from spikingjelly.activation_based import functional from replay_buffer_norm import ReplayBuffer from noisysan import NoisyPopSpikeActor from cor...
null
7,595
import numpy as np import torch import torch.nn as nn from spikingjelly.activation_based import neuron, layer, learning from matplotlib import pyplot as plt def f_pre(x, w_min, alpha=0.): return (x - w_min) ** alpha
null
7,596
import numpy as np import torch import torch.nn as nn from spikingjelly.activation_based import neuron, layer, learning from matplotlib import pyplot as plt def f_post(x, w_max, alpha=0.): return (w_max - x) ** alpha
null
7,597
import ptan import argparse, os from itertools import count import numpy as np import torch import torch.optim as optim from spikingjelly.activation_based import functional from tensorboardX import SummaryWriter from utils import model, common, atari_wrappers def make_env(params): env = atari_wrappers.make_atari(p...
null
7,598
import ptan import argparse, os from itertools import count import numpy as np import torch import torch.optim as optim from spikingjelly.activation_based import functional from tensorboardX import SummaryWriter from utils import model, common, atari_wrappers def make_test_env(params): env = atari_wrappers.make_at...
null
7,599
import ptan import argparse, os from itertools import count import numpy as np import torch import torch.optim as optim from spikingjelly.activation_based import functional from tensorboardX import SummaryWriter from utils import model, common, atari_wrappers EVAL_LEN = 125000 def eval_Q(env, net, cuda): device = ...
null
7,600
import sys import time import numpy as np import torch import torch.nn as nn def unpack_batch(batch): states, actions, rewards, dones, last_states = [], [], [], [], [] for exp in batch: state = np.array(exp.state, copy=False) states.append(state) actions.append(exp.action) reward...
null
7,601
import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.cpp_extension import load_inline from torch.cuda.amp import custom_fwd, custom_bwd import logging from . import tensor_cache from torch import Tensor from typing import Optional, Union from torch.types import _int, _size from torch.nn.m...
* :ref:`API in English <spike_linear-en>` .. _spike_linear-cn: :class:`torch.nn.functional.linear` 在输入为脉冲时的特例。 .. note:: 在CUDA设备上训练时拥有比 :class:`torch.nn.functional.linear` 更低的显存消耗。 .. warning:: `spike` 中的任何元素都必须为0或1。 * :ref:`中文API <spike_linear-cn>` .. _spike_linear-en: A specific case of :class:`torch.nn.functional.li...
7,602
import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.cpp_extension import load_inline from torch.cuda.amp import custom_fwd, custom_bwd import logging from . import tensor_cache from torch import Tensor from typing import Optional, Union from torch.types import _int, _size from torch.nn.m...
* :ref:`API in English <spike_conv1d-en>` .. _spike_conv1d-cn: :class:`torch.nn.functional.conv1d` 在输入为脉冲时的特例。 .. note:: 在CUDA设备上训练时拥有比 :class:`torch.nn.functional.conv1d` 更低的显存消耗。 .. warning:: `spike` 中的任何元素都必须为0或1。 * :ref:`中文API <spike_conv1d-cn>` .. _spike_conv1d-en: A specific case of :class:`torch.nn.functional.co...
7,603
import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.cpp_extension import load_inline from torch.cuda.amp import custom_fwd, custom_bwd import logging from . import tensor_cache from torch import Tensor from typing import Optional, Union from torch.types import _int, _size from torch.nn.m...
* :ref:`API in English <spike_conv2d-en>` .. _spike_conv2d-cn: :class:`torch.nn.functional.conv2d` 在输入为脉冲时的特例。 .. note:: 在CUDA设备上训练时拥有比 :class:`torch.nn.functional.conv2d` 更低的显存消耗。 .. warning:: `spike` 中的任何元素都必须为0或1。 * :ref:`中文API <spike_conv2d-cn>` .. _spike_conv2d-en: A specific case of :class:`torch.nn.functional.co...
7,604
import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.cpp_extension import load_inline from torch.cuda.amp import custom_fwd, custom_bwd import logging from . import tensor_cache from torch import Tensor from typing import Optional, Union from torch.types import _int, _size from torch.nn.m...
* :ref:`API in English <spike_conv3d-en>` .. _spike_conv3d-cn: :class:`torch.nn.functional.conv3d` 在输入为脉冲时的特例。 .. note:: 在CUDA设备上训练时拥有比 :class:`torch.nn.functional.conv3d` 更低的显存消耗。 .. warning:: `spike` 中的任何元素都必须为0或1。 * :ref:`中文API <spike_conv3d-cn>` .. _spike_conv3d-en: A specific case of :class:`torch.nn.functional.co...
7,605
import torch import numpy as np from torch import nn from typing import Callable, Any from spikingjelly.activation_based import neuron import threading from torch.utils.tensorboard import SummaryWriter import os import time import re import datetime def unpack_len1_tuple(x: tuple or torch.Tensor): if isinstance(x,...
null
7,606
import torch import torch.nn.functional as F import threading from .. import configure from . import cuda_utils import logging try: import cupy except BaseException as e: logging.info(f'spikingjelly.activation_based.tensor_cache: {e}') cupy = None class DataTypeConvertCUDACode: float2bool = r''' ext...
:param spike: a spike tensor whose ``dtype=torch.float`` or ``dtype=torch.half`` and all elements are 0 or 1 :type spike: torch.Tensor :return: (spike_b, s_dtype, s_shape, s_padding) spike_b: a compressed spike tensor with ``dtype=torch.uint8`` and each element stores 8 spikes s_dtype: the dtype of the original spike s...
7,607
import torch import torch.nn.functional as F import threading from .. import configure from . import cuda_utils import logging try: import cupy except BaseException as e: logging.info(f'spikingjelly.activation_based.tensor_cache: {e}') cupy = None class DataTypeConvertCUDACode: float2bool = r''' ext...
:param spike_b: a compressed spike tensor with ``dtype=torch.uint8`` and each element stores 8 spikes :type spike_b: torch.Tensor :param s_dtype: the dtype of the original spike :type s_dtype: torch.dtype :param s_shape: the shape of the original spike :type s_shape: torch.Size :param s_padding: the number of padding e...
7,608
import torch import torch.nn.functional as F import threading from .. import configure from . import cuda_utils import logging def tensor_key(x: torch.Tensor): x = x.flatten() return x.data_ptr(), x[-1].data_ptr(), x.numel()
null
7,609
from spikingjelly.activation_based.auto_cuda.generator import analyse_graph, gen_forward_codes, gen_backward_codes from spikingjelly.activation_based import surrogate import torch def lif_charge(x: torch.Tensor, v_last: torch.Tensor, tau: float, v_reset: float): h = v_last + (x - (v_last - v_reset)) / tau ...
null
7,610
import logging import torch import torch.nn as nn import torch.nn.functional as F import re import sys import copy from typing import Callable import numpy as np class VarNode: def __init__(self, prefix: str, name: str, instance: object, value=None): self.debug_name = name # 原始的name形如 %8, v_last.1 ...
null
7,611
import logging import torch import torch.nn as nn import torch.nn.functional as F import re import sys import copy from typing import Callable import numpy as np def hash_str(x: object): def gen_forward_codes(input_nodes: dict, inter_nodes: dict, output_nodes: dict, cmds: list, hard_reset: bool): # 暂时只支持单个输出 a...
null
7,612
import logging import torch import torch.nn as nn import torch.nn.functional as F import re import sys import copy from typing import Callable import numpy as np def hash_str(x: object): hash_code = hash(x) if hash_code < 0: return f'_{-hash_code}' else: return hash_code The provided code s...
用户定义的前向传播函数为 h_seq[t] = fun(x_seq[t], v_v_seq[t], ...) 需要计算出 h_seq[t] -> x_seq[t] 的梯度和 h_seq[t] -> v_v_seq[t]的梯度 还需要考虑 ... 中如果有tensor,可以增加flag,决定是否计算h_seq[t]对其的梯度
7,613
import torch import torch.nn.functional as F import numpy as np import logging from .. import cuda_utils, surrogate from ... import configure from typing import Callable, Iterable from . import base, cfunction import math def if_requires_grad(items: Iterable): requires_grad = False for item in items: i...
null
7,614
import torch import torch.nn.functional as F import numpy as np import logging try: import cupy except BaseException as e: logging.info(f'spikingjelly.activation_based.auto_cuda.ss_neuronal_kernel: {e}') cupy = None from .. import cuda_utils, surrogate from ... import configure from typing import Callable, ...
null
7,615
import torch import torch.nn.functional as F import numpy as np import logging from .. import cuda_utils, surrogate from ... import configure from typing import Callable, Iterable from . import base, cfunction import math def new_tensors(news: tuple, py_dict: dict, ref: str = 'x'): ref = py_dict[ref] zero_shap...
null
7,616
import torch import torch.nn.functional as F import numpy as np import logging from .. import cuda_utils, surrogate from ... import configure from typing import Callable, Iterable from . import base, cfunction import math def neuronal_hard_reset(v_next: str, h: str, spike: str, v_reset: str, dtype: str = 'float'): ...
null
7,617
import torch import torch.nn.functional as F import numpy as np import logging from .. import cuda_utils, surrogate from ... import configure from typing import Callable, Iterable from . import base, cfunction import math def neuronal_soft_reset(v_next: str, h: str, spike: str, v_th: str, dtype: str = 'float'): if...
null
7,618
import torch import torch.nn.functional as F import numpy as np import logging from .. import cuda_utils, surrogate from ... import configure from typing import Callable, Iterable from . import base, cfunction import math def neuronal_fire(spike: str, v: str, v_th: str, dtype: str = 'float'): if dtype == 'float': ...
null
7,619
def wrap_return_codes(y: str or None, codes: str): if y is None: return f'({codes})' else: return f'{y} = {codes};' def float2half2(y: str or None, x: str): codes = f'__float2half2_rn({x})' return wrap_return_codes(y, codes)
null
7,620
def wrap_return_codes(y: str or None, codes: str): if y is None: return f'({codes})' else: return f'{y} = {codes};' def maximum(z: str or None, x: str, y: str, dtype: str): if dtype == 'float': codes = f'max({x}, {y})' elif dtype == 'half2': codes = f'__hmax2({x}, {y})' ...
null
7,621
def wrap_return_codes(y: str or None, codes: str): if y is None: return f'({codes})' else: return f'{y} = {codes};' def neg(y: str or None, x: str, dtype: str): if dtype == 'float': codes = f'- {x}' elif dtype == 'half2': codes = f'__hneg2({x})' else: raise N...
null
7,622
def wrap_return_codes(y: str or None, codes: str): if y is None: return f'({codes})' else: return f'{y} = {codes};' def exp(y: str or None, x: str, dtype: str): if dtype == 'float': codes = f'expf({x})' elif dtype == 'half2': codes = f'h2exp({x})' else: raise...
null
7,623
def constant(y: str or None, x: float, dtype: str): def atan_backward(y: str, x: str, alpha: float, dtype: str): assert y is not None alpha = constant(None, alpha, dtype) if dtype == 'float': codes = f'const float atan_backward__alpha_x = ((float) 1.57079632679489661923) * {alpha} * {x};' c...
null
7,624
def constant(y: str or None, x: float, dtype: str): def abs(y: str or None, x: str, dtype: str): def if_else(z: str or None, x: str, y: str, mask: str, dtype: str): def greater_equal(z: str or None, x: str, y: str, dtype: str): def piecewise_leaky_relu_backward(y: str, x: str, w: float, c: float, dtype: str): asse...
null
7,625
def constant(y: str or None, x: float, dtype: str): if dtype == 'float': codes = f'{x}f' elif dtype == 'half2': codes = f'__float2half2_rn({x}f)' else: raise NotImplementedError(dtype) return wrap_return_codes(y, codes) def if_else(z: str or None, x: str, y: str, mask: str, dtype...
null
7,626
def constant(y: str or None, x: float, dtype: str): if dtype == 'float': codes = f'{x}f' elif dtype == 'half2': codes = f'__float2half2_rn({x}f)' else: raise NotImplementedError(dtype) return wrap_return_codes(y, codes) def power(z: str or None, x: str, y: str, dtype: str): i...
null
7,627
def constant(y: str or None, x: float, dtype: str): if dtype == 'float': codes = f'{x}f' elif dtype == 'half2': codes = f'__float2half2_rn({x}f)' else: raise NotImplementedError(dtype) return wrap_return_codes(y, codes) def if_else(z: str or None, x: str, y: str, mask: str, dtype...
null
7,628
def constant(y: str or None, x: float, dtype: str): if dtype == 'float': codes = f'{x}f' elif dtype == 'half2': codes = f'__float2half2_rn({x}f)' else: raise NotImplementedError(dtype) return wrap_return_codes(y, codes) def greater_equal(z: str or None, x: str, y: str, dtype: str...
null
7,629
def constant(y: str or None, x: float, dtype: str): if dtype == 'float': codes = f'{x}f' elif dtype == 'half2': codes = f'__float2half2_rn({x}f)' else: raise NotImplementedError(dtype) return wrap_return_codes(y, codes) def if_else_else(w: str or None, x: str, y: str, z: str, mas...
null
7,634
import torch import torch.nn.functional as F import numpy as np import logging try: import cupy except BaseException as e: logging.info(f'spikingjelly.activation_based.auto_cuda.neuronal_kernel: {e}') cupy = None from .. import cuda_utils, surrogate from ... import configure from typing import Callable, Ite...
null
7,635
import torch import torch.nn.functional as F import numpy as np import logging from .. import cuda_utils, surrogate from ... import configure from typing import Callable, Iterable from . import base, cfunction import math def new_tensors(news: tuple, py_dict: dict, ref: str = 'x_seq'): ref = py_dict[ref] zero_...
null
7,636
import numpy as np import logging import torch import torch.nn.functional as F import sys import logging from .. import cuda_utils from ... import configure def wrap_with_comment(code: str, comment: str): if logging.DEBUG >= logging.root.level: return '\n//------' + comment + ' start------\n' + code + '\n/...
null
7,637
import numpy as np import logging import torch import torch.nn.functional as F import sys import logging from .. import cuda_utils from ... import configure def startswiths(x: str, prefixes: tuple): ret = False for prefix in prefixes: if x.startswith(prefix): ret = True return ret
null
7,638
import torch import torch.nn as nn import torch.nn.functional as F from spikingjelly.activation_based import surrogate, layer import math def directional_rnn_cell_forward(cell: nn.Module, x: torch.Tensor, states: torch.Tensor): T = x.shape[0] ss = states output = [] ...
null
7,639
import torch import torch.nn as nn import torch.nn.functional as F from spikingjelly.activation_based import surrogate, layer import math The provided code snippet includes necessary dependencies for implementing the `bidirectional_rnn_cell_forward` function. Write a Python function `def bidirectional_rnn_cell_forward...
:param cell: 正向RNN cell,输入是正向序列 :type cell: nn.Module :param cell_reverse: 反向的RNN cell,输入是反向序列 :type cell_reverse: nn.Module :param x: ``shape = [T, batch_size, input_size]`` 的输入 :type x: torch.Tensor :param states: 正向RNN cell的起始状态 若RNN cell只有单个隐藏状态,则 ``shape = [batch_size, hidden_size]`` ; 否则 ``shape = [states_num, ba...
7,640
import logging import torch import time import numpy as np from .. import configure from typing import Callable def cpu_timer(f: Callable, *args, **kwargs): """ * :ref:`API in English <cpu_timer-en>` .. _cpu_timer-cn: 计算在CPU上执行 ``f(*args, **kwargs)`` 所需的时间 :param f: 函数 :type f: Callable :ret...
* :ref:`API in English <cal_fun_t-en>` .. _cal_fun_t-cn: 测量在 ``device`` 上执行 ``n`` 次 ``f(*args, **kwargs)`` 的平均用时 .. note:: 当 ``n > 1`` 时,实际上会执行 ``2n`` 次,然后返回后 ``n`` 次的平均用时,以减小误差。 :param n: 重复的次数 :type n: int :param device: ``f`` 执行的设备,可以为 'cpu' 或CUDA设备 :type device: str or torch.device or int :param f: 函数 :type f: Call...
7,641
from abc import abstractmethod from typing import Callable import torch import torch.nn as nn import torch.nn.functional as F import math import numpy as np import logging from . import surrogate, base from .auto_cuda import neuron_kernel as ac_neuron_kernel from .auto_cuda import ss_neuron_kernel as ss_ac_neuron_kerne...
Gaussian (1/f)**beta noise. Based on the algorithm in: Timmer, J. and Koenig, M.: On generating power law noise. Astron. Astrophys. 300, 707-710 (1995) Normalised to unit variance Parameters: ----------- exponent : float The power-spectrum of the generated noise is proportional to S(f) = (1 / f)**beta flicker / pink no...
7,642
import logging import copy import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Callable from . import neuron, base from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `set_backend` function. Write a Python function `def s...
* :ref:`API in English <set_backend-en>` .. _set_backend-cn: :param net: 一个神经网络 :type net: nn.Module :param backend: 使用哪个后端 :type backend: str :param instance: 类型为 ``instance`` 的模块后端会被改变 :type instance: nn.Module or tuple[nn.Module] :return: None 将 ``net`` 中 所有类型为 ``instance`` 的模块后端更改为 ``backend`` * :ref:`中文 API <set_b...
7,643
import logging import copy import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Callable from . import neuron, base from torch import Tensor def kernel_dot_product(x: Tensor, y: Tensor, kernel='linear', *args): """ * :ref:`API in English <kernel_dot_product-en>` ...
* :ref:`API in English <spike_similar_loss-en>` .. _spike_similar_loss-cn: :param spikes: shape=[N, M, T],N个数据生成的脉冲 :param labels: shape=[N, C],N个数据的标签,\ ``labels[i][k] == 1``\ 表示数据i属于第k类,反之亦然,允许多标签 :param str kernel_type: 使用内积来衡量两个脉冲之间的相似性,\ ``kernel_type``\ 是计算内积时,所使用的核函数种类 :param str loss_type: 返回哪种损失,可以为'mse', 'l1'...
7,644
import logging import copy import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Callable from . import neuron, base from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `set_threshold_margin` function. Write a Python functi...
* :ref:`API in English <set_threshold_margin-en>` .. _set_threshold_margin-cn: :param output_layer: 用于分类的网络的输出层,输出层输出shape=[batch_size, C] :param label_one_hot: one hot格式的样本标签,shape=[batch_size, C] :param float eval_threshold: 输出层神经元在测试(推理)时使用的电压阈值 :param float threshold0: 输出层神经元在训练时,负样本的电压阈值 :param float threshold1: 输...
7,645
import logging import copy import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Callable from . import neuron, base from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `redundant_one_hot` function. Write a Python function ...
* :ref:`API in English <redundant_one_hot-en>` .. _redundant_one_hot-cn: :param labels: shape=[batch_size]的tensor,表示\ ``batch_size``\ 个标签 :param int num_classes: 类别总数 :param int n: 表示每个类别所用的编码数量 :return: shape=[batch_size, num_classes * n]的tensor 对数据进行冗余的one-hot编码,每一类用 ``n`` 个1和 ``(num_classes - 1) * n`` 个0来编码。 示例: .. ...
7,646
import logging import copy import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Callable from . import neuron, base from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `first_spike_index` function. Write a Python function ...
* :ref:`API in English <first_spike_index-en>` .. _first_spike_index-cn: :param spikes: shape=[*, T],表示任意个神经元在t=0, 1, ..., T-1,共T个时刻的输出脉冲 :return: index, shape=[*, T],为 ``True`` 的位置表示该神经元首次释放脉冲的时刻 输入若干个神经元的输出脉冲,返回一个与输入相同shape的 ``bool`` 类型的index。index为 ``True`` 的位置,表示该神经元首次释放脉冲的时刻。 示例: .. code-block:: python >>> spikes ...
7,647
import logging import copy import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Callable from . import neuron, base from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `multi_step_forward` function. Write a Python function...
* :ref:`API in English <multi_step_forward-en>` .. _multi_step_forward-cn: :param x_seq: ``shape=[T, batch_size, ...]`` 的输入tensor :type x_seq: Tensor :param single_step_module: 一个或多个单步模块 :type single_step_module: torch.nn.Module or list[nn.Module] or tuple[nn.Module] or torch.nn.Sequential or Callable :return: ``shape=...
7,648
import logging import copy import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Callable from . import neuron, base from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `chunk_multi_step_forward` function. Write a Python fu...
* :ref:`API in English <chunk_multi_step_forward-en>` .. _chunk_multi_step_forward-cn: :param split_size: 分割的尺寸 :type split_size: int :param x_seq: 输入 :type x_seq: Tensor :param multi_step_module: 一个使用多步传播模式的网络 :type multi_step_module: nn.Module :return: 输出 :rtype: Tensor 将 ``shape = [T, *]`` 的输入 ``x_seq`` 拆分成多个 ``shap...
7,649
import logging import copy import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Callable from . import neuron, base from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `scale_fused_conv2d_weight_of_convbn2d` function. Writ...
* :ref:`API in English <scale_fused_conv2d_weight_of_convbn2d-en>` .. _scale_fused_conv2d_weight_of_convbn2d-cn: :param conv2d: 一个2D卷积层 :type conv2d: torch.nn.Conv2d :param bn2d: 一个2D的BN层 :type bn2d: torch.nn.BatchNorm2d :return: the weight of this fused module :rtype: Tensor ``{Conv2d-BatchNorm2d}`` 模块可以合并为一个单个的 ``{Co...
7,650
import logging import copy import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Callable from . import neuron, base from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `scale_fused_conv2d_bias_of_convbn2d` function. Write ...
* :ref:`API in English <scale_fused_conv2d_bias_of_convbn2d-en>` .. _scale_fused_conv2d_bias_of_convbn2d-cn: :param conv2d: 一个2D卷积层 :type conv2d: torch.nn.Conv2d :param bn2d: 一个2D的BN层 :type bn2d: torch.nn.BatchNorm2d :return: the weight of this fused module :rtype: Tensor ``{Conv2d-BatchNorm2d}`` 模块可以合并为一个单个的 ``{Conv2d...
7,651
import logging import copy import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Callable from . import neuron, base from torch import Tensor def fused_conv2d_weight_of_convbn2d(conv2d: nn.Conv2d, bn2d: nn.BatchNorm2d): """ * :ref:`API in English <fused_conv2d_weight_...
* :ref:`API in English <fuse_convbn2d-en>` .. _fuse_convbn2d-cn: :param conv2d: 一个2D卷积层 :type conv2d: torch.nn.Conv2d :param bn2d: 一个2D的BN层 :type bn2d: torch.nn.BatchNorm2d :return: the weight of this fused module :rtype: Tensor ``{Conv2d-BatchNorm2d}`` 模块可以合并为一个单个的 ``{Conv2d}``,其中``BatchNorm2d`` 的参数会被吸收进 ``Conv2d``。 本...
7,652
import logging import copy import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Callable from . import neuron, base from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `temporal_efficient_training_cross_entropy` function. ...
* :ref:`API in English <temporal_efficient_training_cross_entropy-en>` .. _temporal_efficient_training_cross_entropy-cn: :param x_seq: ``shape=[T, N, C, *]`` 的预测值,其中 ``C`` 是类别总数 :type x_seq: torch.Tensor :param target: ``shape=[N]`` 的真实值,其中 ``target[i]`` 是真实类别 :type target: torch.Tensor :return: the temporal efficient ...
7,653
import logging import copy import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Callable from . import neuron, base from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `kaiming_normal_conv_linear_weight` function. Write a ...
* :ref:`API in English <kaiming_normal_conv_linear_weight-en>` .. _kaiming_normal_conv_linear_weight-cn: :param net: 任何属于 ``nn.Module`` 子类的网络 :return: None 使用kaiming normal初始化 ``net` `中的所有 :class:`torch.nn._ConvNd` 和 :class:`torch.nn.Linear` 的权重(不包括偏置项)。参见 :class:`torch.nn.init.kaiming_normal_`。 * :ref:`中文API <kaiming_...
7,654
import logging import copy import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Callable from . import neuron, base from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `delay` function. Write a Python function `def delay(x...
* :ref:`API in English <delay.__init__-en>` .. _delay.__init__-cn: :param x_seq: 输入的序列,``shape = [T, *]`` :type x_seq: torch.Tensor :param delay_steps: 延迟的时间步数 :type delay_steps: int :return: 延迟后的序列 :rtype: torch.Tensor 延迟函数,可以用来延迟输入,使得 ``y[t] = x[t - delay_steps]``。缺失的数据用0填充。 代码示例: .. code-block:: python x = torch.ran...
7,655
import logging import copy import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Callable from . import neuron, base from torch import Tensor def fptt_online_training_init_w_ra(optimizer: torch.optim.Optimizer) -> list: w_ra = [] for item in optimizer.param_groups: ...
null
7,656
import logging import copy import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Callable from . import neuron, base from torch import Tensor def detach_net(net: nn.Module): """ * :ref:`API in English <detach_net-en>` .. _detach_net-cn: :param net: 任何属于 ``nn.M...
:param model: the neural network :type model: nn.Module :param optimizer: the optimizer for the network :type optimizer: torch.optim.Optimizer :param x_seq: the input sequence :type x_seq: torch.Tensor :param target_seq: the output sequence :type target_seq: torch.Tensor :param f_loss_t: the loss function, which should...
7,657
import logging import copy import torch import torch.nn as nn import torch.nn.functional as F import math from typing import Callable from . import neuron, base from torch import Tensor The provided code snippet includes necessary dependencies for implementing the `ottt_online_training` function. Write a Python functi...
:param model: the neural network :type model: nn.Module :param optimizer: the optimizer for the network :type optimizer: torch.optim.Optimizer :param x_seq: the input sequence :type x_seq: torch.Tensor :param target_seq: the output sequence :type target_seq: torch.Tensor :param f_loss_t: the loss function, which should...
7,658
import torch class round_atgf(torch.autograd.Function): def forward(ctx, x: torch.Tensor): return torch.round(x) def backward(ctx, grad_output: torch.Tensor): return grad_output The provided code snippet includes necessary dependencies for implementing the `round` function. Write a Python funct...
:param x: the input tensor :type x: torch.Tensor :return: the output tensor :rtype: torch.Tensor Apply ``y = torch.round(x)`` with re-defining gradient as :math:`\\frac{\\partial y}{\\partial x} = 1`.
7,659
import torch class ceil_atgf(torch.autograd.Function): def forward(ctx, x: torch.Tensor): return torch.ceil(x) def backward(ctx, grad_output: torch.Tensor): return grad_output The provided code snippet includes necessary dependencies for implementing the `ceil` function. Write a Python function...
:param x: the input tensor :type x: torch.Tensor :return: the output tensor :rtype: torch.Tensor Apply ``y = torch.ceil(x)`` with re-defining gradient as :math:`\\frac{\\partial y}{\\partial x} = 1`.
7,660
import torch class floor_atgf(torch.autograd.Function): def forward(ctx, x: torch.Tensor): return torch.floor(x) def backward(ctx, grad_output: torch.Tensor): return grad_output The provided code snippet includes necessary dependencies for implementing the `floor` function. Write a Python funct...
:param x: the input tensor :type x: torch.Tensor :return: the output tensor :rtype: torch.Tensor Apply ``y = torch.floor(x)`` with re-defining gradient as :math:`\\frac{\\partial y}{\\partial x} = 1`.
7,661
import torch def clamp_backward(grad_output: torch.Tensor, x: torch.Tensor, min_value: float, max_value: float): mask = (x >= min_value).to(x) * (x <= max_value).to(x) return grad_output * mask
null
7,662
import torch class clamp_atgf(torch.autograd.Function): def forward(ctx, x: torch.Tensor, min_value: float, max_value: float): if x.requires_grad: ctx.save_for_backward(x) ctx.min_value = min_value ctx.max_value = max_value return torch.clamp(x, min_value, max_val...
:param x: the input tensor :type x: torch.Tensor :param min_value: lower-bound of the range to be clamped to :type min_value: float :param max_value: upper-bound of the range to be clamped to :type max_value: torch.Tensor :return: the output tensor :rtype: torch.Tensor Apply ``y = torch.clamp(x, min_value, max_value)``...
7,663
import torch def step_quantize_forward(x: torch.Tensor, step: float): return torch.round_(x / step) * step
null
7,664
import torch class step_quantize_atgf(torch.autograd.Function): def forward(ctx, x: torch.Tensor, step: float): return step_quantize_forward(x, step) def backward(ctx, grad_output: torch.Tensor): return grad_output, None The provided code snippet includes necessary dependencies for implementing...
:param x: the input tensor :type x: torch.Tensor :param step: the quantize step :type step: float :return: the quantized tensor :rtype: torch.Tensor Quantize ``x`` to the nearest ``i * step``, where ``i`` is an integer. Note that the gradient is defined by :math:`\\frac{\\partial y}{\\partial x} = 1`. .. image:: ../_st...
7,665
import torch def k_bit_quantize_forward(x: torch.Tensor, k: int): c = float(1 << k) - 1. x = x * c torch.round_(x) return x / c
null
7,666
import torch def k_bit_quantize(x: torch.Tensor, k: int): """ :param x: a float tensor whose range is ``[0, 1]``. :type x: torch.Tensor :param k: the bit number of output :type k: int :return: ``y = round((2 ** k - 1) * x) / (2 ** k - 1)`` :rtype: torch.Tensor The k-bit quantizer defined...
:param x: a float tensor whose range is ``[0, 1]``. :type x: torch.Tensor :param k: the bit number of output :type k: int :param w: the weight of the affine transform :type w: torch.Tensor :param b: the bias of the affine transform :type b: torch.Tensor :return: ``y = w * round((2 ** k - 1) * x) / (2 ** k - 1) + b`` :r...
7,667
import torch The provided code snippet includes necessary dependencies for implementing the `clamp_by_linear` function. Write a Python function `def clamp_by_linear(x: torch.Tensor, eps: float = 1e-5)` to solve the following problem: :param x: the input tensor to be normed, whose range is ``(-inf, inf)`` :type x: torc...
:param x: the input tensor to be normed, whose range is ``(-inf, inf)`` :type x: torch.Tensor :param eps: a value added to the denominator for numerical stability. The default value is ``1e-5`` :type eps: float :type max_value: float :return: the normed tensor, whose range is ``[min_value, max_value]`` :rtype: torch.Te...
7,668
import logging import torch import torch.nn.functional as F from . import cuda_utils, surrogate, tensor_cache from .. import configure import numpy as np def check_multi_step_neuron_output_and_grad(device, multi_step_neuron, shape = [65, 15, 511], *neu_args, **neu_kwargs): @torch.no_grad() def max_error(x, y):...
null
7,669
import logging import torch import torch.nn.functional as F from . import cuda_utils, surrogate, tensor_cache from .. import configure import numpy as np def check_single_step_neuron_output_and_grad(device, single_step_neuron, shape = [65, 15, 511], *neu_args, **neu_kwargs): @torch.no_grad() def max_error(x, y...
null
7,670
import logging import torch import torch.nn.functional as F from . import cuda_utils, surrogate, tensor_cache from .. import configure import numpy as np class MultiStepIFNodePTT(torch.autograd.Function): def create_fptt_kernel(hard_reset: bool, dtype: str): kernel_name = f'IFNode_fptt_{"hard" if hard_reset...
null
7,671
import torch import torch.nn as nn import copy import logging from abc import abstractmethod try: import cupy except BaseException as e: logging.info(f'spikingjelly.activation_based.base: {e}') cupy = None The provided code snippet includes necessary dependencies for implementing the `check_backend_library...
* :ref:`API in English <check_backend_library-en>` .. _check_backend_library-cn: :param backend: ``'torch'``, ``'cupy'`` 或 ``'lava'`` :type backend: str 检查某个后端的python库是否已经安装。若未安装则此函数会报错。 * :ref:`中文 API <check_backend_library-cn>` .. _check_backend_library-en: :param backend: ``'torch'``, ``'cupy'`` or ``'lava'`` :type ...
7,672
from typing import Callable, Union import math import torch import torch.nn as nn import torch.nn.functional as F from . import neuron, monitor, base def mstdp_linear_single_step( fc: nn.Linear, in_spike: torch.Tensor, out_spike: torch.Tensor, trace_pre: Union[float, torch.Tensor, None], trace_post: Union[...
null
7,673
from typing import Callable, Union import math import torch import torch.nn as nn import torch.nn.functional as F from . import neuron, monitor, base def mstdpet_linear_single_step( fc: nn.Linear, in_spike: torch.Tensor, out_spike: torch.Tensor, trace_pre: Union[float, torch.Tensor, None], trace_post: Unio...
null
7,674
from typing import Callable, Union import math import torch import torch.nn as nn import torch.nn.functional as F from . import neuron, monitor, base def stdp_linear_single_step( fc: nn.Linear, in_spike: torch.Tensor, out_spike: torch.Tensor, trace_pre: Union[float, torch.Tensor, None], trace_post: Union[fl...
null
7,675
import torch import torch.nn as nn import torch.nn.functional as F import math from .auto_cuda import cfunction The provided code snippet includes necessary dependencies for implementing the `check_manual_grad` function. Write a Python function `def check_manual_grad(primitive_function, spiking_function, *args, **kwar...
:param primitive_function: 梯度替代函数的原函数 :type primitive_function: callable :param spiking_function: 梯度替代函数 :type spiking_function: callable 梯度替代函数的反向传播一般是手写的,可以用此函数去检查手写梯度是否正确。 此函数检查梯度替代函数spiking_function的反向传播,与原函数primitive_function的反向传播结果是否一致。“一致”被定义为,两者的误差不超过eps。 示例代码: .. code-block:: python def s2nn_apply(x, alpha, be...
7,676
import torch import torch.nn as nn import torch.nn.functional as F import math from .auto_cuda import cfunction def check_cuda_grad(neu, surrogate_function, device, *args, **kwargs): # check_cuda_grad(neuron.IFNode, surrogate.S2NN, device='cuda:1', alpha=4., beta=1.) for dtype in [torch.float, torch.half]: ...
null
7,677
import torch import torch.nn as nn import torch.nn.functional as F import math from .auto_cuda import cfunction def piecewise_quadratic_backward(grad_output: torch.Tensor, x: torch.Tensor, alpha: float): x_abs = x.abs() mask = (x_abs > (1 / alpha)) grad_x = (grad_output * (- (alpha ** 2) * x_abs + alpha))....
null