code
stringlengths
17
6.64M
class NoiseLayer(nn.Module): def __init__(self, in_planes, out_planes, level): super(NoiseLayer, self).__init__() self.noise = nn.Parameter(torch.Tensor(0), requires_grad=False).to(device) self.level = level self.layers = nn.Sequential(nn.ReLU(True), nn.BatchNorm2d(in_planes), nn....
class NoiseBasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1, shortcut=None, level=0.2): super(NoiseBasicBlock, self).__init__() self.layers = nn.Sequential(NoiseLayer(in_planes, planes, level), nn.MaxPool2d(stride, stride), nn.BatchNorm2d(planes), nn.ReLU(Tr...
class NoiseBottleneck(nn.Module): expansion = 4 def __init__(self, in_planes, planes, stride=1, shortcut=None, level=0.2): super(NoiseBottleneck, self).__init__() self.layers = nn.Sequential(nn.Conv2d(in_planes, planes, kernel_size=1, bias=False), nn.BatchNorm2d(planes), nn.ReLU(True), NoiseL...
class NoiseResNet(nn.Module): def __init__(self, block, nblocks, nchannels, nfilters, nclasses, pool, level): super(NoiseResNet, self).__init__() self.in_planes = nfilters self.pre_layers = nn.Sequential(nn.Conv2d(nchannels, nfilters, kernel_size=7, stride=2, padding=3, bias=False), nn.Ba...
def noiseresnet18(nchannels, nfilters, nclasses, pool=7, level=0.1): return NoiseResNet(NoiseBasicBlock, [2, 2, 2, 2], nchannels=nchannels, nfilters=nfilters, nclasses=nclasses, pool=pool, level=level)
def noiseresnet34(nchannels, nfilters, nclasses, pool=7, level=0.1): return NoiseResNet(NoiseBasicBlock, [3, 4, 6, 3], nchannels=nchannels, nfilters=nfilters, nclasses=nclasses, pool=pool, level=level)
def noiseresnet50(nchannels, nfilters, nclasses, pool=7, level=0.1): return NoiseResNet(NoiseBottleneck, [3, 4, 6, 3], nchannels=nchannels, nfilters=nfilters, nclasses=nclasses, pool=pool, level=level)
def noiseresnet101(nchannels, nfilters, nclasses, pool=7, level=0.1): return NoiseResNet(NoiseBottleneck, [3, 4, 23, 3], nchannels=nchannels, nfilters=nfilters, nclasses=nclasses, pool=pool, level=level)
def noiseresnet152(nchannels, nfilters, nclasses, pool=7, level=0.1): return NoiseResNet(NoiseBottleneck, [3, 8, 36, 3], nchannels=nchannels, nfilters=nfilters, nclasses=nclasses, pool=pool, level=level)
class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(((16 * 5) * 5), 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linea...
def conv3x3(in_planes, out_planes, stride=1): '3x3 convolution with padding' return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 ...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, p...
class ResNet(nn.Module): def __init__(self, block, layers, nchannels, nfilters, nclasses=1000): self.inplanes = nfilters super(ResNet, self).__init__() self.conv1 = nn.Conv2d(nchannels, nfilters, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(nfilters) ...
def resnet18(nchannels, nfilters, nclasses): return ResNet(BasicBlock, [2, 2, 2, 2], nchannels=nchannels, nfilters=nfilters, nclasses=nclasses)
def resnet34(nchannels, nfilters, nclasses): return ResNet(BasicBlock, [3, 4, 6, 3], nchannels=nchannels, nfilters=nfilters, nclasses=nclasses)
def resnet50(nchannels, nfilters, nclasses): return ResNet(Bottleneck, [3, 4, 6, 3], nchannels=nchannels, nfilters=nfilters, nclasses=nclasses)
def resnet101(nchannels, nfilters, nclasses): return ResNet(Bottleneck, [3, 4, 23, 3], nchannels=nchannels, nfilters=nfilters, nclasses=nclasses)
def resnet152(nchannels, nfilters, nclasses): return ResNet(Bottleneck, [3, 8, 36, 3], nchannels=nchannels, nfilters=nfilters, nclasses=nclasses)
class Image(): def __init__(self, path, ext='png'): if (os.path.isdir(path) == False): os.makedirs(path) self.path = path self.names = [] self.ext = ext self.iteration = 1 self.num = 0 def register(self, modules): self.num = (self.num + len...
class Logger(): def __init__(self, path, filename): self.num = 0 if (os.path.isdir(path) == False): os.makedirs(path) self.filename = os.path.join(path, filename) self.fid = open(self.filename, 'w') self.fid.close() def register(self, modules): sel...
class Monitor(): def __init__(self, smoothing=True, smoothness=0.7): self.keys = [] self.losses = {} self.smoothing = smoothing self.smoothness = smoothness self.num = 0 def register(self, modules): for m in modules: self.keys.append(m) ...
class Visualizer(): def __init__(self, port, title): self.keys = [] self.values = {} self.viz = visdom.Visdom(port=port) self.iteration = 0 self.title = title def register(self, modules): for key in modules: self.keys.append(key) self.v...
class Trainer(): def __init__(self, args, model, criterion): self.args = args self.model = model self.criterion = criterion self.port = args.port self.dir_save = args.save self.cuda = args.cuda self.nepochs = args.nepochs self.nclasses = args.nclass...
def readtextfile(filename): with open(filename) as f: content = f.readlines() f.close() return content
def writetextfile(data, filename): with open(filename, 'w') as f: f.writelines(data) f.close()
def delete_file(filename): if (os.path.isfile(filename) == True): os.remove(filename)
def eformat(f, prec, exp_digits): s = ('%.*e' % (prec, f)) (mantissa, exp) = s.split('e') return ('%se%+0*d' % (mantissa, (exp_digits + 1), int(exp)))
def saveargs(args): path = args.logs if (os.path.isdir(path) == False): os.makedirs(path) with open(os.path.join(path, 'args.txt'), 'w') as f: for arg in vars(args): f.write((((arg + ' ') + str(getattr(args, arg))) + '\n'))
class Dataloader(): def __init__(self, args, input_size): self.args = args self.dataset_test_name = args.dataset_test self.dataset_train_name = args.dataset_train self.input_size = input_size if (self.dataset_train_name == 'LSUN'): self.dataset_train = getattr(...
class FileList(data.Dataset): def __init__(self, ifile, lfile=None, split_train=1.0, split_test=0.0, train=True, transform_train=None, transform_test=None, loader_input=loaders.loader_image, loader_label=loaders.loader_torch): self.ifile = ifile self.lfile = lfile self.train = train ...
def is_image_file(filename): return any((filename.endswith(extension) for extension in IMG_EXTENSIONS))
def make_dataset(classlist, labellist=None): images = [] labels = [] classes = utils.readtextfile(ifile) classes = [x.rstrip('\n') for x in classes] classes.sort() for i in len(classes): for fname in os.listdir(classes[i]): if is_image_file(fname): label = {...
class FolderList(data.Dataset): def __init__(self, ifile, lfile=None, split_train=1.0, split_test=0.0, train=True, transform_train=None, transform_test=None, loader_input=loaders.loader_image, loader_label=loaders.loader_torch): (imagelist, labellist) = make_dataset(ifile, lfile) if (len(imagelis...
def loader_image(path): return Image.open(path).convert('RGB')
def loader_torch(path): return torch.load(path)
def loader_numpy(path): return np.load(path)
class Model(): def __init__(self, args): self.cuda = torch.cuda.is_available() self.lr = args.learning_rate self.dataset_train_name = args.dataset_train self.nfilters = args.nfilters self.batch_size = args.batch_size self.level = args.level self.net_type = ...
class PerturbLayerFirst(nn.Module): def __init__(self, in_channels=None, out_channels=None, nmasks=None, level=None, filter_size=None, debug=False, use_act=False, stride=1, act=None, unique_masks=False, mix_maps=None, train_masks=False, noise_type='uniform', input_size=None): super(PerturbLayerFirst, sel...
class PerturbLayer(nn.Module): def __init__(self, in_channels=None, out_channels=None, nmasks=None, level=None, filter_size=None, debug=False, use_act=False, stride=1, act=None, unique_masks=False, mix_maps=None, train_masks=False, noise_type='uniform', input_size=None): super(PerturbLayer, self).__init_...
class PerturbBasicBlock(nn.Module): expansion = 1 def __init__(self, in_channels=None, out_channels=None, stride=1, shortcut=None, nmasks=None, train_masks=False, level=None, use_act=False, filter_size=None, act=None, unique_masks=False, noise_type=None, input_size=None, pool_type=None, mix_maps=None): ...
class PerturbResNet(nn.Module): def __init__(self, block, nblocks=None, avgpool=None, nfilters=None, nclasses=None, nmasks=None, input_size=32, level=None, filter_size=None, first_filter_size=None, use_act=False, train_masks=False, mix_maps=None, act=None, scale_noise=1, unique_masks=False, debug=False, noise_ty...
class LeNet(nn.Module): def __init__(self, nfilters=None, nclasses=None, nmasks=None, level=None, filter_size=None, linear=128, input_size=28, debug=False, scale_noise=1, act='relu', use_act=False, first_filter_size=None, pool_type=None, dropout=None, unique_masks=False, train_masks=False, noise_type='uniform', ...
class CifarNet(nn.Module): def __init__(self, nfilters=None, nclasses=None, nmasks=None, level=None, filter_size=None, input_size=32, linear=256, scale_noise=1, act='relu', use_act=False, first_filter_size=None, pool_type=None, dropout=None, unique_masks=False, debug=False, train_masks=False, noise_type='uniform...
class NoiseLayer(nn.Module): def __init__(self, in_planes, out_planes, level): super(NoiseLayer, self).__init__() self.noise = nn.Parameter(torch.Tensor(0), requires_grad=False).to(device) self.level = level self.layers = nn.Sequential(nn.ReLU(True), nn.BatchNorm2d(in_planes), nn....
class NoiseBasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1, shortcut=None, level=0.2): super(NoiseBasicBlock, self).__init__() self.layers = nn.Sequential(NoiseLayer(in_planes, planes, level), nn.MaxPool2d(stride, stride), nn.BatchNorm2d(planes), nn.ReLU(Tr...
class NoiseResNet(nn.Module): def __init__(self, block, nblocks, nfilters, nclasses, pool, level, first_filter_size=3): super(NoiseResNet, self).__init__() self.in_planes = nfilters if (first_filter_size == 7): pool = 1 self.pre_layers = nn.Sequential(nn.Conv2d(3, ...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2...
class ResNet(nn.Module): def __init__(self, block, num_blocks, nfilters=64, avgpool=4, nclasses=10): super(ResNet, self).__init__() self.in_planes = nfilters self.avgpool = avgpool self.conv1 = nn.Conv2d(3, nfilters, kernel_size=3, stride=1, padding=1, bias=False) self.bn1...
def resnet18(nfilters, avgpool=4, nclasses=10, nmasks=32, level=0.1, filter_size=0, first_filter_size=0, pool_type=None, input_size=None, scale_noise=1, act='relu', use_act=True, dropout=0.5, unique_masks=False, noise_type='uniform', train_masks=False, debug=False, mix_maps=None): return ResNet(BasicBlock, [2, 2,...
def noiseresnet18(nfilters, avgpool=4, nclasses=10, nmasks=32, level=0.1, filter_size=0, first_filter_size=7, pool_type=None, input_size=None, scale_noise=1, act='relu', use_act=True, dropout=0.5, unique_masks=False, debug=False, noise_type='uniform', train_masks=False, mix_maps=None): return NoiseResNet(NoiseBas...
def perturb_resnet18(nfilters, avgpool=4, nclasses=10, nmasks=32, level=0.1, filter_size=0, first_filter_size=0, pool_type=None, input_size=None, scale_noise=1, act='relu', use_act=True, dropout=0.5, unique_masks=False, debug=False, noise_type='uniform', train_masks=False, mix_maps=None): return PerturbResNet(Per...
def lenet(nfilters, avgpool=None, nclasses=10, nmasks=32, level=0.1, filter_size=3, first_filter_size=0, pool_type=None, input_size=None, scale_noise=1, act='relu', use_act=True, dropout=0.5, unique_masks=False, debug=False, noise_type='uniform', train_masks=False, mix_maps=None): return LeNet(nfilters=nfilters, ...
def cifarnet(nfilters, avgpool=None, nclasses=10, nmasks=32, level=0.1, filter_size=3, first_filter_size=0, pool_type=None, input_size=None, scale_noise=1, act='relu', use_act=True, dropout=0.5, unique_masks=False, debug=False, noise_type='uniform', train_masks=False, mix_maps=None): return CifarNet(nfilters=nfil...
class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.linear = nn.Linear(((9 * 6) * 6), 10) self.noise = nn.Parameter(torch.Tensor(1, 1, 28, 28), requires_grad=True) self.noise.data.uniform_((- 1), 1) self.layers = nn.Sequential(nn.Conv2d(1, 9, kernel_...
class Normalize(nn.Module): def __init__(self, mean, std): super(Normalize, self).__init__() self.register_buffer('mean', torch.Tensor(mean)) self.register_buffer('std', torch.Tensor(std)) def forward(self, x): mean = self.mean.reshape(1, 3, 1, 1) std = self.std.resha...
def add_data_normalization(model, mean, std): norm_layer = Normalize(mean=mean, std=std) model_ = torch.nn.Sequential(norm_layer, model) return model_
def apply_attack_on_dataset(model, dataloader, attack, epsilons, device, verbose=True): robust_accuracy = [] c_a = [] for (images, labels) in dataloader: (images, labels) = (images.to(device), labels.to(device)) outputs = model(images) (_, pre) = torch.max(outputs.data, 1) ...
def apply_attack_on_batch(model, images, labels, attack, device): (images, labels) = (images.to(device), labels.to(device)) outputs = model(images) (_, pre) = torch.max(outputs.data, 1) correct_predictions = (pre == labels) correct_predictions = correct_predictions.cpu().numpy() clean_accuracy...
def plot_accuracy(x, accuracy, methods, title, xlabel='x', ylabel='accuracy'): for i in range(len(methods)): plt.plot(x, accuracy[i], label=methods[i]) plt.legend() plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title(title) plt.show()
def imshow(img, title): npimg = img.numpy() fig = plt.figure(figsize=(15, 15)) plt.imshow(np.transpose(npimg, (1, 2, 0))) plt.title(title) plt.show()
class Conv2dGrad(autograd.Function): @staticmethod def forward(context, input, weight, bias, stride, padding, dilation, groups): (context.stride, context.padding, context.dilation, context.groups) = (stride, padding, dilation, groups) context.save_for_backward(input, weight, bias) out...
class LinearGrad(autograd.Function): @staticmethod def forward(context, input, weight, bias=None): context.save_for_backward(input, weight, bias) output = torch.nn.functional.linear(input, weight, bias) return output @staticmethod def backward(context, grad_output): (...
class Conv2dGrad(autograd.Function): '\n Autograd Function that Does a backward pass using the weight_backward matrix of the layer\n ' @staticmethod def forward(context, input, weight, weight_backward, bias, bias_backward, stride, padding, dilation, groups): (context.stride, context.padding...
class LinearGrad(autograd.Function): '\n Autograd Function that Does a backward pass using the weight_backward matrix of the layer\n ' @staticmethod def forward(context, input, weight, weight_backward, bias=None, bias_backward=None): context.save_for_backward(input, weight, weight_backward,...
def select_loss_function(loss_function_config): if (loss_function_config['name'] == 'cross_entropy'): return torch.nn.CrossEntropyLoss()
def create_lr_scheduler(lr_scheduler_config, optimizer): gamma = lr_scheduler_config['gamma'] if (lr_scheduler_config['type'] == 'multistep_lr'): lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=lr_scheduler_config['milestones'], gamma=gamma, verbose=True) else: ra...
def create_optimizer(optimizer_config, model): lr = optimizer_config['lr'] weight_decay = optimizer_config['weight_decay'] momentum = optimizer_config['momentum'] if (optimizer_config['type'] == 'RMSProp'): optimizer = torch.optim.RMSprop(model.parameters(), lr=lr, momentum=momentum, weight_de...
class Benchmark(): def __init__(self, config_file): self.config_file_path = config_file self.config_file = read_yaml(config_file) validate_config(self.config_file, 'benchmark', defaults=True) torch.manual_seed(self.config_file['experiment']['seed']) random.seed(self.config...
def __main__(): parser = argparse.ArgumentParser(description='BioTorch') parser.add_argument('--config_file', help='Path to the configuration file') try: args = parser.parse_args() benchmark = Benchmark(args.config_file) if (benchmark.benchmark_mode == 'training'): benc...
class CIFAR100(Dataset): def __str__(self): return 'CIFAR-100 Dataset' def __init__(self, target_size, dataset_path='./datasets/cifar100', train_transforms=None, test_transforms=None): self.mean = (0.5071, 0.4867, 0.4408) self.std = (0.2675, 0.2565, 0.2761) self.num_classes =...
class CIFAR10(Dataset): def __str__(self): return 'CIFAR-10 Dataset' def __init__(self, target_size, dataset_path='./datasets/cifar10', train_transforms=None, test_transforms=None): self.mean = (0.4914, 0.4821, 0.4465) self.std = (0.247, 0.2435, 0.2616) self.num_classes = 10 ...
class CIFAR10Benchmark(Dataset): def __str__(self): return 'CIFAR-10 Benchmark Dataset' def __init__(self, target_size, dataset_path='./datasets/cifar10', train_transforms=None, test_transforms=None): self.mean = (0.4914, 0.4821, 0.4465) self.std = (0.247, 0.2435, 0.2616) sel...
class Dataset(object): def __init__(self, target_size, dataset_path, mean=None, std=None, train_transforms=None, test_transforms=None): self.dataset_path = dataset_path self.target_size = target_size self.mean = mean self.std = std self.train_transforms = train_transforms ...
class FashionMNIST(Dataset): def __str__(self): return 'Fashion MNIST Dataset' def __init__(self, target_size, dataset_path='./datasets/fashion-mnist', train_transforms=None, test_transforms=None): self.mean = (0.2859,) self.std = (0.353,) self.num_classes = 10 super(...
class ImageNet(Dataset): def __str__(self): return 'Imagenet Dataset' def __init__(self, target_size, dataset_path='./datasets/imagenet', train_transforms=None, test_transforms=None): self.mean = (0.485, 0.456, 0.406) self.std = (0.229, 0.224, 0.225) self.num_classes = 1000 ...
class MNIST(Dataset): def __str__(self): return 'MNIST Dataset' def __init__(self, target_size, dataset_path='./datasets/mnist', train_transforms=None, test_transforms=None): self.mean = (0.1307,) self.std = (0.3081,) self.num_classes = 10 super(MNIST, self).__init__(...
class DatasetSelector(): def __init__(self, dataset_name): if (dataset_name not in DATASETS_AVAILABLE): raise ValueError('Dataset name specified: {} not in the list of available datasets {}'.format(dataset_name, DATASETS_AVAILABLE)) self.dataset_name = dataset_name def get_datase...
class Evaluator(): def __init__(self, model, mode, loss_function, dataloader, device, output_dir, multi_gpu=False): self.model = model self.mode = mode self.output_dir = output_dir self.logs_dir = os.path.join(output_dir, 'logs') self.loss_function = loss_function ...
class Conv2d(nn.Conv2d): def __init__(self, in_channels: int, out_channels: int, kernel_size: _size_2_t, stride: _size_2_t=1, padding: Union[(str, _size_2_t)]=0, dilation: _size_2_t=1, groups: int=1, bias: bool=True, padding_mode: str='zeros', layer_config: dict=None): super(Conv2d, self).__init__(in_cha...
class Linear(nn.Linear): def __init__(self, in_features: int, out_features: int, bias: bool=True, layer_config: dict=None) -> None: super(Linear, self).__init__(in_features, out_features, bias) self.layer_config = layer_config if (self.layer_config is None): self.layer_config ...
class Conv2d(fa_constructor.Conv2d): '\n Implements the method from How Important Is Weight Symmetry in Backpropagation?\n with the modification of taking the absolute value of the Backward Matrix\n\n Batchwise Random Magnitude Sign-concordant Feedbacks (brSF):\n weight_backward = |M| ◦ sign(weight), ...
class Linear(fa_constructor.Linear): '\n Implements the method from How Important Is Weight Symmetry in Backpropagation?\n with the modification of taking the absolute value of the Backward Matrix\n\n Batchwise Random Magnitude Sign-concordant Feedbacks (brSF):\n weight_backward = |M| ◦ sign(weight), ...
class Conv2d(nn.Conv2d): def __init__(self, in_channels: int, out_channels: int, output_dim: int, kernel_size: _size_2_t, stride: _size_2_t=1, padding: Union[(str, _size_2_t)]=0, dilation: _size_2_t=1, groups: int=1, bias: bool=True, padding_mode: str='zeros', layer_config: dict=None): super(Conv2d, self...
class Linear(nn.Linear): def __init__(self, in_features: int, out_features: int, output_dim: int, bias: bool=True, layer_config: dict=None) -> None: super(Linear, self).__init__(in_features, out_features, bias) self.layer_config = layer_config if ('options' not in self.layer_config): ...
class Conv2d(fa_constructor.Conv2d): def __init__(self, in_channels: int, out_channels: int, kernel_size: _size_2_t, stride: _size_2_t=1, padding: Union[(str, _size_2_t)]=0, dilation: _size_2_t=1, groups: int=1, bias: bool=True, padding_mode: str='zeros', layer_config: dict=None): if (layer_config is Non...
class Linear(fa_constructor.Linear): def __init__(self, in_features: int, out_features: int, bias: bool=True, layer_config: dict=None) -> None: if (layer_config is None): layer_config = {} layer_config['type'] = 'fa' super(Linear, self).__init__(in_features, out_features, bias...
class Conv2d(nn.Conv2d): def __init__(self, in_channels: int, out_channels: int, kernel_size: _size_2_t, stride: _size_2_t=1, padding: Union[(str, _size_2_t)]=0, dilation: _size_2_t=1, groups: int=1, bias: bool=True, padding_mode: str='zeros', layer_config: dict=None): super(Conv2d, self).__init__(in_cha...
class Linear(nn.Linear): def __init__(self, in_features: int, out_features: int, bias: bool=True, layer_config: dict=None) -> None: super(Linear, self).__init__(in_features, out_features, bias) self.layer_config = layer_config if (self.layer_config is None): self.layer_config ...
class Conv2d(fa_constructor.Conv2d): '\n Implements the method from How Important Is Weight Symmetry in Backpropagation?\n with the modification of taking the absolute value of the Backward Matrix\n\n Fixed Random Magnitude Sign-concordant Feedbacks (frSF):\n weight_backward = |M| ◦ sign(weight), wher...
class Linear(fa_constructor.Linear): '\n Implements the method from How Important Is Weight Symmetry in Backpropagation?\n with the modification of taking the absolute value of the Backward Matrix\n\n Fixed Random Magnitude Sign-concordant Feedbacks (frSF):\n weight_backward = |M| ◦ sign(weight), wher...
def compute_matrix_angle(A, B): with torch.no_grad(): flat_A = torch.reshape(A, ((- 1),)) normalized_flat_A = (flat_A / torch.norm(flat_A)) flat_B = torch.reshape(B, ((- 1),)) normalized_flat_B = (flat_B / torch.norm(flat_B)) angle = ((180.0 / math.pi) * torch.arccos(torch....
class Conv2d(fa_constructor.Conv2d): '\n Implements the method from How Important Is Weight Symmetry in Backpropagation?\n\n Uniform Sign-concordant Feedbacks (uSF):\n Backward Weights = sign(W)\n\n (https://arxiv.org/pdf/1510.05067.pdf)\n ' def __init__(self, in_channels: int, out_channels: i...
class Linear(fa_constructor.Linear): '\n Method from [How Important Is Weight Symmetry in Backpropagation?](https://arxiv.org/pdf/1510.05067.pdf)\n\n Uniform Sign-concordant Feedbacks (uSF):\n weight_backward = sign(weight)\n\n ' def __init__(self, in_features: int, out_features: int, bias: bool=...
def convert_layer(layer, mode, copy_weights, layer_config=None, output_dim=None): (layer_bias, bias_weight) = (False, None) if (('weight' in layer.__dict__['_parameters']) and copy_weights): weight = layer.weight if (('bias' in layer.__dict__['_parameters']) and (layer.bias is not None)): ...
def alexnet(pretrained: bool=False, progress: bool=True, num_classes: int=1000, layer_config=None) -> AlexNet: 'AlexNet model architecture from the\n `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper.\n The required minimum input size of the model is 63x63.\n Args:\n pretrained (bool...
def densenet121(pretrained: bool=False, progress: bool=True, num_classes: int=1000, layer_config=None) -> DenseNet: 'Densenet-121 model from\n `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_.\n The required minimum input size of the model is 29x29.\n Args:\n pr...
def densenet161(pretrained: bool=False, progress: bool=True, num_classes: int=1000, layer_config=None) -> DenseNet: 'Densenet-161 model from\n `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_.\n The required minimum input size of the model is 29x29.\n Args:\n pr...
def densenet169(pretrained: bool=False, progress: bool=True, num_classes: int=1000, layer_config=None) -> DenseNet: 'Densenet-169 model from\n `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_.\n The required minimum input size of the model is 29x29.\n Args:\n pr...
def densenet201(pretrained: bool=False, progress: bool=True, num_classes: int=1000, layer_config=None) -> DenseNet: 'Densenet-201 model from\n `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_.\n The required minimum input size of the model is 29x29.\n Args:\n pr...