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 |
|---|---|---|---|---|---|---|
auto_LiRPA | auto_LiRPA-master/examples/vision/efficient_convolution.py | """
Demonstration of efficient convolutional network implementation in auto_LiRPA.
auto_LiRPA library supports an efficient algorithm for computing bounds for
convolutional networks. The "patches" mode implementation makes full backward
bounds (CROWN) for convolutional layers significantly faster by using more
efficie... | 3,311 | 37.068966 | 123 | py |
auto_LiRPA | auto_LiRPA-master/examples/vision/jacobian.py | """Examples of computing Jacobian bounds.
We use a small model with two convolutional layers and dense layers respectively.
The width of the model has been reduced for the demonstration here. And we use
data from CIFAR-10.
We show examples of:
- Computing Jacobian bounds
- Computing Linf local Lipschitz constants
- C... | 4,923 | 38.079365 | 85 | py |
auto_LiRPA | auto_LiRPA-master/examples/vision/weight_perturbation_training.py | """
A simple example for certified robustness against model weight perturbations.
Since our framework works on general computational graphs, where both model
weights and model inputs are inputs of the computational graph, our
perturbation analysis can naturally be applied to the model weights, allowing
analysis for ce... | 15,760 | 48.099688 | 149 | py |
auto_LiRPA | auto_LiRPA-master/examples/vision/models/wide_resnet_imagenet64.py | import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
import sys
import numpy as np
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)
def conv_init(m):
classname = m.__class__.__n... | 3,674 | 36.121212 | 98 | py |
auto_LiRPA | auto_LiRPA-master/examples/vision/models/densenet_no_bn.py | '''DenseNet in PyTorch.
https://github.com/kuangliu/pytorch-cifar
'''
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class Bottleneck(nn.Module):
def __init__(self, in_planes, growth_rate):
super(Bottleneck, self).__init__()
# self.bn1 = nn.BatchNorm2d(in_planes)
... | 3,429 | 31.666667 | 95 | py |
auto_LiRPA | auto_LiRPA-master/examples/vision/models/wide_resnet_cifar.py | import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from torch.autograd import Variable
import sys
import numpy as np
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)
def conv_init... | 4,474 | 34.8 | 103 | py |
auto_LiRPA | auto_LiRPA-master/examples/vision/models/feedforward.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from auto_LiRPA import PerturbationLpNorm, BoundedParameter
# CNN, relatively large 4-layer
# parameter in_ch: input image channel, 1 for MNIST and 3 for CIFAR
# parameter in_dim: input dimension, 28 for MNIST and 32 for CIFAR
# parameter width: width... | 6,528 | 32.829016 | 95 | py |
auto_LiRPA | auto_LiRPA-master/examples/vision/models/densenet_imagenet.py | '''DenseNet in PyTorch.
https://github.com/kuangliu/pytorch-cifar
'''
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class Bottleneck(nn.Module):
def __init__(self, in_planes, growth_rate):
super(Bottleneck, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
... | 3,591 | 32.259259 | 95 | py |
auto_LiRPA | auto_LiRPA-master/examples/vision/models/resnet.py | '''
ResNet used in https://arxiv.org/pdf/1805.12514.pdf
https://github.com/locuslab/convex_adversarial/blob/0d11e671ad9318745a2439afce513c82dc6bf5ce/examples/problems.py
'''
import torch
import torch.nn as nn
import math
class Dense(nn.Module):
def __init__(self, *Ws):
super(Dense, self).__init__()
... | 2,966 | 29.90625 | 113 | py |
auto_LiRPA | auto_LiRPA-master/examples/vision/models/resnet18.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,265 | 35.152542 | 85 | py |
auto_LiRPA | auto_LiRPA-master/examples/vision/models/densenet.py | '''DenseNet in PyTorch.
https://github.com/kuangliu/pytorch-cifar
'''
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class Bottleneck(nn.Module):
def __init__(self, in_planes, growth_rate):
super(Bottleneck, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
... | 3,583 | 32.495327 | 95 | py |
auto_LiRPA | auto_LiRPA-master/examples/vision/models/resnext.py | '''ResNeXt in PyTorch.
See the paper "Aggregated Residual Transformations for Deep Neural Networks" for more details.
https://github.com/kuangliu/pytorch-cifar
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class Block(nn.Module):
'''Grouped convolution block.'''
expansion = 2
def... | 4,029 | 36.314815 | 128 | py |
auto_LiRPA | auto_LiRPA-master/examples/vision/models/vnncomp_resnet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1, bn=True, kernel=3):
super(BasicBlock, self).__init__()
self.bn = bn
if kernel == 3:
... | 6,514 | 38.484848 | 101 | py |
auto_LiRPA | auto_LiRPA-master/examples/vision/models/resnext_imagenet64.py | '''ResNeXt in PyTorch.
See the paper "Aggregated Residual Transformations for Deep Neural Networks" for more details.
https://github.com/kuangliu/pytorch-cifar
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class Block(nn.Module):
'''Grouped convolution block.'''
expansion = 2
def... | 3,632 | 36.453608 | 128 | py |
auto_LiRPA | auto_LiRPA-master/examples/vision/models/mobilenet.py | '''MobileNetV2 in PyTorch.
See the paper "Inverted Residuals and Linear Bottlenecks:
Mobile Networks for Classification, Detection and Segmentation" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class Block(nn.Module):
'''expand + depthwise + pointwise'''
def __init... | 3,067 | 35.094118 | 114 | py |
auto_LiRPA | auto_LiRPA-master/examples/language/lstm.py | import os
import shutil
import torch
import torch.nn as nn
import torch.nn.functional as F
from auto_LiRPA.utils import logger
from language_utils import build_vocab
class LSTMFromEmbeddings(nn.Module):
def __init__(self, args, vocab_size):
super(LSTMFromEmbeddings, self).__init__()
self.embedding... | 5,357 | 41.52381 | 96 | py |
auto_LiRPA | auto_LiRPA-master/examples/language/oracle.py | import torch
from auto_LiRPA.utils import logger
from auto_LiRPA import PerturbationSynonym
from data_utils import get_batches
def oracle(args, model, ptb, data, type):
logger.info('Running oracle for {}'.format(type))
model.eval()
assert(isinstance(ptb, PerturbationSynonym))
cnt_cor = 0
word_embed... | 2,218 | 45.229167 | 116 | py |
auto_LiRPA | auto_LiRPA-master/examples/language/train.py | import argparse
import random
import pickle
import os
import pdb
import time
import logging
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
from torch.utils.tensorboard import SummaryWriter
from auto_LiRPA import BoundedModule, BoundedTensor, P... | 13,981 | 43.670927 | 140 | py |
auto_LiRPA | auto_LiRPA-master/examples/language/Transformer/Transformer.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights rved.
#
# 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 ... | 5,616 | 41.877863 | 110 | py |
auto_LiRPA | auto_LiRPA-master/examples/language/Transformer/modeling.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# 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 cop... | 10,793 | 40.837209 | 118 | py |
auto_LiRPA | auto_LiRPA-master/examples/language/Transformer/utils.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights rved.
#
# 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 ... | 2,975 | 35.740741 | 85 | py |
auto_LiRPA | auto_LiRPA-master/examples/language/preprocess/pre_compute_lm_scores.py | # Ref: https://worksheets.codalab.org/rest/bundles/0x3f614472f4a14393b3d85d5568114591/contents/blob/precompute_lm_scores.py
"""Precompute language model scores."""
import argparse
import json
import os
import sys
import torch
from tqdm import tqdm
from data_utils import load_data
sys.path.insert(0, 'tmp/windweller-l... | 2,547 | 36.470588 | 123 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_simple_verification.py | """Test optimized bounds in simple_verification."""
import torch
import torch.nn as nn
import torchvision
from auto_LiRPA import BoundedModule, BoundedTensor
from auto_LiRPA.perturbations import PerturbationLpNorm
from auto_LiRPA.utils import Flatten
from testcase import TestCase
# This simple model comes from https:/... | 1,885 | 32.678571 | 93 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_linear_cnn_model.py | """Test bounds on a 1 layer CNN network."""
import torch.nn as nn
from auto_LiRPA import BoundedModule, BoundedTensor
from auto_LiRPA.perturbations import *
from test_linear_model import TestLinearModel
input_dim = 8
out_channel = 2
N = 10
class LinearCNNModel(nn.Module):
def __init__(self):
super().__in... | 2,523 | 39.709677 | 111 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_avgpool.py | """Test average pooling."""
import torch.nn as nn
from auto_LiRPA import BoundedModule, BoundedTensor
from auto_LiRPA.perturbations import *
import torch.nn.functional as F
import numpy as np
n_classes = 3
N = 10
torch.manual_seed(0)
class LinearModel(nn.Module):
def __init__(self):
super().__init__()
... | 1,182 | 25.886364 | 71 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_maxpool.py | """Test max pooling."""
import torch
import os
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from auto_LiRPA import BoundedModule, BoundedTensor
from auto_LiRPA.perturbations import *
from auto_LiRPA.utils import Flatten
from testcase import TestCase
class Model(nn.Module):
def __init_... | 4,827 | 43.703704 | 213 | py |
auto_LiRPA | auto_LiRPA-master/tests/testcase.py | import unittest
import random
import torch
import numpy as np
class TestCase(unittest.TestCase):
"""Superclass for unit test cases in auto_LiRPA."""
def __init__(self, methodName='runTest', seed=1, ref_path=None, generate=False):
super().__init__(methodName)
self.addTypeEqualityFunc(np.ndarra... | 2,154 | 34.327869 | 88 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_rectangle_patches.py | import torch
import random
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from auto_LiRPA import BoundedModule, BoundedTensor
from auto_LiRPA.perturbations import *
import sys
sys.path.append('../examples/vision')
import models
from testcase import TestCase
class cnn_4layer... | 2,575 | 33.810811 | 121 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_jacobian.py | """Test Jacobian bounds."""
import torch
import torch.nn as nn
import torch.nn.functional as F
from auto_LiRPA import BoundedModule, BoundedTensor
from auto_LiRPA.perturbations import *
from testcase import TestCase
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(... | 1,826 | 27.107692 | 67 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_vision_models.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from auto_LiRPA import BoundedModule, BoundedTensor
from auto_LiRPA.perturbations import *
from testcase import TestCase
class cnn_4layer_test(nn.Module):
def __init__(self):
super(cnn_4layer_test, self).__init__()
self.conv1 = nn.C... | 4,174 | 41.602041 | 120 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_constant.py | """Test BoundConstant"""
import torch
import os
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from auto_LiRPA import BoundedModule, BoundedTensor
from auto_LiRPA.perturbations import *
from testcase import TestCase
class cnn_MNIST(nn.Module):
def __init__(self):
super(cnn_MNIST, ... | 1,870 | 29.177419 | 104 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_resnet_patches.py | import torch
import numpy as np
import torchvision
from auto_LiRPA import BoundedModule, BoundedTensor
from auto_LiRPA.perturbations import *
import sys
sys.path.append('../examples/vision')
import models
from testcase import TestCase
class TestResnetPatches(TestCase):
def __init__(self, methodName='runTest', gen... | 1,875 | 35.076923 | 121 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_linear_model.py | """Test bounds on a 1 layer linear network."""
import torch.nn as nn
from auto_LiRPA import BoundedModule, BoundedTensor
from auto_LiRPA.perturbations import *
from testcase import TestCase
n_classes = 3
N = 10
class LinearModel(nn.Module):
def __init__(self):
super().__init__()
self.fc = nn.Line... | 3,694 | 35.584158 | 95 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_language_models.py | """Test classes for Transformer and LSTM on language tasks"""
import os
import argparse
import pickle
import torch
import numpy as np
import pytest
from auto_LiRPA.utils import logger
parser = argparse.ArgumentParser()
parser.add_argument('--gen_ref', action='store_true', help='generate reference results')
parser.add_... | 4,082 | 37.885714 | 110 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_bound_ops.py | """Test classes for bound operators"""
import torch
from auto_LiRPA.bound_ops import *
from auto_LiRPA.linear_bound import LinearBound
from testcase import TestCase
"""Dummy node for testing"""
class Dummy:
def __init__(self, lower, upper=None, perturbed=False):
self.lower = lower
self.upper = upp... | 5,730 | 45.217742 | 109 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_identity.py | """Test a model with an nn.Identity layer only"""
import torch
import torch.nn as nn
from auto_LiRPA import BoundedModule, BoundedTensor
from auto_LiRPA.perturbations import *
from testcase import TestCase
class TestIdentity(TestCase):
def __init__(self, methodName='runTest'):
super().__init__(methodNam... | 843 | 29.142857 | 54 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_distinct_patches.py | from numpy.core.numeric import allclose
import torch
import random
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from auto_LiRPA import BoundedModule, BoundedTensor
from auto_LiRPA.perturbations import *
import sys
sys.path.append('../examples/vision')
import models
from te... | 4,306 | 36.780702 | 125 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_1d_activation.py | """Test one dimensional activation functions (e.g., ReLU, tanh, exp, sin, etc)"""
import torch
import torch.nn as nn
from testcase import TestCase
from auto_LiRPA import BoundedModule, BoundedTensor
from auto_LiRPA.perturbations import *
from auto_LiRPA.utils import logger
# Wrap the computation with a nn.Module
class... | 6,443 | 40.844156 | 212 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_weight_perturbation.py | import copy
import subprocess
import numpy as np
from testcase import TestCase
import sys
sys.path.append('../examples/vision')
import models
from auto_LiRPA import BoundedModule
from auto_LiRPA.perturbations import *
class TestWeightPerturbation(TestCase):
def __init__(self, methodName='runTest', generate=False)... | 4,967 | 49.693878 | 141 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_state_dict_name.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from auto_LiRPA import BoundedModule
from testcase import TestCase
class FeatureExtraction(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 8, 4, stride=2, padding=1)
self.conv2 = nn.Conv2d(8, 16... | 2,054 | 27.541667 | 96 | py |
auto_LiRPA | auto_LiRPA-master/tests/test_conv.py | import torch
import os
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from auto_LiRPA import BoundedModule, BoundedTensor
from auto_LiRPA.perturbations import *
from testcase import TestCase
class Flatten(nn.Module):
def __init__(self):
super(Flatten, self).__init__()
d... | 3,156 | 34.875 | 115 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/patches.py | import torch
import torch.nn.functional as F
from torch import Tensor
def insert_zeros(image, s):
"""
Insert s columns and rows 0 between every pixel in the image. For example:
image = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
s = 2
output = [[1, 0, 0, 2, 0, 0, 3],
... | 29,151 | 55.605825 | 330 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/interval_bound.py | import torch
from .bound_ops import *
def IBP_general(self, node=None, C=None, delete_bounds_after_use=False):
def _delete_unused_bounds(node_list):
"""Delete bounds from input layers after use to save memory. Used when
sparse_intermediate_bounds_with_ibp is true."""
if delete_bounds_afte... | 5,917 | 37.934211 | 79 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/bounded_tensor.py | import copy
import torch
import torch.nn as nn
from torch import Tensor as Tensor
import torch._C as _C
class BoundedTensor(Tensor):
@staticmethod
# We need to override the __new__ method since Tensor is a C class
def __new__(cls, x, ptb, *args, **kwargs):
if isinstance(x, Tensor):
ten... | 3,491 | 32.576923 | 92 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/backward_bound.py | import torch
from torch import Tensor
from collections import deque, defaultdict
from tqdm import tqdm
from .patches import Patches
from .utils import *
from .bound_ops import *
import warnings
def batched_backward(
self, node, C, unstable_idx, batch_size, bound_lower=True,
bound_upper=True):
crow... | 38,156 | 48.044987 | 243 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/bound_general.py | import copy
import numpy as np
import warnings
from collections import OrderedDict, deque
import torch
from torch.nn import Parameter
from .bound_op_map import bound_op_map
from .bound_ops import *
from .bounded_tensor import BoundedTensor, BoundedParameter
from .parse_graph import parse_module
from .perturbations im... | 62,128 | 43.219929 | 94 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/wrapper.py | import torch
import torch.nn as nn
class CrossEntropyWrapper(nn.Module):
def __init__(self, model):
super(CrossEntropyWrapper, self).__init__()
self.model = model
def forward(self, x, labels):
y = self.model(x)
logits = y - torch.gather(y, dim=-1, index=labels.unsqueeze(-1))
... | 740 | 32.681818 | 72 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/parse_graph.py | import os
import torch
from torch.onnx.utils import _optimize_graph
from torch.onnx.symbolic_helper import _set_opset_version
from collections import OrderedDict
from collections import namedtuple
import re
from .bounded_tensor import BoundedTensor, BoundedParameter
from .utils import logger, unpack_inputs
Node = name... | 6,851 | 38.37931 | 123 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/utils.py | import logging
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import os
import sys
import appdirs
from collections import defaultdict, namedtuple
from collections.abc import Sequence
from functools import reduce
import operator
import warnings
from typing import Tuple
from .patches impor... | 9,387 | 31.597222 | 134 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/perturbations.py | import json
import math
import numpy as np
import torch
from .utils import logger, eyeC
from .patches import Patches, patches_to_matrix
from .linear_bound import LinearBound
class Perturbation:
r"""
Base class for a perturbation specification. Please see examples
at `auto_LiRPA/perturbations.py`.
Exa... | 22,309 | 41.414449 | 155 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/bound_multi_gpu.py | from torch.nn import DataParallel
from .perturbations import *
from .bounded_tensor import BoundedTensor
from itertools import chain
class BoundDataParallel(DataParallel):
# https://github.com/huanzhang12/CROWN-IBP/blob/master/bound_layers.py
# This is a customized DataParallel class for our project
def __... | 6,702 | 51.367188 | 120 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/forward_bound.py | import torch
import warnings
from .bound_ops import *
from .utils import *
from .linear_bound import LinearBound
from .perturbations import PerturbationLpNorm
import sys
sys.setrecursionlimit(1000000)
def forward_general(self, C=None, node=None, concretize=False, offset=0):
if self.bound_opts['dynamic_forward']:
... | 12,671 | 41.099668 | 144 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/cuda_utils.py | import os
import sys
import torch
from torch.utils.cpp_extension import load, BuildExtension, CUDAExtension
from setuptools import setup
class DummyCudaClass:
"""A dummy class with error message when a CUDA function is called."""
def __getattr__(self, attr):
if attr == "double2float":
# Whe... | 4,536 | 35.007937 | 168 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/beta_crown.py | import torch
def beta_bias(self):
batch_size = len(self.relus[-1].split_beta)
batch = int(batch_size/2)
bias = torch.zeros((batch_size, 1), device=self.device)
for m in self.relus:
if not m.used or not m.perturbed:
continue
if m.split_beta_used:
bias[:batch] = b... | 2,493 | 50.958333 | 123 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/jacobian.py | """Handle Jacobian bounds."""
import torch
import numpy as np
from auto_LiRPA.bound_ops import BoundInput, BoundParams, BoundAdd
from auto_LiRPA.bound_ops import GradNorm, JVP
from auto_LiRPA.utils import get_spec_matrix, Flatten
from collections import deque
def augment_gradient_graph(self, dummy_input, norm=None, ... | 9,906 | 39.272358 | 80 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/optimized_bounds.py | import time
import os
import warnings
from collections import OrderedDict
from contextlib import ExitStack
import torch
from torch import optim
from .cuda_utils import double2float
from .utils import logger
def _set_alpha(optimizable_activations, parameters, alphas, lr):
"""
Set best_alphas, alphas and param... | 44,596 | 40.875117 | 87 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/pooling.py | """Pooling operators."""
from collections import OrderedDict
from .base import *
from .activation_base import BoundOptimizableActivation
import numpy as np
from .solver_utils import grb
class BoundMaxPool(BoundOptimizableActivation):
#FIXME clean up needed
def __init__(self, attr, inputs, output_index, optio... | 33,545 | 56.639175 | 215 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/shape.py | """ Shape operators """
from .base import *
from ..patches import Patches, patches_to_matrix
from .linear import BoundLinear
from .gradient_modules import ReshapeGrad
class BoundReshape(Bound):
def __init__(self, attr, inputs, output_index, options):
super().__init__(attr, inputs, output_index, options)
... | 29,225 | 43.825153 | 178 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/base.py | """ Base class and functions for implementing bound operators"""
import warnings
import torch
import torch.nn as nn
from torch import Tensor
import numpy as np
from ..perturbations import *
from ..utils import *
from ..patches import *
from ..linear_bound import LinearBound
torch._C._jit_set_profiling_executor(False)... | 15,662 | 40.218421 | 179 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/softmax.py | """ Softmax """
from .base import *
class BoundSoftmaxImpl(nn.Module):
def __init__(self, axis):
super().__init__()
self.axis = axis
assert self.axis == int(self.axis)
def forward(self, x):
max_x = torch.max(x, dim=self.axis).values
x = torch.exp(x - max_x.unsqueeze(sel... | 1,649 | 34.869565 | 97 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/cut_ops.py | """ Cut operators"""
from .base import *
from .clampmult import multiply_by_A_signs
class CutModule():
# store under BoundedModule
def __init__(self, relu_nodes=[], general_beta=None, x_coeffs=None,
active_cuts=None, cut_bias=None):
# all dict, storing cut parameters for each start no... | 36,993 | 61.808149 | 189 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/nonlinear.py | """Unary nonlinearities other than activation functions."""
import math
import torch
from .activation_base import BoundActivation
from .activations import BoundTanh
from .base import epsilon, LinearBound
class BoundSin(BoundActivation):
# Lookup tables shared by all BoundSin classes.
xl_lower_tb = None
xl... | 31,036 | 46.384733 | 296 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/constant.py | """ Constant operators, including operators that are usually fixed nodes and not perturbed """
from .base import *
class BoundConstant(Bound):
def __init__(self, attr, inputs, output_index, options):
super().__init__(attr, inputs, output_index, options)
self.value = attr['value'].to(self.device)
... | 4,704 | 36.943548 | 124 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/dtype.py | from .base import *
from ..utils import Patches
class BoundCast(Bound):
def __init__(self, attr, inputs, output_index, options):
super().__init__(attr, inputs, output_index, options)
self.to = attr['to']
self.data_types = [
None, torch.float, torch.uint8, torch.int8,
... | 1,706 | 41.675 | 172 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/reduce.py | """ Reduce operators"""
from .base import *
class BoundReduceMax(Bound):
def __init__(self, attr, inputs, output_index, options):
super().__init__(attr, inputs, output_index, options)
self.axis = attr['axes']
# for torch.max, `dim` must be an int
if isinstance(self.axis, list):
... | 5,441 | 38.434783 | 127 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/convolution.py | """ Convolution and padding operators"""
from .base import *
import numpy as np
from .solver_utils import grb
from ..patches import unify_shape, compute_patches_stride_padding, is_shape_used
from .gradient_modules import Conv2dGrad
class BoundConv(Bound):
def __init__(self, attr, inputs, output_index, options):
... | 37,026 | 53.773669 | 215 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/linear.py | """ Linear (possibly with weight perturbation) or Dot product layers """
from torch import Tensor
from .base import *
from .bivariate import BoundMul
from .gradient_modules import LinearGrad
from ..patches import Patches, inplace_unfold
from .solver_utils import grb
class BoundLinear(Bound):
def __init__(self, at... | 35,333 | 47.803867 | 234 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/dropout.py | from .base import *
class BoundDropout(Bound):
def __init__(self, attr, inputs, output_index, options):
super().__init__(attr, inputs, output_index, options)
if 'ratio' in attr:
self.ratio = attr['ratio']
self.dynamic = False
else:
self.ratio = None
... | 2,574 | 36.318841 | 81 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/activations.py | """ Activation operators or other unary nonlinear operators"""
from typing import Optional, Tuple
import torch
from torch import Tensor
from collections import OrderedDict
from .base import *
from .clampmult import multiply_by_A_signs
from .activation_base import BoundActivation, BoundOptimizableActivation
from .gradie... | 57,464 | 52.455814 | 207 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/rnn.py | """RNN."""
from .base import *
class BoundRNN(Bound):
def __init__(self, attr, inputs, output_index, options):
super().__init__(attr, inputs, output_index, options)
self.complex = True
self.output_index = output_index
raise NotImplementedError(
'torch.nn.RNN is not supp... | 2,324 | 37.114754 | 108 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/normalization.py | """ Normalization operators"""
import copy
from .base import *
from .solver_utils import grb
class BoundBatchNormalization(Bound):
def __init__(self, attr, inputs, output_index, options, training):
super().__init__(attr, inputs, output_index, options)
self.eps = attr['epsilon']
self.momentu... | 11,931 | 49.991453 | 170 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/gradient_bounds.py | """ Bound classes for gradient operators """
import torch
import torch.nn.functional as F
import numpy as np
from auto_LiRPA.patches import Patches, inplace_unfold
from .base import Bound, Interval
from .activation_base import BoundActivation
from .gradient_modules import relu_grad
# FIXME reuse the function from aut... | 14,015 | 43.214511 | 88 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/gradient_modules.py | """ Modules for gradients """
import torch
from torch.autograd import Function
from torch.nn import Module
import torch.nn.functional as F
def relu_grad(preact):
return (preact > 0).float()
class SqrOp(Function):
@staticmethod
def symbolic(_, x):
return _.op('grad::Sqr', x)
@staticmethod
... | 4,444 | 29.445205 | 86 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/leaf.py | """ Leaf nodes (indepedent nodes in the auto_LiRPA paper).
Including input, parameter, buffer, etc."""
from itertools import chain
from .base import *
class BoundInput(Bound):
def __init__(self, ori_name, value, perturbation=None, input_index=None):
super().__init__()
self.ori_name = ori_name
... | 7,689 | 43.450867 | 120 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/clampmult.py | """Element multiplication with the A matrix based on its sign."""
import torch
import time
from typing import Optional, Tuple
from torch import Tensor
from ..patches import Patches
torch._C._jit_set_profiling_executor(False)
torch._C._jit_set_profiling_mode(False)
# @torch.jit.script
def _reference_multiply_by_A_si... | 12,291 | 50.430962 | 182 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/logical.py | """ Logical operators"""
from .base import *
class BoundWhere(Bound):
def __init__(self, attr, inputs, output_index, options):
super().__init__(attr, inputs, output_index, options)
def forward(self, condition, x, y):
return torch.where(condition.to(torch.bool), x, y)
def interval_propaga... | 1,384 | 33.625 | 82 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/bivariate.py | """ Bivariate operators"""
import copy
from .base import *
from .nonlinear import BoundSqrt, BoundReciprocal
from .clampmult import multiply_by_A_signs
from ..utils import *
from .solver_utils import grb
from .constant import BoundConstant
from .leaf import BoundParams, BoundBuffers
class BoundMul(Bound):
def __i... | 27,037 | 44.138564 | 218 | py |
auto_LiRPA | auto_LiRPA-master/auto_LiRPA/operators/activation_base.py | """ Activation operators or other unary nonlinear operators"""
import torch
from torch import Tensor
from collections import OrderedDict
from .base import *
from .clampmult import multiply_by_A_signs
torch._C._jit_set_profiling_executor(False)
torch._C._jit_set_profiling_mode(False)
class BoundActivation(Bound):
... | 11,001 | 39.153285 | 198 | py |
QBee | QBee-master/docs/source/conf.py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | 2,068 | 34.067797 | 79 | py |
OPP-DARTS | OPP-DARTS-main/test.py | import os
import sys
import glob
import numpy as np
import torch
import utils
import logging
import argparse
import torch.nn as nn
import genotypes
import torch.utils
import torchvision.datasets as dset
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from model import NetworkCIFAR as Network
... | 3,593 | 33.228571 | 102 | py |
OPP-DARTS | OPP-DARTS-main/architect.py | import torch
import numpy as np
import torch.nn as nn
from torch.autograd import Variable
def _concat(xs):
return torch.cat([x.view(-1) for x in xs])#把x先拉成一行,然后把所有的x摞起来,变成n行
class Architect(object):
def __init__(self, model, args):
self.network_momentum = args.momentum
self.network_weight_decay = args.... | 5,238 | 45.362832 | 194 | py |
OPP-DARTS | OPP-DARTS-main/train_imagenet.py | import os
import sys
import numpy as np
import time
import torch
import utils
import glob
import random
import logging
import argparse
import torch.nn as nn
import genotypes
import torch.utils
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torch.backends.cudnn as cudnn
from torc... | 7,992 | 33.601732 | 106 | py |
OPP-DARTS | OPP-DARTS-main/utils.py | import os
import numpy as np
import torch
import shutil
import torchvision.transforms as transforms
from torch.autograd import Variable
class AvgrageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.avg = 0
self.sum = 0
self.cnt = 0
def update(self, val, n=1):
self.sum... | 3,080 | 24.254098 | 105 | py |
OPP-DARTS | OPP-DARTS-main/model.py | import torch
import torch.nn as nn
from operations import *
from torch.autograd import Variable
from utils import drop_path
class Cell(nn.Module):
def __init__(self, genotype, C_prev_prev, C_prev, C, reduction, reduction_prev):
super(Cell, self).__init__()
print(C_prev_prev, C_prev, C)
if reduction_pr... | 6,640 | 29.888372 | 89 | py |
OPP-DARTS | OPP-DARTS-main/model_search.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from operations import *
from torch.autograd import Variable
import copy
from genotypes import PRIMITIVES
from genotypes import Genotype
from genotypes import PARAMETERD
class MixedOp(nn.Module):
def __init__(self, C, stride, index):
super(Mixed... | 9,722 | 33.601423 | 160 | py |
OPP-DARTS | OPP-DARTS-main/train_search.py | import os
import sys
import time
import glob
import numpy as np
import torch
import utils
import logging
import argparse
import torch.nn as nn
import torch.utils
import torch.nn.functional as F
import torchvision.datasets as dset
import torch.backends.cudnn as cudnn
import copy
from torch.autograd import Variable
from ... | 15,482 | 39.425587 | 115 | py |
OPP-DARTS | OPP-DARTS-main/test_imagenet.py | import os
import sys
import numpy as np
import torch
import utils
import glob
import random
import logging
import argparse
import torch.nn as nn
import genotypes
import torch.utils
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torch.backends.cudnn as cudnn
from torch.autograd i... | 3,785 | 32.504425 | 104 | py |
OPP-DARTS | OPP-DARTS-main/train.py | import os
import sys
import time
import glob
import numpy as np
import torch
import utils
import logging
import argparse
import torch.nn as nn
import genotypes
import torch.utils
import torchvision.datasets as dset
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from model import NetworkCIFAR ... | 6,248 | 35.331395 | 100 | py |
OPP-DARTS | OPP-DARTS-main/operations.py | import torch
import torch.nn as nn
OPS = {
'none' : lambda C, stride, affine: Zero(stride),
'avg_pool_3x3' : lambda C, stride, affine: nn.AvgPool2d(3, stride=stride, padding=1, count_include_pad=False),
'max_pool_3x3' : lambda C, stride, affine: nn.MaxPool2d(3, stride=stride, padding=1),
'skip_connect' : lambd... | 3,717 | 34.075472 | 129 | py |
SauronUNet | SauronUNet-main/train.py | ###########################################
# This script trains great UNet baselines #
# Prior to this, run preprocess.py #
###########################################
import torch, os, time
from lib.utils import parseArguments, Log
from torch.utils.data import DataLoader
import numpy as np
import lib.callback as cal... | 3,713 | 36.14 | 83 | py |
SauronUNet | SauronUNet-main/torchio_lib/resample.py | from pathlib import Path
from numbers import Number
from typing import Union, Tuple, Optional
from collections.abc import Iterable
import torch
import numpy as np
import SimpleITK as sitk
from ....data.io import sitk_to_nib, get_sitk_metadata_from_ras_affine
from ....data.subject import Subject
from ....typing import... | 12,521 | 39.263666 | 149 | py |
SauronUNet | SauronUNet-main/torchio_lib/crop_or_pad.py | import warnings
from typing import Union, Tuple, Optional
import numpy as np
from .pad import Pad
from .crop import Crop
from .bounds_transform import BoundsTransform
from ...transform import TypeTripletInt, TypeSixBounds
from ....data.subject import Subject
class CropOrPad(BoundsTransform):
"""Crop and/or pad ... | 9,501 | 37.008 | 114 | py |
SauronUNet | SauronUNet-main/torchio_lib/queue.py | import random, time
import numpy as np
import warnings
from itertools import islice
from typing import List, Iterator, Optional
import humanize
from tqdm import trange
from torch.utils.data import Dataset, DataLoader
from .subject import Subject
from .sampler import PatchSampler
from .dataset import SubjectsDataset
... | 15,620 | 41.79726 | 161 | py |
SauronUNet | SauronUNet-main/lib/loss.py | # This file contains all the loss functions that I've tested, including the
# proposed "Rectified normalized Region-wise map".
#
# To simplify and for clarity reasons, I've only commented those functions
# that appear in the paper. In any case, there is a lot of repetion because
# the class "BaseData" computes the "wei... | 3,851 | 28.40458 | 79 | py |
SauronUNet | SauronUNet-main/lib/utils.py | import argparse, inspect, os, sys
from lib.data.BaseDataset import BaseDataset
from typing import Type
from torch.nn.parameter import Parameter as TorchParameter
import torch, json
from lib.paths import data_path
import numpy as np
import types, random, time, pickle
from datetime import datetime
from torch import Tenso... | 27,227 | 37.621277 | 159 | py |
SauronUNet | SauronUNet-main/lib/callback.py | from typing import Type, List, Dict
from lib.models.BaseModel import BaseModel, unwrap_data
import torch, os
import numpy as np
from torchio.data.dataset import SubjectsDataset
from torchio.data.subject import Subject
from torch.utils.data import DataLoader
from torch.optim import Optimizer
from torch import Tensor
imp... | 32,517 | 46.680352 | 178 | py |
SauronUNet | SauronUNet-main/lib/distance.py | import torch
from torch import Tensor
def Euclidean_norm(fm: Tensor, compress) -> Tensor:
"""
Computes the Euclidean distance w.r.t. the first channel, and normalizes
the distances.
"""
fm1 = fm[:, 0:1]
fm2 = fm[:, 1:]
fm1_max_vals = torch.amax(fm1, axis=[2,3], keepdim=True)
fm1_min_va... | 2,521 | 31.753247 | 76 | py |
SauronUNet | SauronUNet-main/lib/metric.py | import numpy as np
from skimage import measure
from scipy import ndimage
from medpy import metric
import torch
from typing import List, Callable, Dict
from lib.metric_utils import compute_surface_distances, compute_surface_dice_at_tolerance
from lib.utils import softmax2onehot
def surface_dice_np(pred, true, voxres):
... | 12,117 | 32.943978 | 152 | py |
SauronUNet | SauronUNet-main/lib/models/Sauron.py | import torch
from lib.models.BaseModel import BaseModel
from torch.nn.functional import interpolate
from torch.nn import Conv3d, Conv2d, InstanceNorm2d, InstanceNorm3d
from torch.nn import LeakyReLU, AvgPool2d, AvgPool3d
from torch.nn import ConvTranspose2d, ConvTranspose3d
import numpy as np
import os
from lib.models.... | 7,458 | 36.862944 | 97 | py |
SauronUNet | SauronUNet-main/lib/models/nnUNet.py | import torch
from lib.models.BaseModel import BaseModel
from torch.nn.functional import interpolate
from torch.nn import Conv3d, Conv2d, InstanceNorm2d, InstanceNorm3d
from torch.nn import LeakyReLU, AvgPool2d, AvgPool3d
from torch.nn import ConvTranspose2d, ConvTranspose3d
import numpy as np
import os
# Details from ... | 10,304 | 39.097276 | 124 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.