AmanC007/Spiking-CODER-V1
Text Generation β’ 3B β’ Updated β’ 6
prompt stringlengths 4 63.1k | output stringlengths 15 60.2k |
|---|---|
def seed_all(seed=1029): | random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed) # if you are using multi-GPU.
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
def fwrit... |
def fwrite(log_file, s): | with open(log_file, 'a', buffering=1) as fp:
fp.write(s)
def get_logger(filename, verbosity=1, name=None):
level_dict = {0: logging.DEBUG, 1: logging.INFO, 2: logging.WARNING}
formatter = logging.Formatter(
"[%(asctime)s][%(filename)s][line:%(lineno)d][%(levelname)s] %(message)s"
)
... |
def get_logger(filename, verbosity=1, name=None): | level_dict = {0: logging.DEBUG, 1: logging.INFO, 2: logging.WARNING}
formatter = logging.Formatter(
"[%(asctime)s][%(filename)s][line:%(lineno)d][%(levelname)s] %(message)s"
)
logger = logging.getLogger(name)
logger.setLevel(level_dict[verbosity])
fh = logging.FileHandler(filename, "w")
... |
def BPTT_attack(model, image, T): | model.set_simulation_time(T, mode='bptt')
output = model(image).mean(0)
model.set_simulation_time(T)
return output
def BPTR_attack(model, image, T):
model.set_simulation_time(T, mode='bptr')
output = model(image).mean(0)
model.set_simulation_time(T)
return output
def BPTR2_attack(model... |
def BPTR_attack(model, image, T): | model.set_simulation_time(T, mode='bptr')
output = model(image).mean(0)
model.set_simulation_time(T)
return output
def BPTR2_attack(model, image, T):
model.set_simulation_time(T, mode='bptr2')
output = model(image).mean(0)
model.set_simulation_time(T)
return output
def BPTR3_attack(mod... |
def BPTR2_attack(model, image, T): | model.set_simulation_time(T, mode='bptr2')
output = model(image).mean(0)
model.set_simulation_time(T)
return output
def BPTR3_attack(model, image, T):
model.set_simulation_time(T, mode='bptr3')
output = model(image).mean(0)
model.set_simulation_time(T)
return output
def AVG_attack(mode... |
def BPTR3_attack(model, image, T): | model.set_simulation_time(T, mode='bptr3')
output = model(image).mean(0)
model.set_simulation_time(T)
return output
def AVG_attack(model, image, T):
model.set_simulation_time(T, mode='avg')
output = model(image).mean(0)
model.set_simulation_time(T)
return output
def Act_attack(model, i... |
def AVG_attack(model, image, T): | model.set_simulation_time(T, mode='avg')
output = model(image).mean(0)
model.set_simulation_time(T)
return output
def Act_attack(model, image, T):
model.set_simulation_time(0, mode='act')
output = model(image)
model.set_simulation_time(T)
return output |
def Act_attack(model, image, T): | model.set_simulation_time(0, mode='act')
output = model(image)
model.set_simulation_time(T)
return output |
import logging
import os
import random | import numpy as np
import torch
import torch.nn as nn |
class Cutout(object): | """Randomly mask out one or more patches from an image.
Args:
n_holes (int): Number of patches to cut out of each image.
length (int): The length (in pixels) of each square patch.
"""
def __init__(self, n_holes, length):
self.n_holes = n_holes
self.length = length
de... |
def build_cifar(cutout=True, use_cifar10=True, download=True): | aug = [transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(),transforms.ToTensor()]
if cutout:
aug.append(Cutout(n_holes=1, length=16))
if use_cifar10:
# aug.append(
# transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), )
transfor... |
def build_svhn(cutout=True, download=False): | aug = [transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip()]
aug.append(transforms.ToTensor())
if cutout:
aug.append(cutout(n_holes=1, length=16))
transform_train = transforms.Compose(aug)
transform_test = transforms.ToTensor()
train_dataset = SVHN(root='~/datasets/'... |
def build_dvscifar(root, time=10): | def t(data):
aug = transforms.Compose([transforms.Resize(size=(48, 48)), transforms.RandomHorizontalFlip()])
data = torch.from_numpy(data)
data = aug(data).float()
return data
def tt(data):
aug = transforms.Resize(size=(48, 48))
data = torch.from_numpy(data)
... |
def build_dvsgesture(root): | def t(data):
aug = transforms.Compose([transforms.Resize(size=(64, 64)), transforms.RandomHorizontalFlip()])
data = torch.from_numpy(data)
data = aug(data).float()
return data
def tt(data):
aug = transforms.Resize(size=(64, 64))
data = torch.from_numpy(data)
... |
def build_nmnist(root, time=10): | def t(data):
aug = transforms.RandomHorizontalFlip()
data = torch.from_numpy(data)
data = aug(data).float()
return data
def tt(data):
data = torch.from_numpy(data).float()
return data
train_dataset = NMNIST(root=root, train=True, data_type='frame', frames_num... |
def build_imagenet(root): | train_root = os.path.join(root, 'ILSVRC2012_train')
val_root = os.path.join(root, 'ILSVRC2012_val')
train_dataset = ImageFolder(
train_root,
transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
... |
def __init__(self, n_holes, length): | self.n_holes = n_holes
self.length = length
def __call__(self, img):
"""
Args:
img (Tensor): Tensor image of size (C, H, W).
Returns:
Tensor: Image with n_holes of dimension length x length cut out of it.
"""
h = img.size(1)
w = img.size(2)
mask = np.ones((h, w), np... |
def __call__(self, img): | """
Args:
img (Tensor): Tensor image of size (C, H, W).
Returns:
Tensor: Image with n_holes of dimension length x length cut out of it.
"""
h = img.size(1)
w = img.size(2)
mask = np.ones((h, w), np.float32)
for n in range(self.n_holes):
y = np.random.randint(h)
... |
def t(data): | aug = transforms.Compose([transforms.Resize(size=(48, 48)), transforms.RandomHorizontalFlip()])
data = torch.from_numpy(data)
data = aug(data).float()
return data
def tt(data):
aug = transforms.Resize(size=(48, 48))
data = torch.from_numpy(data)
data = aug(da... |
def tt(data): | aug = transforms.Resize(size=(48, 48))
data = torch.from_numpy(data)
data = aug(data).float()
return data
data1 = CIFAR10DVS(root=root, data_type='frame', frames_number=time, split_by='number', transform=t)
train_dataset, _ = torch.utils.data.random_split(data1, [9000, 1000], ge... |
def t(data): | aug = transforms.Compose([transforms.Resize(size=(64, 64)), transforms.RandomHorizontalFlip()])
data = torch.from_numpy(data)
data = aug(data).float()
return data
def tt(data):
aug = transforms.Resize(size=(64, 64))
data = torch.from_numpy(data)
data = aug(da... |
def tt(data): | aug = transforms.Resize(size=(64, 64))
data = torch.from_numpy(data)
data = aug(data).float()
return data
train_dataset = DVS128Gesture(root=root, train=True, data_type='frame', frames_number=10, split_by='number', transform=t)
val_dataset = DVS128Gesture(root=root, train=False,... |
def t(data): | aug = transforms.RandomHorizontalFlip()
data = torch.from_numpy(data)
data = aug(data).float()
return data
def tt(data):
data = torch.from_numpy(data).float()
return data
train_dataset = NMNIST(root=root, train=True, data_type='frame', frames_number=time, split_b... |
def tt(data): | data = torch.from_numpy(data).float()
return data
train_dataset = NMNIST(root=root, train=True, data_type='frame', frames_number=time, split_by='number', transform=t)
val_dataset = NMNIST(root=root, train=False, data_type='frame', frames_number=time, split_by='number', transform=tt)
return t... |
import json
import os
import random
import warnings
from os import listdir
from os.path import isfile, join
import numpy as np
import torch
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, Dataset, random_split
from torchvision.datasets import CIFAR10, CIFAR100, MNIST, SVHN, ImageFol... | mask[y1: y2, x1: x2] = 0.
mask = torch.from_numpy(mask)
mask = mask.expand_as(img)
img = img * mask
return img
transform_test = transforms.Compose([
transforms.ToTensor(),
])
train_dataset = CIFAR100(root='/home/datasets/',
... |
def main(): | global args
dvs = False
gamma_start, gamma_end, gamma_step = 80, 190, 10
if args.dataset.lower() == 'cifar10':
use_cifar10 = True
num_labels = 10
elif args.dataset.lower() == 'cifar100':
use_cifar10 = False
num_labels = 100
elif args.dataset.lower() == 'svhn':
... |
import argparse
import os
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim
import attack
import data_loaders
from functions import *
from models import *
from utils import *
from functions import *
parser = argparse.ArgumentParser(description='PyTorch Training')
# just use ... | model = CNNDVS(args.time, num_labels, args.tau, 2, init_s)
elif 'vggdvs' in args.model.lower():
model = VGGDVS(args.model.lower(), args.time, num_labels, znorm, args.tau)
elif 'vgg' in args.model.lower():
model = VGG(args.model.lower(), args.time, num_labels, znorm, args.tau)
elif 'r... |
def update_gamma(model, val): | for name, module in model._modules.items():
if hasattr(module, "_modules"):
model._modules[name] = update_gamma(module, val)
if module.__class__.__name__ == 'LIFSpike':
module.gamma = val
return model
def finetune_attack(model, atkmodel, test_loader, device, T, dvs, atk... |
def finetune_attack(model, atkmodel, test_loader, device, T, dvs, atk, gamma_start, gamma_end, gamma_step): | best_gamma = 1.
best_acc = 0.
for gama in range(gamma_start,gamma_end,gamma_step):
gamma = gama / 100.
update_gamma(atkmodel, gamma)
acc = val_success_rate(model, test_loader, device, T, dvs, atk)
#print(f'gamma={gamma}, acc={acc}')
if best_acc < acc:
best... |
def train(model, device, train_loader, criterion, optimizer, T, dvs): | running_loss = 0
model.train()
total = 0
correct = 0
for i, (images, labels) in enumerate(tqdm(train_loader)):
optimizer.zero_grad()
labels = labels.to(device)
images = images.to(device)
if dvs:
images = images.transpose(0, 1)
if T == 0:
... |
def train_poisson(model, device, train_loader, criterion, optimizer, T): | running_loss = 0
model.train()
M = len(train_loader)
total = 0
correct = 0
for i, (images, labels) in enumerate((train_loader)):
optimizer.zero_grad()
labels = labels.to(device)
images = images.to(device)
if T > 0:
outputs = model(images).mean(0)
... |
def advtrain(model, device, train_loader, criterion, optimizer, T, atk, dvs): | running_loss = 0
model.train()
M = len(train_loader)
total = 0
correct = 0
for i, (images, labels) in enumerate((train_loader)):
optimizer.zero_grad()
labels = labels.to(device)
images = images.to(device)
if dvs:
images = images.transpose(0, 1)
... |
def val(model, test_loader, device, T, dvs, atk=None): | correct = 0
total = 0
model.eval()
for batch_idx, (inputs, targets) in enumerate(tqdm(test_loader)):
inputs = inputs.to(device)
if dvs:
inputs = inputs.transpose(0, 1)
if atk is not None:
atk.set_model_training_mode(model_training=False, batchnorm_training... |
def val_success_rate(model, test_loader, device, T, dvs, atk=None): | correct = 0
total = 0
tt = 0
model.eval()
for batch_idx, (inputs, targets) in enumerate((test_loader)):
inputs = inputs.to(device)
if dvs:
inputs = inputs.transpose(0, 1)
#inputs = inputs.transpose(0, 1).mean(0).repeat(T,1,1,1,1)
with torch.no_grad():... |
import torch
import torch.nn.parallel
import torch.optim
from tqdm import tqdm
from models.layers import *
total += float(labels.size(0))
_, predicted = outputs.cpu().max(1)
correct += float(predicted.eq(labels.cpu()).sum().item())
return running_loss, 100 * correct / total
_, predic... | correct += float(predicted.eq(labels.cpu()).sum().item())
return running_loss, 100 * correct / total
final_acc = 100 * correct / total
return final_acc
atk.set_model_training_mode(model_training=False, batchnorm_training=False, dropout_training=False)
inputs = atk(inputs, tar... |
class FGSM(Attack): | r"""
altered from torchattack
"""
def __init__(self, model, forward_function=None, eps=0.007, T=None, **kwargs):
super().__init__("FGSM", model)
self.eps = eps
self._supported_mode = ['default', 'targeted']
self.forward_function = forward_function
self.T = T
... |
def __init__(self, model, forward_function=None, eps=0.007, T=None, **kwargs): | super().__init__("FGSM", model)
self.eps = eps
self._supported_mode = ['default', 'targeted']
self.forward_function = forward_function
self.T = T
def forward(self, images, labels):
r"""
Overridden.
"""
# images.unsqueeze_(1)
# images = images.repeat(8, 1, 1, 1, 1)
images = i... |
def forward(self, images, labels): | r"""
Overridden.
"""
# images.unsqueeze_(1)
# images = images.repeat(8, 1, 1, 1, 1)
images = images.clone().detach().to(self.device)
labels = labels.clone().detach().to(self.device)
if self.targeted:
target_labels = self._get_target_label(images, labels)
loss = nn.CrossEnt... |
import torch
import torch.nn as nn
from torchattacks.attack import Attack
# Calculate loss
if self.targeted:
cost = -loss(outputs, target_labels) | else:
cost = loss(outputs, labels)
# Update adversarial images
grad = torch.autograd.grad(cost, images, retain_graph=False, create_graph=False)[0]
adv_images = images + self.eps*grad.sign()
adv_images = torch.clamp(adv_images, min=0, max=1).detach()
return adv... |
class MIXFGSM(Attack): | r"""
altered from torchattack
"""
def __init__(self, model, forward_function_list=None, eps=0.007, T=None, **kwargs):
super().__init__("MIXFGSM", model)
self.eps = eps
self._supported_mode = ['default', 'targeted']
self.forward_function_list = forward_function_list
... |
def __init__(self, model, forward_function_list=None, eps=0.007, T=None, **kwargs): | super().__init__("MIXFGSM", model)
self.eps = eps
self._supported_mode = ['default', 'targeted']
self.forward_function_list = forward_function_list
self.T = T
def forward(self, images, labels):
r"""
Overridden.
"""
# images.unsqueeze_(1)
# images = images.repeat(8, 1, 1, 1, 1)
... |
def forward(self, images, labels): | r"""
Overridden.
"""
# images.unsqueeze_(1)
# images = images.repeat(8, 1, 1, 1, 1)
images = images.clone().detach().to(self.device)
labels = labels.clone().detach().to(self.device)
if self.targeted:
target_labels = self._get_target_label(images, labels)
loss = nn.CrossEnt... |
import torch
import torch.nn as nn
from torchattacks.attack import Attack
outputs = ff(self.model, images, self.T)
# Calculate loss
if self.targeted:
cost = -loss(outputs, target_labels)
else:
cost = loss(outputs, la... | adv_images = images + self.eps*tot_grad.sign()
adv_images = torch.clamp(adv_images, min=0, max=1).detach()
else:
outputs = self.model(images)
# Calculate loss
if self.targeted:
cost = -loss(outputs, target_labels)
... |
class MIXPGD(Attack): | r"""
altered from torchattack
"""
def __init__(self, model, forward_function_list=None, eps=0.3,
alpha=2/255, steps=40, random_start=True, T=None, **kwargs):
super().__init__("MIXPGD", model)
self.eps = eps
self.alpha = alpha
self.steps = steps
se... |
def __init__(self, model, forward_function_list=None, eps=0.3, | alpha=2/255, steps=40, random_start=True, T=None, **kwargs):
super().__init__("MIXPGD", model)
self.eps = eps
self.alpha = alpha
self.steps = steps
self.random_start = random_start
self._supported_mode = ['default', 'targeted']
self.forward_function_list = forward_function_list
... |
def forward(self, images, labels): | r"""
Overridden.
"""
images = images.clone().detach().to(self.device)
labels = labels.clone().detach().to(self.device)
if self.targeted:
target_labels = self._get_target_label(images, labels)
loss = nn.CrossEntropyLoss()
adv_images = images.clone().detach()
if self.rando... |
import torch
import torch.nn as nn
from torchattacks.attack import Attack
for _ in range(self.steps):
adv_images.requires_grad = True
if self.forward_function_list is not None:
tot_grad = 0.
for ff in self.forward_function_list:
outputs... | #images.grad.zero_()
adv_images = adv_images.detach() + self.alpha*tot_grad.sign()
delta = torch.clamp(adv_images - images, min=-self.eps, max=self.eps)
adv_images = torch.clamp(images + delta, min=0, max=1).detach()
else:
o... |
class PGD(Attack): | r"""
altered from torchattack
"""
def __init__(self, model, forward_function=None, eps=0.3,
alpha=2/255, steps=40, random_start=True, T=None, **kwargs):
super().__init__("PGD", model)
self.eps = eps
self.alpha = alpha
self.steps = steps
self.rando... |
def __init__(self, model, forward_function=None, eps=0.3, | alpha=2/255, steps=40, random_start=True, T=None, **kwargs):
super().__init__("PGD", model)
self.eps = eps
self.alpha = alpha
self.steps = steps
self.random_start = random_start
self._supported_mode = ['default', 'targeted']
self.forward_function = forward_function
self.T = ... |
def forward(self, images, labels): | r"""
Overridden.
"""
images = images.clone().detach().to(self.device)
labels = labels.clone().detach().to(self.device)
if self.targeted:
target_labels = self._get_target_label(images, labels)
loss = nn.CrossEntropyLoss()
adv_images = images.clone().detach()
if self.rando... |
import torch
import torch.nn as nn
from torchattacks.attack import Attack
for _ in range(self.steps):
adv_images.requires_grad = True
if self.forward_function is not None:
outputs = self.forward_function(self.model, adv_images, self.T)
else:
ou... | if self.targeted:
cost = -loss(outputs, target_labels)
else:
cost = loss(outputs, labels)
# Update adversarial images
grad = torch.autograd.grad(cost, adv_images,
retain_graph=False, create_graph=False... |
class VGG(nn.Module): | def __init__(self, vgg_name, T, num_class, norm, tau=1., init_c=3):
super(VGG, self).__init__()
if norm is not None and isinstance(norm, tuple):
self.norm = TensorNormalization(*norm)
else:
self.norm = TensorNormalization((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2... |
class VGGDVS(nn.Module): | def __init__(self, vgg_name, T, num_class, norm, tau=1., init_c=2, init_s=48):
super(VGGDVS, self).__init__()
self.T = T
self.tau = tau
self.init_channels = init_c
cnt = 0
for l in cfg[vgg_name]:
if len(l)>0:
cnt += 1
self.W = int... |
class Print(nn.Module): | def __init__(self) -> None:
super(Print, self).__init__()
def forward(self, x):
print(x.shape)
return x
class CNNDVS(nn.Module):
def __init__(self, T, num_class, tau=1., init_c=2, init_s=48):
super(CNNDVS, self).__init__()
self.T = T
self.tau = tau
s... |
class CNNDVS(nn.Module): | def __init__(self, T, num_class, tau=1., init_c=2, init_s=48):
super(CNNDVS, self).__init__()
self.T = T
self.tau = tau
self.init_channels = init_c
self.merge = MergeTemporalDim(T)
self.expand = ExpandTemporalDim(T)
self.poisson = False
self.w = int(... |
def __init__(self, vgg_name, T, num_class, norm, tau=1., init_c=3): | super(VGG, self).__init__()
if norm is not None and isinstance(norm, tuple):
self.norm = TensorNormalization(*norm)
else:
self.norm = TensorNormalization((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))
self.T = T
self.tau = tau
self.init_channels = init_c
if vgg_name == ... |
def hook(self, model, gradin, gradout): | self.hooked = gradin[0]
def act_hook(self, model, input, output):
x = input[0]
if self.T > 0:
x = self.expand(x)
x = x.mean(0)
self.hooked = x
def _make_layers(self, cfg):
layers = []
for x in cfg:
if x == 'A':
layers.append(nn.AvgPool2d(2))
else:
... |
def act_hook(self, model, input, output): | x = input[0]
if self.T > 0:
x = self.expand(x)
x = x.mean(0)
self.hooked = x
def _make_layers(self, cfg):
layers = []
for x in cfg:
if x == 'A':
layers.append(nn.AvgPool2d(2))
else:
layers.append(nn.Conv2d(self.init_channels, x, kernel_size=3,... |
def _make_layers(self, cfg): | layers = []
for x in cfg:
if x == 'A':
layers.append(nn.AvgPool2d(2))
else:
layers.append(nn.Conv2d(self.init_channels, x, kernel_size=3, padding=1))
layers.append(nn.BatchNorm2d(x))
layers.append(LIFSpike(T=self.T, tau=self.tau))
self.... |
def _make_classifier(self, num_class): | layer = [
nn.Flatten(),
nn.Linear(512*self.W, 4096),
LIFSpike(self.T, tau=self.tau),
nn.Linear(4096, 4096),
LIFSpike(self.T, tau=self.tau),
nn.Linear(4096, num_class)
]
return nn.Sequential(*layer)
# pass T to determine whether it is an ANN or SNN
def set_simulation_time(self, T, m... |
def set_simulation_time(self, T, mode='bptt'): | self.T = T
for module in self.modules():
if isinstance(module, (LIFSpike, ExpandTemporalDim)):
module.T = T
if isinstance(module, LIFSpike):
module.mode = mode
return
def forward(self, input):
if not self.poisson:
input = self.norm(input)
#inp... |
def forward(self, input): | if not self.poisson:
input = self.norm(input)
#input = self.blur(input)
if self.T > 0:
input = add_dimention(input, self.T)
if self.poisson:
input = self.encode(input)
input = self.merge(input)
out = self.layer1(input)
... |
def __init__(self, vgg_name, T, num_class, norm, tau=1., init_c=2, init_s=48): | super(VGGDVS, self).__init__()
self.T = T
self.tau = tau
self.init_channels = init_c
cnt = 0
for l in cfg[vgg_name]:
if len(l)>0:
cnt += 1
self.W = int(init_s/(1<<cnt))**2
self.layer1 = self._make_layers(cfg[vgg_name][0])
self.layer2 = self._make_layers(cfg[vgg... |
def _make_layers(self, cfg): | layers = []
for x in cfg:
if x == 'A':
layers.append(nn.AvgPool2d(2))
else:
layers.append(nn.Conv2d(self.init_channels, x, kernel_size=3, padding=1))
layers.append(nn.BatchNorm2d(x))
layers.append(LIFSpike(T=self.T, tau=self.tau))
self.... |
def _make_classifier(self, num_class, channels): | layer = [nn.Linear(channels*self.W, num_class)]
return nn.Sequential(*layer)
# pass T to determine whether it is an ANN or SNN
def set_simulation_time(self, T, mode='bptt'):
self.T = T
for module in self.modules():
if isinstance(module, (LIFSpike, ExpandTemporalDim)):
if isinstance(... |
def set_simulation_time(self, T, mode='bptt'): | self.T = T
for module in self.modules():
if isinstance(module, (LIFSpike, ExpandTemporalDim)):
if isinstance(module, LIFSpike):
module.mode = mode
return
def forward(self, input):
if self.T == 0:
input = input.mean(0,keepdim=False)
else:
input = s... |
def forward(self, input): | if self.T == 0:
input = input.mean(0,keepdim=False)
else:
input = self.merge(input)
out = self.layer1(input)
out = self.layer2(out)
out = self.layer3(out)
out = self.layer4(out)
out = torch.flatten(out, 1)
out = self.classifier(out)... |
def __init__(self) -> None: | super(Print, self).__init__()
def forward(self, x):
print(x.shape)
return x
class CNNDVS(nn.Module):
def __init__(self, T, num_class, tau=1., init_c=2, init_s=48):
super(CNNDVS, self).__init__()
self.T = T
self.tau = tau
self.init_channels = init_c
... |
def forward(self, x): | print(x.shape)
return x
class CNNDVS(nn.Module):
def __init__(self, T, num_class, tau=1., init_c=2, init_s=48):
super(CNNDVS, self).__init__()
self.T = T
self.tau = tau
self.init_channels = init_c
self.merge = MergeTemporalDim(T)
self.expand = Expan... |
def __init__(self, T, num_class, tau=1., init_c=2, init_s=48): | super(CNNDVS, self).__init__()
self.T = T
self.tau = tau
self.init_channels = init_c
self.merge = MergeTemporalDim(T)
self.expand = ExpandTemporalDim(T)
self.poisson = False
self.w = int(int((int((init_s+2-5)/2)+1)/2)/2)
self.layer = nn.Sequential(
nn.Conv2d(2, 16, 5, 2, 1... |
def set_simulation_time(self, T, mode='bptt'): | self.T = T
for module in self.modules():
if isinstance(module, (LIFSpike, ExpandTemporalDim)):
if isinstance(module, LIFSpike):
module.mode = mode
return
def forward(self, x: torch.Tensor):
if self.T == 0:
x = x.mean(0,keepdim=False)
else:
x = sel... |
def forward(self, x: torch.Tensor): | if self.T == 0:
x = x.mean(0,keepdim=False)
else:
x = self.merge(x)
x = self.layer(x)
x = self.classifier(x)
if self.T > 0:
x = self.expand(x)
return x |
from kornia.filters.median import MedianBlur
from models.layers import *
cfg = {
'vgg5' : [[64, 'A'],
[128, 128, 'A'],
[],
[],
[]],
'vgg11': [
[64, 'A'],
[128, 256, 'A'],
[512, 512, 512, 'A'],
[512, 512],
[]
],
... | ],
'vgggesture': [
[16, 32, 'A'],
[32, 32, 'A'],
[],
[],
[]
]
}
self.classifier = self._make_classifier(num_class)
self.merge = MergeTemporalDim(T)
self.expand = ExpandTemporalDim(T)
self.encode = Poisson()
self.poisson = False
... |
class conv(nn.Module): | def __init__(self,in_plane, out_plane, kernel_size, stride,padding, bias=True):
super(conv, self).__init__()
self.fwd = nn.Sequential(nn.Conv2d(in_plane,out_plane,kernel_size=kernel_size,stride=stride,padding=padding, bias=bias),
nn.BatchNorm2d(out_plane))
def forward(self,x):
x... |
class ResidualBlock(nn.Module): | def __init__(self, in_ch, out_ch, T, tau, stride=1, shortcut=None):
super(ResidualBlock, self).__init__()
self.in_ch = in_ch
self.out_ch = out_ch
self.stride = stride
self.conv1 = conv(in_ch, out_ch, 3, stride, 1, bias=False)
self.neuron1 = LIFSpike(T, tau=tau)
... |
class ResNet17(nn.Module): | def __init__(self, T, tau=1.0, num_class=10, norm=None):
super(ResNet17, self).__init__()
self.T = T
self.tau = tau
if norm is not None and isinstance(norm, tuple):
self.norm = TensorNormalization(*norm)
else:
self.norm = TensorNormalization((0.4914, 0... |
class ResNet19(nn.Module): | def __init__(self, T, tau=1.0, num_class=10, norm=None):
super(ResNet19, self).__init__()
self.T = T
self.tau = tau
if norm is not None and isinstance(norm, tuple):
self.norm = TensorNormalization(*norm)
else:
self.norm = TensorNormalization((0.4914, 0... |
def __init__(self,in_plane, out_plane, kernel_size, stride,padding, bias=True): | super(conv, self).__init__()
self.fwd = nn.Sequential(nn.Conv2d(in_plane,out_plane,kernel_size=kernel_size,stride=stride,padding=padding, bias=bias),
nn.BatchNorm2d(out_plane))
def forward(self,x):
x = self.fwd(x)
return x
class ResidualBlock(nn.Module):
def __init__(s... |
def forward(self,x): | x = self.fwd(x)
return x
class ResidualBlock(nn.Module):
def __init__(self, in_ch, out_ch, T, tau, stride=1, shortcut=None):
super(ResidualBlock, self).__init__()
self.in_ch = in_ch
self.out_ch = out_ch
self.stride = stride
self.conv1 = conv(in_ch, out_ch, 3... |
def __init__(self, in_ch, out_ch, T, tau, stride=1, shortcut=None): | super(ResidualBlock, self).__init__()
self.in_ch = in_ch
self.out_ch = out_ch
self.stride = stride
self.conv1 = conv(in_ch, out_ch, 3, stride, 1, bias=False)
self.neuron1 = LIFSpike(T, tau=tau)
self.conv2 = conv(out_ch, out_ch, 3, 1, 1, bias=False)
self.neuron2 = LIFSpike(T, tau=tau)
... |
def forward(self, input): | out = self.conv1(input)
out = self.neuron1(out)
out = self.conv2(out)
residual = input if self.right is None else self.right(input)
out += residual
out = self.neuron2(out)
return out
class ResNet17(nn.Module):
def __init__(self, T, tau=1.0, num_class=10, nor... |
def __init__(self, T, tau=1.0, num_class=10, norm=None): | super(ResNet17, self).__init__()
self.T = T
self.tau = tau
if norm is not None and isinstance(norm, tuple):
self.norm = TensorNormalization(*norm)
else:
self.norm = TensorNormalization((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))
self.pre_conv = conv(3, 64, 3, stride=1, pa... |
def make_layer(self, in_ch, out_ch, block_num, stride=1): | shortcut = conv(in_ch, out_ch, 1, stride, 0, bias=False)
layers = []
layers.append(ResidualBlock(in_ch, out_ch, self.T, self.tau, stride, shortcut))
for i in range(1, block_num):
layers.append(ResidualBlock(out_ch, out_ch, self.T, self.tau))
return nn.Sequential(*layers)
# pass T to determi... |
def set_simulation_time(self, T, mode='bptt'): | self.T = T
for module in self.modules():
if isinstance(module, (LIFSpike, ExpandTemporalDim)):
module.T = T
if isinstance(module, LIFSpike):
module.mode = mode
return
def forward(self, input):
if not self.poisson:
input = self.norm(input)
if s... |
def forward(self, input): | if not self.poisson:
input = self.norm(input)
if self.T > 0:
input = add_dimention(input, self.T)
if self.poisson:
input = self.encode(input)
input = self.merge(input)
x = self.pre_conv(input)
x = self.neuron1(x)
x = self.layer1(x)
x = self.layer2(x)
... |
def __init__(self, T, tau=1.0, num_class=10, norm=None): | super(ResNet19, self).__init__()
self.T = T
self.tau = tau
if norm is not None and isinstance(norm, tuple):
self.norm = TensorNormalization(*norm)
else:
self.norm = TensorNormalization((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))
self.pre_conv = conv(3, 128, 3, stride=1, p... |
def make_layer(self, in_ch, out_ch, block_num, stride=1): | shortcut = conv(in_ch, out_ch, 1, stride, 0, bias=False)
layers = []
layers.append(ResidualBlock(in_ch, out_ch, self.T, self.tau, stride, shortcut))
for i in range(1, block_num):
layers.append(ResidualBlock(out_ch, out_ch, self.T, self.tau))
return nn.Sequential(*layers)
# pass T to determ... |
def set_simulation_time(self, T, mode='bptt'): | self.T = T
for module in self.modules():
if isinstance(module, (LIFSpike, ExpandTemporalDim)):
module.T = T
if isinstance(module, LIFSpike):
module.mode = mode
return
def forward(self, input):
if not self.poisson:
input = self.norm(input)
if s... |
def forward(self, input): | if not self.poisson:
input = self.norm(input)
if self.T > 0:
input = add_dimention(input, self.T)
if self.poisson:
input = self.encode(input)
input = self.merge(input)
x = self.pre_conv(input)
x = self.neuron1(x)
x = self.layer1(x)
x = self.layer2(x)
... |
import random
from models.layers import *
self.encode = Poisson()
self.poisson = False
self.hooked_grad = None
return out | self.fc2 = nn.Linear(256, num_class)
self.merge = MergeTemporalDim(T)
self.expand = ExpandTemporalDim(T)
self.encode = Poisson()
self.poisson = False
self.hooked_grad = None
return out |
class VGG(nn.Module): | def __init__(self, vgg_name, T, num_classes, norm, tau=1., dropout=0):
super(VGG, self).__init__()
if norm is not None and isinstance(norm, tuple):
self.norm = TensorNormalization(*norm)
else:
self.norm = TensorNormalization((0.4914, 0.4822, 0.4465), (0.2023, 0.1994,... |
def __init__(self, vgg_name, T, num_classes, norm, tau=1., dropout=0): | super(VGG, self).__init__()
if norm is not None and isinstance(norm, tuple):
self.norm = TensorNormalization(*norm)
else:
self.norm = TensorNormalization((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))
self.T = T
self.tau = tau
self.init_channels = 3
self.merge = MergeT... |
def _make_layers(self, cfg, dropout): | layers = []
for x in cfg:
if x == 'M':
layers.append(nn.AvgPool2d(kernel_size=2, stride=2))
else:
layers.append(nn.Conv2d(self.init_channels, x, kernel_size=3, padding=1))
layers.append(nn.BatchNorm2d(x))
layers.append(MyFloor())
layers... |
def set_simulation_time(self, T, mode='bptt'): | self.T = T
for module in self.modules():
if isinstance(module, (LIFSpike, ExpandTemporalDim)):
module.T = T
if isinstance(module, LIFSpike):
module.mode = mode
return
def forward(self, input):
if not self.poisson:
input = self.norm(input)
if s... |
def forward(self, input): | if not self.poisson:
input = self.norm(input)
if self.T > 0:
input = add_dimention(input, self.T)
if self.poisson:
input = self.encode(input)
input = self.merge(input)
out = self.layer1(input)
out = self.layer2(out)
... |
from unicodedata import numeric
import torch.nn as nn
from models.layers import *
cfg = {
'VGG11': [
[64, 'M'],
[128, 'M'],
[256, 256, 'M'],
[512, 512, 'M'],
[512, 512, 'M']
],
'VGG13': [
[64, 64, 'M'],
[128, 128, 'M'],
[256, 256, 'M'],
... | }
self.layer4 = self._make_layers(cfg[vgg_name][3], dropout)
self.layer5 = self._make_layers(cfg[vgg_name][4], dropout)
if num_classes == 1000:
self.classifier = nn.Sequential(
nn.Flatten(),
nn.Linear(512*7*7, 4096),
MyFloor(),
... |
class MyFloor(nn.Module): | def __init__(self, up=8., t=32):
super().__init__()
self.up = nn.Parameter(torch.tensor([up]), requires_grad=True)
self.t = t
def forward(self, x):
x = x / self.up
# x = myfloor(x*self.t+0.5)/self.t
x = torch.clamp(x, 0, 1)
x = x * self.up
return ... |
class TensorNormalization(nn.Module): | def __init__(self,mean, std):
super(TensorNormalization, self).__init__()
if not isinstance(mean, torch.Tensor):
mean = torch.tensor(mean)
if not isinstance(std, torch.Tensor):
std = torch.tensor(std)
self.mean = mean
self.std = std
def forward(sel... |
def normalizex(tensor, mean, std): | mean = mean[None, :, None, None]
std = std[None, :, None, None]
if mean.device != tensor.device:
mean = mean.to(tensor.device)
std = std.to(tensor.device)
return tensor.sub(mean).div(std)
class MergeTemporalDim(nn.Module):
def __init__(self, T):
super().__init__()
se... |
This dataset contains 50,000 raw code samples extracted from open-source Spiking Neural Network (SNN) GitHub repositories.
This dataset directly captures coding patterns from real-world SNN projects, making it valuable for pretraining and structure learning.