repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/pointnet_modules/point_fp_module.py | import torch
from mmcv.cnn import ConvModule
from mmcv.runner import BaseModule, force_fp32
from torch import nn as nn
from typing import List
from mmdet3d.ops import three_interpolate, three_nn
class PointFPModule(BaseModule):
"""Point feature propagation module used in PointNets.
Propagate the features fr... | 2,669 | 32.375 | 99 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/pointnet_modules/paconv_sa_module.py | import torch
from torch import nn as nn
from mmdet3d.ops import PAConv, PAConvCUDA
from .builder import SA_MODULES
from .point_sa_module import BasePointSAModule
@SA_MODULES.register_module()
class PAConvSAModuleMSG(BasePointSAModule):
r"""Point set abstraction module with multi-scale grouping (MSG) used in
... | 12,351 | 34.39255 | 96 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/group_points/group_points.py | import torch
from torch import nn as nn
from torch.autograd import Function
from typing import Tuple
from ..ball_query import ball_query
from ..knn import knn
from . import group_points_ext
class QueryAndGroup(nn.Module):
"""Query and Group.
Groups with a ball query of radius
Args:
max_radius (... | 7,538 | 33.113122 | 100 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/gather_points/gather_points.py | import torch
from torch.autograd import Function
from . import gather_points_ext
class GatherPoints(Function):
"""Gather Points.
Gather points with given index.
"""
@staticmethod
def forward(ctx, features: torch.Tensor, indices: torch.Tensor) -> torch.Tensor:
"""forward.
Args:
... | 1,393 | 26.333333 | 91 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/bev_pool/bev_pool.py | import torch
from . import bev_pool_ext
__all__ = ["bev_pool"]
class QuickCumsum(torch.autograd.Function):
@staticmethod
def forward(ctx, x, geom_feats, ranks):
x = x.cumsum(0)
kept = torch.ones(x.shape[0], device=x.device, dtype=torch.bool)
kept[:-1] = ranks[1:] != ranks[:-1]
... | 2,638 | 25.928571 | 76 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/voxel/voxelize.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import torch
from torch import nn
from torch.autograd import Function
from torch.nn.modules.utils import _pair
from .voxel_layer import dynamic_voxelize, hard_voxelize
class _Voxelization(Function):
@staticmethod
def forward(
ctx,... | 6,375 | 41.791946 | 97 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/voxel/scatter_points.py | import torch
from torch import nn
from torch.autograd import Function
from .voxel_layer import dynamic_point_to_voxel_backward, dynamic_point_to_voxel_forward
class _dynamic_scatter(Function):
@staticmethod
def forward(ctx, feats, coors, reduce_type="max"):
"""convert kitti points(N, >=3) to voxels.
... | 4,092 | 37.980952 | 90 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/knn/knn.py | import torch
from torch.autograd import Function
from . import knn_ext
class KNN(Function):
r"""KNN (CUDA) based on heap data structure.
Modified from `PAConv <https://github.com/CVMI-Lab/PAConv/tree/main/
scene_seg/lib/pointops/src/knnquery_heap>`_.
Find k-nearest points.
"""
@staticmethod... | 2,313 | 31.138889 | 97 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/furthest_point_sample/utils.py | import torch
def calc_square_dist(point_feat_a, point_feat_b, norm=True):
"""Calculating square distance between a and b.
Args:
point_feat_a (Tensor): (B, N, C) Feature vector of each point.
point_feat_b (Tensor): (B, M, C) Feature vector of each point.
norm (Bool): Whether to normali... | 1,051 | 31.875 | 70 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/furthest_point_sample/points_sampler.py | import torch
from mmcv.runner import force_fp32
from torch import nn as nn
from typing import List
from .furthest_point_sample import furthest_point_sample, furthest_point_sample_with_dist
from .utils import calc_square_dist
def get_sampler_type(sampler_type):
"""Get the type and mode of points sampler.
Arg... | 5,258 | 32.28481 | 100 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/furthest_point_sample/furthest_point_sample.py | import torch
from torch.autograd import Function
from . import furthest_point_sample_ext
class FurthestPointSampling(Function):
"""Furthest Point Sampling.
Uses iterative furthest point sampling to select a set of features whose
corresponding points have the furthest distance.
"""
@staticmethod... | 2,367 | 28.974684 | 81 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/iou3d/iou3d_utils.py | import torch
from . import iou3d_cuda
def boxes_iou_bev(boxes_a, boxes_b):
"""Calculate boxes IoU in the bird view.
Args:
boxes_a (torch.Tensor): Input boxes a with shape (M, 5).
boxes_b (torch.Tensor): Input boxes b with shape (N, 5).
Returns:
ans_iou (torch.Tensor): IoU result... | 2,207 | 31 | 85 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/interpolate/three_interpolate.py | import torch
from torch.autograd import Function
from typing import Tuple
from . import interpolate_ext
class ThreeInterpolate(Function):
@staticmethod
def forward(
ctx, features: torch.Tensor, indices: torch.Tensor, weight: torch.Tensor
) -> torch.Tensor:
"""Performs weighted linear inte... | 1,934 | 31.25 | 97 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/interpolate/three_nn.py | import torch
from torch.autograd import Function
from typing import Tuple
from . import interpolate_ext
class ThreeNN(Function):
@staticmethod
def forward(
ctx, target: torch.Tensor, source: torch.Tensor
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Find the top-3 nearest neighbors of the ta... | 1,293 | 27.130435 | 77 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/paconv/utils.py | import torch
def calc_euclidian_dist(xyz1, xyz2):
"""Calculate the Euclidian distance between two sets of points.
Args:
xyz1 (torch.Tensor): (N, 3), the first set of points.
xyz2 (torch.Tensor): (N, 3), the second set of points.
Returns:
torch.Tensor: (N, ), the Euclidian distanc... | 3,698 | 40.1 | 87 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/paconv/assign_score.py | from torch.autograd import Function
from . import assign_score_withk_ext
class AssignScoreWithK(Function):
r"""Perform weighted sum to generate output features according to scores.
Modified from `PAConv <https://github.com/CVMI-Lab/PAConv/tree/main/
scene_seg/lib/paconv_lib/src/gpu>`_.
This is a mem... | 4,151 | 34.487179 | 88 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/paconv/paconv.py | import copy
import torch
from mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer, constant_init
from torch import nn as nn
from torch.nn import functional as F
from .assign_score import assign_score_withk as assign_score_cuda
from .utils import assign_kernel_withoutk, assign_score, calc_euclidian_dis... | 15,524 | 38.105793 | 96 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/spconv/structure.py | import numpy as np
import torch
def scatter_nd(indices, updates, shape):
"""pytorch edition of tensorflow scatter_nd.
this function don't contain except handle code. so use this carefully when
indice repeats, don't support repeat add which is supported in tensorflow.
"""
ret = torch.zeros(*shape,... | 2,087 | 31.625 | 84 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/spconv/modules.py | # Copyright 2019 Yan Yan
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | 6,962 | 32.800971 | 97 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/spconv/functional.py | # Copyright 2019 Yan Yan
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | 4,034 | 31.540323 | 86 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/spconv/ops.py | # Copyright 2019 Yan Yan
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | 6,584 | 29.486111 | 100 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/spconv/conv.py | # Copyright 2019 Yan Yan
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | 13,449 | 26.962578 | 100 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/roiaware_pool3d/roiaware_pool3d.py | import mmcv
import torch
from torch import nn as nn
from torch.autograd import Function
from . import roiaware_pool3d_ext
class RoIAwarePool3d(nn.Module):
def __init__(self, out_size, max_pts_per_voxel=128, mode="max"):
super().__init__()
"""RoIAwarePool3d module
Args:
out_si... | 3,504 | 31.155963 | 99 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/roiaware_pool3d/points_in_boxes.py | import torch
from . import roiaware_pool3d_ext
def points_in_boxes_gpu(points, boxes):
"""Find points that are in boxes (CUDA)
Args:
points (torch.Tensor): [B, M, 3], [x, y, z] in LiDAR coordinate
boxes (torch.Tensor): [B, T, 7],
num_valid_boxes <= T, [x, y, z, w, l, h, ry] in Li... | 4,327 | 34.186992 | 99 | py |
RoboBEV | RoboBEV-master/zoo/BEVFusion/mmdet3d/ops/ball_query/ball_query.py | import torch
from torch.autograd import Function
from . import ball_query_ext
class BallQuery(Function):
"""Ball Query.
Find nearby points in spherical space.
"""
@staticmethod
def forward(
ctx,
min_radius: float,
max_radius: float,
sample_num: int,
xyz: ... | 1,482 | 25.963636 | 82 | py |
RoboBEV | RoboBEV-master/corruptions/tools/generate_dataset.py | import argparse
import os
import warnings
import time
import numpy as np
import torch
import mmcv
from mmdet3d.datasets import build_dataset, build_dataloader
from mmcv import Config, DictAction
from mmdet3d.datasets import build_dataset
from project.mmdet3d_plugin.corruptions import CORRUPTIONS
def parse_args():
... | 4,414 | 34.32 | 128 | py |
RoboBEV | RoboBEV-master/corruptions/tools/robust_test.py | # Copyright (c) OpenMMLab. All rights reserved.
# ---------------------------------------------
# Modified by Shaoyuan Xie
# ---------------------------------------------
import argparse
import mmcv
import os
import torch
import warnings
from mmcv import Config, DictAction
from mmcv.cnn import fuse_conv_bn
from mmcv.p... | 11,425 | 39.51773 | 94 | py |
RoboBEV | RoboBEV-master/corruptions/tools/analysis_tools/visual.py | # Based on https://github.com/nutonomy/nuscenes-devkit
# ---------------------------------------------
# Modified by Zhiqi Li
# ---------------------------------------------
# Modified by Shaoyuan Xie
# ---------------------------------------------
import mmcv
import os
from nuscenes.nuscenes import NuScenes
from PI... | 27,938 | 42.929245 | 156 | py |
RoboBEV | RoboBEV-master/corruptions/project/mmdet3d_plugin/corruptions.py | from copy import deepcopy
import functools
import PIL
from PIL import Image
import torch
import numpy as np
from mmcv.utils import Registry
from imagecorruptions import corrupt
CORRUPTIONS= Registry('corruptions')
@CORRUPTIONS.register_module()
class Clean:
def __init__(self, severity, norm_config):
"... | 11,140 | 30.650568 | 108 | py |
RoboBEV | RoboBEV-master/corruptions/project/mmdet3d_plugin/datasets/custom_nuscenes_dataset.py | # Copied from BEVFormer
# Modified by Shaoyuan Xie
import copy
import numpy as np
from mmdet.datasets import DATASETS
from mmdet3d.datasets import NuScenesDataset
import mmcv
from os import path as osp
from mmdet.datasets import DATASETS
import torch
import numpy as np
from nuscenes.eval.common.utils import quaterni... | 6,882 | 36.612022 | 97 | py |
fast_finite_width_ntk | fast_finite_width_ntk-main/example.py | """Minimal NTK example."""
from jax import random
from jax import numpy as jnp
from jax.experimental import stax
from fast_finite_width_ntk import empirical
key1, key2, key3 = random.split(random.PRNGKey(1), 3)
x1 = random.normal(key1, (6, 8, 8, 3))
x2 = random.normal(key2, (3, 8, 8, 3))
# A vanilla CNN.
init_fn, f =... | 1,829 | 24.774648 | 73 | py |
fast_finite_width_ntk | fast_finite_width_ntk-main/setup.py | """Setup the package with pip."""
import os
import setuptools
# https://packaging.python.org/guides/making-a-pypi-friendly-readme/
this_directory = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
INSTALL_REQUIRES... | 2,491 | 33.136986 | 97 | py |
fast_finite_width_ntk | fast_finite_width_ntk-main/fast_finite_width_ntk/empirical.py | """Fast computation of empirical NTK.
All functions in this module are applicable to any JAX functions of proper
signatures.
The NTK kernels have a very specific output shape convention that may be
unexpected. Further, NTK has multiple implementations that may perform
differently depending on the task.
Please read in... | 54,469 | 32.958853 | 95 | py |
fast_finite_width_ntk | fast_finite_width_ntk-main/fast_finite_width_ntk/rules.py | """Structured derivatives rules."""
import functools
from typing import Callable, Optional, Tuple, Dict, List, Union
import jax.numpy as np
import jax
from jax import lax
from jax.interpreters import ad, xla
import numpy as onp
from jax.interpreters.ad import UndefinedPrimal
from jax.core import JaxprEqn, ShapedArray,... | 24,980 | 26.33151 | 89 | py |
fast_finite_width_ntk | fast_finite_width_ntk-main/fast_finite_width_ntk/utils/typing.py | """Common Type Definitions."""
from typing import Tuple, Callable, Union, List, Any, Optional, Sequence, TypeVar, Dict
import jax.numpy as np
# Missing JAX Types.
PyTree = Any
"""A type alias for PRNGKeys.
See https://jax.readthedocs.io/en/latest/jax.random.html#jax.random.PRNGKey
for details.
"""
PRNGKey = n... | 1,735 | 25.30303 | 87 | py |
fast_finite_width_ntk | fast_finite_width_ntk-main/fast_finite_width_ntk/utils/utils.py | """General-purpose internal utilities."""
import functools
import inspect
import operator
from typing import Any, Callable, Iterable, List, Optional, Sequence, Sized, Tuple, Union
from .typing import Axes, PyTree
import warnings
from . import dataclasses
import jax
from jax import lax, dtypes, tree_flatten, tree_unfl... | 16,611 | 31.069498 | 90 | py |
fast_finite_width_ntk | fast_finite_width_ntk-main/fast_finite_width_ntk/utils/dataclasses.py | """Utilities for defining dataclasses that can be used with jax transformations.
This code was copied and adapted from https://github.com/google/flax/struct.py.
"""
from typing import Dict, Any, Tuple
import dataclasses
import jax
def dataclass(clz):
"""Create a class which can be passed to functional transforma... | 2,777 | 29.527473 | 80 | py |
spikingjelly | spikingjelly-master/setup.py | '''
python setup.py sdist bdist_wheel
python -m twine upload dist/*
'''
from setuptools import find_packages
from setuptools import setup
requirements = ["torch"]
with open("./requirements.txt", "r", encoding="utf-8") as fh:
install_requires = fh.read()
with open("./README.md", "r", encoding="utf-8") as fh:
... | 1,153 | 28.589744 | 71 | py |
spikingjelly | spikingjelly-master/spikingjelly/datasets/hardvs.py | from typing import Callable, Dict, Optional, Tuple
import numpy as np
from .. import datasets as sjds
from torchvision.datasets.utils import extract_archive
import os
import multiprocessing
from concurrent.futures import ThreadPoolExecutor
import time
import shutil
from .. import configure
from ..datasets import np_sav... | 5,363 | 39.330827 | 126 | py |
spikingjelly | spikingjelly-master/spikingjelly/datasets/dvs128_gesture.py | from typing import Callable, Dict, Optional, Tuple
import numpy as np
from .. import datasets as sjds
from torchvision.datasets.utils import extract_archive
import os
import multiprocessing
from concurrent.futures import ThreadPoolExecutor
import time
from .. import configure
from ..datasets import np_savez
class DVS1... | 13,745 | 41.557276 | 211 | py |
spikingjelly | spikingjelly-master/spikingjelly/datasets/bullying10k.py | import multiprocessing
import os
import shutil
import time
from concurrent.futures import ThreadPoolExecutor
from typing import Callable, List, Optional, Tuple
import numpy as np
from torchvision.datasets import utils
from .. import configure
from .. import datasets as sjds
from ..datasets import np_savez
CATEGORY_L... | 9,994 | 40.473029 | 153 | py |
spikingjelly | spikingjelly-master/spikingjelly/datasets/nav_gesture.py |
# Codes from the source dataset:
# ---------------------------------------------------------------------------------------------
#!/usr/bin/python
# -*- coding: utf8 -*
#####################
# read_td_events.py #
#####################
# Feb 2017 - Jean-Matthieu Maro
# Email: jean-matthieu dot maro, hosted at inserm, w... | 13,961 | 37.891365 | 238 | py |
spikingjelly | spikingjelly-master/spikingjelly/datasets/n_caltech101.py | from typing import Callable, Dict, Optional, Tuple
from .. import datasets as sjds
from torchvision.datasets.utils import extract_archive
import os
import multiprocessing
from concurrent.futures import ThreadPoolExecutor
import time
from .. import configure
from ..datasets import np_savez
class NCaltech101(sjds.Neurom... | 5,710 | 40.992647 | 208 | py |
spikingjelly | spikingjelly-master/spikingjelly/datasets/n_mnist.py | from typing import Callable, Dict, Optional, Tuple
from .. import datasets as sjds
from torchvision.datasets.utils import extract_archive
import os
import multiprocessing
from concurrent.futures import ThreadPoolExecutor
import time
from .. import configure
from ..datasets import np_savez
class NMNIST(sjds.Neuromorphi... | 6,207 | 40.386667 | 203 | py |
spikingjelly | spikingjelly-master/spikingjelly/datasets/to_x_rep.py | from dataclasses import dataclass
import numpy as np
import math
from typing import Callable, Optional, Tuple, Union,Any, List
# Code adapted from https://github.com/uzh-rpg/rpg_e2vid/blob/master/utils/inference_utils.py#L431,
# https://github.com/neuromorphs/tonic/blob/develop/tonic/transforms.py,
# and https://githu... | 19,586 | 39.976987 | 147 | py |
spikingjelly | spikingjelly-master/spikingjelly/datasets/asl_dvs.py | from typing import Callable, Dict, Optional, Tuple
import spikingjelly.datasets as sjds
import scipy.io
from torchvision.datasets.utils import extract_archive
import os
import multiprocessing
from concurrent.futures import ThreadPoolExecutor
import time
import shutil
from .. import configure
from ..datasets import np_... | 6,601 | 40.78481 | 264 | py |
spikingjelly | spikingjelly-master/spikingjelly/datasets/shd.py | from typing import Callable, Dict, Optional, Tuple
import h5py
import numpy as np
from torch.utils.data import Dataset
from torchvision.datasets import utils
from torchvision.datasets.utils import extract_archive
import os
import multiprocessing
from concurrent.futures import ThreadPoolExecutor
import time
from .. imp... | 43,845 | 47.182418 | 238 | py |
spikingjelly | spikingjelly-master/spikingjelly/datasets/speechcommands.py | import os
from typing import Callable, Tuple, Dict, Optional
from pathlib import Path
import torch
import torchaudio
from torch.utils.data import Dataset
from torch import Tensor
from torchaudio.datasets.utils import (
download_url,
extract_archive
)
from torchvision.datasets.utils import verify_str_arg
import... | 8,317 | 39.57561 | 176 | py |
spikingjelly | spikingjelly-master/spikingjelly/datasets/__init__.py | from torchvision.datasets import DatasetFolder
from typing import Callable, Dict, Optional, Tuple
from abc import abstractmethod
import scipy.io
import struct
import numpy as np
from torchvision.datasets import utils
import torch.utils.data
import os
from concurrent.futures import ThreadPoolExecutor
import time
from to... | 45,845 | 43.424419 | 214 | py |
spikingjelly | spikingjelly-master/spikingjelly/datasets/cifar10_dvs.py | from typing import Callable, Dict, Optional, Tuple
import numpy as np
from .. import datasets as sjds
from torchvision.datasets.utils import extract_archive
import os
import multiprocessing
from concurrent.futures import ThreadPoolExecutor
import time
from .. import configure
from ..datasets import np_savez
# https://g... | 9,836 | 37.576471 | 167 | py |
spikingjelly | spikingjelly-master/spikingjelly/visualizing/__init__.py | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
def plot_2d_heatmap(array: np.ndarray, title: str, xlabel: str, ylabel: str, int_x_ticks=True, int_y_ticks=True,
plot_colorbar=True, colorbar_y_label='magnitude', x_max=None, figsize=(12, 8), dpi=200):
'''
:param array: s... | 12,984 | 34.478142 | 178 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/neuron.py | 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_kern... | 97,906 | 40.20665 | 265 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/base.py | 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
try:
import lava.lib.dl.slayer as slayer
except BaseException as e:
slayer = None
def chec... | 12,153 | 25.889381 | 152 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/layer.py | import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from . import base, functional
from torch import Tensor
from torch.nn.common_types import _size_any_t, _size_1_t, _size_2_t, _size_3_t
from typing import Optional, List, Tuple, Union
from typing import Callable
from torch.nn.... | 82,698 | 34.707686 | 308 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/surrogate.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from .auto_cuda import cfunction
tab4_str = '\t\t\t\t' # used for aligning code
curly_bracket_l = '{'
curly_bracket_r = '}'
@torch.jit.script
def heaviside(x: torch.Tensor):
'''
* :ref:`API in English <heaviside.__init__-en>`
... | 71,589 | 34.024462 | 320 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/lava_exchange.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import logging
from typing import Union, Callable
from . import neuron, base, surrogate
_hw_bits = 12
@torch.jit.script
def step_quantize_forward(x: torch.Tensor, step: float):
x = x / step
torch.round_(x)
return x * step
class step_qua... | 38,727 | 37.11811 | 187 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/spike_op.py | 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.... | 17,772 | 34.055227 | 191 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/functional.py | 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 reset_net(net: nn.Module):
"""
* :ref:`API in English <reset_net-en>`
.. _reset_net-cn:
:param net: 任何属于 ``nn... | 47,717 | 36.250585 | 334 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/learning.py | 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: Uni... | 18,092 | 35.331325 | 118 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/tensor_cache.py | 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'''
ex... | 8,927 | 34.149606 | 112 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/monitor.py | 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,... | 34,887 | 37.004357 | 232 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/cuda_utils.py | import logging
import torch
import time
import numpy as np
from .. import configure
from typing import Callable
try:
import cupy
except BaseException as e:
logging.info(f'spikingjelly.activation_based.cuda_utils: {e}')
cupy = None
def cpu_timer(f: Callable, *args, **kwargs):
"""
* :ref:`API in Engl... | 8,155 | 25.828947 | 184 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/rnn.py | 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 = []
... | 38,809 | 41.002165 | 255 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/quantize.py | import torch
class round_atgf(torch.autograd.Function):
@staticmethod
def forward(ctx, x: torch.Tensor):
return torch.round(x)
@staticmethod
def backward(ctx, grad_output: torch.Tensor):
return grad_output
@torch.jit.ignore
def round(x: torch.Tensor):
"""
:param x: the input... | 8,854 | 30.625 | 165 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/encoding.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from . import functional
import math
from . import base
from abc import abstractmethod
class StatelessEncoder(nn.Module, base.StepModule):
def __init__(self, step_mode='s'):
"""
* :ref:`API in English <StatelessEncoder.__init__-en>... | 15,611 | 36.801453 | 180 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/neuron_kernel.py | import logging
try:
import cupy
except BaseException as e:
logging.info(f'spikingjelly.activation_based.neuron_kernel: {e}')
cupy = None
import torch
import torch.nn.functional as F
from . import cuda_utils, surrogate, tensor_cache
from .. import configure
import numpy as np
class MultiStepIFNo... | 112,025 | 44.912295 | 658 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/lynxi_exchange.py | import copy
import os
from typing import Dict
import torch
import torch.nn as nn
import torch.nn.functional as F
import logging
import numpy as np
from . import neuron, functional, layer
'''
TracerWarning: Converting a tensor to a Python index might cause the trace to be incorrect. We can't record the data flow of Pyt... | 7,744 | 33.118943 | 262 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/spiking_lstm_text.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from spikingjelly.activation_based import rnn
# from torch.utils.tensorboard import SummaryWriter
# import sys
# if sys.platform != 'win32':
# import readline
# import torchvision
# import tqdm
import matplotlib.pyplot as plt
impo... | 11,108 | 34.378981 | 124 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/lif_fc_mnist.py | import os
import time
import argparse
import sys
import datetime
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as data
from torch.cuda import amp
from torch.utils.tensorboard import SummaryWriter
import torchvision
import numpy as np
from spikingjelly.activation_based impo... | 9,579 | 33.336918 | 183 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/rsnn_sequential_fmnist.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.datasets
from spikingjelly.activation_based import neuron, surrogate, layer, functional
from torch.cuda import amp
import os, argparse
from torch.utils.tensorboard import SummaryWriter
import time
import datetime
import sys
class Pla... | 9,789 | 35.259259 | 193 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/DQN_state.py | 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
c... | 5,753 | 28.813472 | 98 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/spiking_lstm_sequential_mnist.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from spikingjelly.activation_based import rnn
from torch.utils.tensorboard import SummaryWriter
import sys
if sys.platform != 'win32':
import readline
import torchvision
import tqdm
class Net(nn.Module):
def __init__(self):
... | 4,026 | 34.955357 | 130 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/PPO.py | 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 Normal
from torch.utils.tensorboard import SummaryWriter
from spikingjelly.activation_based.examples.common.multiprocessing_env import ... | 6,390 | 30.024272 | 143 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/Spiking_PPO.py | 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 Normal
from torch.utils.tensorboard import SummaryWriter
from spikingjelly.activation_based.examples.common.multiprocessing_env import ... | 7,946 | 31.304878 | 143 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/speechcommands.py | """
.. codeauthor:: Yanqi Chen <chyq@pku.edu.cn>, Ismail Khalfaoui Hassani <ismail.khalfaoui-hassani@univ-tlse3.fr>
A reproduction of the paper `Technical report: supervised training of convolutional spiking neural networks with PyTorch <https://arxiv.org/pdf/1911.10124.pdf>`_\ .
This code reproduces an audio recogni... | 19,149 | 40.54013 | 373 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/mstdp.py | 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)
# plt.style.use(['science'])
if __name__ == '__main__':
def f_pre(x, w_min, alpha=0.):
return (x - w_min) ** alpha
def f_post(x, w_max, alpha=... | 3,783 | 32.192982 | 82 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/lynxi_fmnist_inference.py | import torch
import torch.nn as nn
import argparse
from spikingjelly.activation_based import lynxi_exchange
from spikingjelly.activation_based.examples import conv_fashion_mnist
import torchvision
import tqdm
'''
python w1.py -T 4 -device cuda:0 -b 128 -epochs 64 -data-dir /datasets/FashionMNIST/ -cupy -opt sgd -lr 0.... | 4,157 | 38.226415 | 205 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/mstdpet.py | 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
torch.manual_seed(0)
# plt.style.use(['science'])
if __name__ == '__main__':
def f_pre(x, w_min, alpha=0.):
return (x - w_min) ** alpha
def f_po... | 3,927 | 30.934959 | 94 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/stdp_trace.py | import torch
import torch.nn as nn
from spikingjelly.activation_based import neuron, layer, learning
from matplotlib import pyplot as plt
def f_weight(x):
return torch.clamp(x, -1, 1.)
torch.manual_seed(0)
# plt.style.use(['science'])
if __name__ == '__main__':
def f_pre(x, w_min, alpha=0.):
return ... | 3,455 | 31 | 87 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/Spiking_DQN_state.py | 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, neur... | 11,480 | 33.581325 | 193 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/classify_dvsg.py | import torch
import sys
import torch.nn.functional as F
from torch.cuda import amp
from spikingjelly.activation_based import functional, surrogate, neuron
from spikingjelly.activation_based.model import parametric_lif_net
from spikingjelly.datasets.dvs128_gesture import DVS128Gesture
from torch.utils.data import DataLo... | 7,981 | 37.560386 | 184 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/A2C.py | 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 im... | 4,745 | 26.593023 | 97 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/Spiking_A2C.py | 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 im... | 5,903 | 26.849057 | 105 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/lava_mnist.py | import logging
logging.getLogger().setLevel(logging.INFO)
import torch
import torch.nn as nn
import torchvision
from torchvision import transforms
from spikingjelly.activation_based import functional, lava_exchange, surrogate, encoding, neuron
import torch.nn.functional as F
from torch.utils.data import DataLoader
imp... | 7,570 | 32.799107 | 182 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/conv_fashion_mnist.py | import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from spikingjelly.activation_based import neuron, functional, surrogate, layer
from torch.utils.tensorboard import SummaryWriter
import os
import time
import argparse
from torch.cuda import amp
import s... | 12,537 | 39.315113 | 261 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/examples/cifar10_r11_enabling_spikebased_backpropagation.py | """
.. codeauthor:: Yanqi Chen <chyq@pku.edu.cn>
A reproduction of the paper `Enabling Spike-Based Backpropagation for Training Deep Neural Network Architectures <https://doi.org/10.3389/fnins.2020.00119>`_\ .
This code reproduces a novel gradient-based training method of SNN. We to some extent refer to the network s... | 11,268 | 30.044077 | 394 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/auto_cuda/base.py | import numpy as np
import logging
try:
import cupy
except BaseException as e:
logging.info(f'spikingjelly.activation_based.auto_cuda.base: {e}')
cupy = None
import torch
import torch.nn.functional as F
import sys
import logging
from .. import cuda_utils
from ... import configure
def wrap_with_comment(cod... | 48,109 | 30.34202 | 242 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/auto_cuda/example.py | from spikingjelly.activation_based.auto_cuda.generator import analyse_graph, gen_forward_codes, gen_backward_codes
from spikingjelly.activation_based import surrogate
import torch
if __name__ == '__main__':
def lif_charge(x: torch.Tensor, v_last: torch.Tensor, tau: float, v_reset: float):
h = v_last + (x ... | 1,243 | 50.833333 | 120 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/auto_cuda/ss_neuron_kernel.py | 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 Cal... | 19,900 | 38.564612 | 171 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/auto_cuda/generator.py | 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
class VarNode:
... | 21,423 | 32.112828 | 116 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/auto_cuda/neuron_kernel.py | 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 Callab... | 28,829 | 37.854447 | 213 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/ann2snn/modules.py | import torch.nn as nn
import torch
import numpy as np
class VoltageHook(nn.Module):
def __init__(self, scale=1.0, momentum=0.1, mode='Max'):
"""
* :ref:`API in English <VoltageHook.__init__-en>`
.. _voltageHook.__init__-cn:
:param scale: 缩放初始值
:type scale: float
:p... | 4,094 | 28.673913 | 254 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/ann2snn/converter.py | from typing import Type, Dict, Any, Tuple, Iterable
from spikingjelly.activation_based import neuron
from spikingjelly.activation_based.ann2snn.modules import *
from torch import fx
from torch.nn.utils.fusion import fuse_conv_bn_eval
from tqdm import tqdm
class Converter(nn.Module):
def __init__(self, dataloader... | 13,646 | 39.37574 | 289 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/ann2snn/examples/resnet18_cifar10.py | import torch
import torchvision
from tqdm import tqdm
import spikingjelly.activation_based.ann2snn as ann2snn
from spikingjelly.activation_based.ann2snn.sample_models import cifar10_resnet
def val(net, device, data_loader, T=None):
net.eval().to(device)
correct = 0.0
total = 0.0
with torch.no_grad():
... | 2,618 | 30.939024 | 116 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/ann2snn/examples/cnn_mnist.py | import torch
import torchvision
import torch.nn as nn
import spikingjelly
from spikingjelly.activation_based import ann2snn
from tqdm import tqdm
from spikingjelly.activation_based.ann2snn.sample_models import mnist_cnn
import numpy as np
import matplotlib.pyplot as plt
def val(net, device, data_loader, T=None):
n... | 6,153 | 38.961039 | 110 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/ann2snn/sample_models/mnist_cnn.py | import torch.nn as nn
class CNN(nn.Module):
def __init__(self):
super().__init__()
self.network = nn.Sequential(
nn.Conv2d(1, 32, 3, 1),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.AvgPool2d(2, 2),
nn.Conv2d(32, 32, 3, 1),
nn.BatchNorm2... | 644 | 22.035714 | 37 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/ann2snn/sample_models/cifar10_resnet.py | '''ResNet in PyTorch.
For Pre-activation ResNet, see 'preact_resnet.py'.
Reference:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
expansi... | 4,454 | 30.821429 | 83 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/model/snas_net.py | import torch
import torch.nn as nn
import numpy as np
from ...activation_based import functional, layer, surrogate, neuron
import argparse
### Components ###
class ScaleLayer(nn.Module):
def __init__(self):
super().__init__()
self.scale = torch.tensor(0.)
def forward(self, input):
return i... | 15,124 | 44.972644 | 161 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/model/sew_resnet.py | import torch
import torch.nn as nn
from copy import deepcopy
from .. import layer
try:
from torchvision.models.utils import load_state_dict_from_url
except ImportError:
from torchvision._internally_replaced_utils import load_state_dict_from_url
__all__ = ['SEWResNet', 'sew_resnet18', 'sew_resnet34', 'sew_r... | 21,136 | 44.751082 | 283 | py |
spikingjelly | spikingjelly-master/spikingjelly/activation_based/model/spiking_vgg.py | import torch
import torch.nn as nn
from copy import deepcopy
from .. import functional, neuron, layer
try:
from torchvision.models.utils import load_state_dict_from_url
except ImportError:
from torchvision._internally_replaced_utils import load_state_dict_from_url
__all__ = [
'SpikingVGG',
'spiking_vg... | 12,264 | 39.747508 | 159 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.