├── .gitignore ├── .DS_Store ├── dfme ├── .DS_Store ├── network │ ├── __init__.py │ ├── lenet.py │ ├── wrn.py │ ├── resnet_8x.py │ └── gan.py ├── checkpoint │ └── .DS_Store ├── cifar10_models │ ├── __init__.py │ ├── resnet_orig.py │ ├── mobilenetv2.py │ ├── kt_wrn.py │ ├── vgg.py │ ├── densenet.py │ ├── googlenet.py │ ├── resnet.py │ └── inception.py ├── my_utils.py ├── dataloader.py ├── approximate_gradients.py └── train.py ├── requirements.txt ├── run_cifar_dfme.sh ├── run_svhn_dfme.sh ├── surrogate_benchmark ├── params.py ├── dataloader.py ├── wrn.py ├── resnet_8x.py └── train.py ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cake-lab/datafree-model-extraction/HEAD/.DS_Store -------------------------------------------------------------------------------- /dfme/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cake-lab/datafree-model-extraction/HEAD/dfme/.DS_Store -------------------------------------------------------------------------------- /dfme/network/__init__.py: -------------------------------------------------------------------------------- 1 | from . import gan 2 | from . import lenet 3 | from . import resnet_8x 4 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch>=1.2 2 | torchvision 3 | numpy 4 | pillow 5 | scikit-learn 6 | matplotlib 7 | tqdm 8 | -------------------------------------------------------------------------------- /dfme/checkpoint/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cake-lab/datafree-model-extraction/HEAD/dfme/checkpoint/.DS_Store -------------------------------------------------------------------------------- /dfme/cifar10_models/__init__.py: -------------------------------------------------------------------------------- 1 | from .mobilenetv2 import * 2 | from .resnet import * 3 | from .vgg import * 4 | from .densenet import * 5 | from .resnet_orig import * 6 | from .googlenet import * 7 | from .inception import * 8 | from.kt_wrn import * -------------------------------------------------------------------------------- /run_cifar_dfme.sh: -------------------------------------------------------------------------------- 1 | cd dfme; 2 | 3 | python3 train.py --dataset cifar10 --ckpt checkpoint/teacher/cifar10-resnet34_8x.pt --device 0 --grad_m 1 --query_budget 20 --log_dir save_results/cifar10 --lr_G 1e-4 --student_model resnet18_8x --loss l1; 4 | -------------------------------------------------------------------------------- /run_svhn_dfme.sh: -------------------------------------------------------------------------------- 1 | cd dfme; 2 | 3 | python3 train.py --dataset svhn --ckpt checkpoint/teacher/svhn-resnet34_8x.pt --device 0 --grad_m 1 --query_budget 2 --log_dir save_results/svhn --lr_G 5e-5 --student_model resnet18_8x --loss l1 --steps 0.5 0.8; -------------------------------------------------------------------------------- /surrogate_benchmark/params.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | from distutils import util 3 | import yaml 4 | import sys 5 | 6 | def parse_args(): 7 | parser = argparse.ArgumentParser(description='Adversarial Training') 8 | ## Basics 9 | parser.add_argument("--config_file", help="Configuration file containing parameters", type=str) 10 | parser.add_argument("--target", help="svhn/cifar10", type=str, default = "cifar10", choices = ["cifar10", "svhn"]) 11 | parser.add_argument("--surrogate", help="for query", type=str, default = "cifar10") 12 | parser.add_argument("--model_type", help="cnn/wrn-40-2/wrn-28-10/preactresnet", 13 | type=str, default = "wrn-28-10", choices = ["cnn","wrn-40-2","wrn-28-10","preactresnet"]) 14 | parser.add_argument("--gpu_id", help="Id of GPU to be used", type=int, default = 0) 15 | parser.add_argument("--batch_size", help = "Batch Size for Train Set (Default = 100)", type = int, default = 100) 16 | parser.add_argument("--model_id", help = "For Saving", type = str, default = '0') 17 | parser.add_argument("--seed", help = "Seed", type = int, default = 0) 18 | parser.add_argument("--normalize", help = "Normalize training data inside the model", type = int, default = 1, choices = [0,1]) 19 | parser.add_argument("--device", help = "To be assigned later", type = int, default = 0) 20 | parser.add_argument("--epochs", help = "Number of Epochs", type = int, default = 50) 21 | 22 | #LR 23 | parser.add_argument("--lr_mode", help = "Step wise or Cyclic", type = int, default = 1) 24 | parser.add_argument("--opt_type", help = "Optimizer", type = str, default = "SGD") 25 | parser.add_argument("--lr_max", help = "Max LR", type = float, default = 0.1) 26 | parser.add_argument("--lr_min", help = "Min LR", type = float, default = 0.) 27 | 28 | parser.add_argument("--temp", help = "Temperature for KL loss", type = float, default = 1.0) 29 | 30 | #TEST 31 | parser.add_argument("--path", help = "Path for test model load", type = str, default = None) 32 | 33 | return parser 34 | 35 | def add_config(args): 36 | data = yaml.load(open(args.config_file,'r')) 37 | args_dict = args.__dict__ 38 | for key, value in data.items(): 39 | if('--'+key in sys.argv and args_dict[key] != None): ## Giving higher priority to arguments passed in cli 40 | continue 41 | if isinstance(value, list): 42 | args_dict[key] = [] 43 | args_dict[key].extend(value) 44 | else: 45 | args_dict[key] = value 46 | return args 47 | 48 | 49 | -------------------------------------------------------------------------------- /dfme/network/lenet.py: -------------------------------------------------------------------------------- 1 | # This part is borrowed from https://github.com/huawei-noah/Data-Efficient-Model-Compression 2 | 3 | import torch.nn as nn 4 | 5 | 6 | class LeNet5(nn.Module): 7 | 8 | def __init__(self): 9 | super(LeNet5, self).__init__() 10 | 11 | self.conv1 = nn.Conv2d(1, 6, kernel_size=(5, 5)) 12 | self.relu1 = nn.ReLU() 13 | self.maxpool1 = nn.MaxPool2d(kernel_size=(2, 2), stride=2) 14 | self.conv2 = nn.Conv2d(6, 16, kernel_size=(5, 5)) 15 | self.relu2 = nn.ReLU() 16 | self.maxpool2 = nn.MaxPool2d(kernel_size=(2, 2), stride=2) 17 | self.conv3 = nn.Conv2d(16, 120, kernel_size=(5, 5)) 18 | self.relu3 = nn.ReLU() 19 | self.fc1 = nn.Linear(120, 84) 20 | self.relu4 = nn.ReLU() 21 | self.fc2 = nn.Linear(84, 10) 22 | 23 | def forward(self, img, out_feature=False): 24 | output = self.conv1(img) 25 | output = self.relu1(output) 26 | output = self.maxpool1(output) 27 | output = self.conv2(output) 28 | output = self.relu2(output) 29 | output = self.maxpool2(output) 30 | output = self.conv3(output) 31 | output = self.relu3(output) 32 | feature = output.view(-1, 120) 33 | output = self.fc1(feature) 34 | output = self.relu4(output) 35 | output = self.fc2(output) 36 | if out_feature == False: 37 | return output 38 | else: 39 | return output,feature 40 | 41 | 42 | class LeNet5Half(nn.Module): 43 | 44 | def __init__(self): 45 | super(LeNet5Half, self).__init__() 46 | 47 | self.conv1 = nn.Conv2d(1, 3, kernel_size=(5, 5)) 48 | self.relu1 = nn.ReLU() 49 | self.maxpool1 = nn.MaxPool2d(kernel_size=(2, 2), stride=2) 50 | self.conv2 = nn.Conv2d(3, 8, kernel_size=(5, 5)) 51 | self.relu2 = nn.ReLU() 52 | self.maxpool2 = nn.MaxPool2d(kernel_size=(2, 2), stride=2) 53 | self.conv3 = nn.Conv2d(8, 60, kernel_size=(5, 5)) 54 | self.relu3 = nn.ReLU() 55 | self.fc1 = nn.Linear(60, 42) 56 | self.relu4 = nn.ReLU() 57 | self.fc2 = nn.Linear(42, 10) 58 | 59 | def forward(self, img, out_feature=False): 60 | output = self.conv1(img) 61 | output = self.relu1(output) 62 | output = self.maxpool1(output) 63 | output = self.conv2(output) 64 | output = self.relu2(output) 65 | output = self.maxpool2(output) 66 | output = self.conv3(output) 67 | output = self.relu3(output) 68 | feature = output.view(-1, 60) 69 | output = self.fc1(feature) 70 | output = self.relu4(output) 71 | output = self.fc2(output) 72 | if out_feature == False: 73 | return output 74 | else: 75 | return output,feature -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data-Free Model Extraction 2 | 3 | This repository complements the [Data-Free Model Extraction paper](https://arxiv.org/abs/2011.14779), that will be published at the 2021 IEEE/CVF Conference on Computer Vision and Pattern Recognition. 4 | 5 | This project was conducted in collaboration between the [Cake Lab](https://cake.wpi.edu/) at Worcester Polytechnic Institute, and the [University of Toronto](https://www.utoronto.ca/) and the [Vector Institute](https://vectorinstitute.ai/). 6 | 7 | 8 | ## Updates 9 | - Jan 14, 2022: Updated the default learning rate parameter for the generator to match the paper's experimental setup. 10 | 11 | ## Citation 12 | ``` 13 | @InProceedings{Truong_2021_CVPR, 14 | author = {Truong, Jean-Baptiste and Maini, Pratyush and Walls, Robert J. and Papernot, Nicolas}, 15 | title = {Data-Free Model Extraction}, 16 | booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)}, 17 | month = {June}, 18 | year = {2021} 19 | } 20 | ``` 21 | 22 | ## Dependencies 23 | The code requires dependencies that can be installed using the `pip` environment file provided: 24 | ``` 25 | pip install -r requirements.txt 26 | ``` 27 | 28 | ## Replicating DFME Results 29 | 30 | ### Load Victim Model Weights 31 | First, download the pretrained victim model weights from [this dropbox](https://www.dropbox.com/sh/lt6w0nq3msp4do0/AADmJk2k3LQqFqWt9916W-nra?dl=0). The two file names are `cifar10-resnet34_8x.pt` and `svhn-resnet34_8x.pt`. The CIFAR10 weights were found on the [Data Free Adversarial Distillation](https://github.com/VainF/Data-Free-Adversarial-Distillation) dropbox, while we trained the SVHN model ourselves. 32 | 33 | Then, store the pre-trained model weights at the following location 34 | 35 | `dfme/checkpoint/teacher/{victim_dataset}-resnet34_8x.pt` 36 | 37 | 38 | ### Perform Model Extraction 39 | ``` 40 | bash run_cifar_dfme.sh 41 | bash run_svhn_dfme.sh 42 | ``` 43 | Logs and saved models can be found at `save_results/{victim_dataset}/` 44 | 45 | 46 | ## Surrogate Benchmarking 47 | Standard model extraction attacks can be performed using the code in the folder `surrogate_benchmark`. 48 | 49 | ``` 50 | cd surrogate_benchmark 51 | python train.py --surrogate {surrogate_dataset} --target {target_dataset} --temp {temperature_value} --lr_mode 1 --epochs 50 52 | ``` 53 | Typically, using `temperature_value` in {1,3,5} provides good extraction results. The number of epochs may be reduced to 30 in case the `target` dataset is `svhn`. 54 | 55 | 56 | 57 | ## Attribution 58 | 59 | This repository was built on code from the paper [Data Free Adversarial Distillation](https://github.com/VainF/Data-Free-Adversarial-Distillation). The weights and model architectures for Resnet34-8x and Resnet18_8x were also found on the repository released with the Data Free Adversarial Distillation paper. 60 | -------------------------------------------------------------------------------- /dfme/my_utils.py: -------------------------------------------------------------------------------- 1 | from cifar10_models import * 2 | from approximate_gradients import * 3 | import network 4 | 5 | def get_classifier(classifier, pretrained=True, num_classes=10): 6 | if classifier == "wrn-28-10": 7 | net = wrn( 8 | num_classes=num_classes, 9 | depth=28, 10 | widen_factor=10, 11 | dropRate=0.3 12 | ) 13 | if pretrained: 14 | state_dict = torch.load("cifar100_models/state_dicts/model_best.pt", map_location=device)["state_dict"] 15 | # create new OrderedDict that does not contain `module.` 16 | from collections import OrderedDict 17 | new_state_dict = OrderedDict() 18 | for k, v in state_dict.items(): 19 | name = k[7:] # remove `module.` 20 | new_state_dict[name] = v 21 | net.load_state_dict(new_state_dict) 22 | 23 | return net 24 | elif 'wrn' in classifier and 'kt' not in classifier: 25 | depth = int(classifier.split("-")[1]) 26 | width = int(classifier.split("-")[2]) 27 | 28 | net = wrn( 29 | num_classes=num_classes, 30 | depth=depth, 31 | widen_factor=width 32 | ) 33 | if pretrained: 34 | raise ValueError("Cannot be pretrained") 35 | return net 36 | elif classifier == "kt-wrn-40-2": 37 | net = WideResNetKT(depth=40, num_classes=num_classes, widen_factor=2, dropRate=0.0) 38 | if pretrained: 39 | state_dict = torch.load("cifar10_models/state_dicts/kt_wrn.pt", map_location=device)["state_dict"] 40 | net.load_state_dict(state_dict) 41 | return net 42 | elif classifier == "resnet34_8x": 43 | if pretrained: 44 | raise ValueError("Cannot load pretrained resnet34_8x from here") 45 | return network.resnet_8x.ResNet34_8x(num_classes=num_classes) 46 | elif classifier == "resnet18_8x": 47 | if pretrained: 48 | raise ValueError("Cannot load pretrained resnet18_8x from here") 49 | return network.resnet_8x.ResNet18_8x(num_classes=num_classes) 50 | 51 | else: 52 | raise NameError('Please enter a valid classifier') 53 | 54 | 55 | def measure_true_grad_norm(args, x): 56 | # Compute true gradient of loss wrt x 57 | true_grad, _ = compute_gradient(args, args.teacher, args.student, x, pre_x=True, device=args.device) 58 | true_grad = true_grad.view(-1, 3072) 59 | 60 | # Compute norm of gradients 61 | norm_grad = true_grad.norm(2, dim=1).mean().cpu() 62 | 63 | return norm_grad 64 | 65 | classifiers = [ 66 | "resnet34_8x", # Default DFAD 67 | "vgg11", 68 | "vgg13", 69 | "vgg16", 70 | "vgg19", 71 | "vgg11_bn", 72 | "vgg13_bn", 73 | "vgg16_bn", 74 | "vgg19_bn", 75 | "resnet18", 76 | "resnet34", 77 | "resnet50", 78 | "densenet121", 79 | "densenet161", 80 | "densenet169", 81 | "mobilenet_v2", 82 | "googlenet", 83 | "inception_v3", 84 | "wrn-28-10", 85 | "resnet18_8x", 86 | "kt-wrn-40-2", 87 | ] -------------------------------------------------------------------------------- /dfme/cifar10_models/resnet_orig.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import os 5 | 6 | #Credit to https://github.com/akamaster/pytorch_resnet_cifar10 7 | 8 | __all__ = ['resnet_orig'] 9 | 10 | class LambdaLayer(nn.Module): 11 | def __init__(self, lambd): 12 | super(LambdaLayer, self).__init__() 13 | self.lambd = lambd 14 | 15 | def forward(self, x): 16 | return self.lambd(x) 17 | 18 | class BasicBlock(nn.Module): 19 | expansion = 1 20 | 21 | def __init__(self, in_planes, planes, stride=1, option='A'): 22 | super(BasicBlock, self).__init__() 23 | self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) 24 | self.bn1 = nn.BatchNorm2d(planes) 25 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False) 26 | self.bn2 = nn.BatchNorm2d(planes) 27 | 28 | self.shortcut = nn.Sequential() 29 | if stride != 1 or in_planes != planes: 30 | if option == 'A': 31 | """ 32 | For CIFAR10 ResNet paper uses option A. 33 | """ 34 | self.shortcut = LambdaLayer(lambda x: 35 | F.pad(x[:, :, ::2, ::2], (0, 0, 0, 0, planes//4, planes//4), "constant", 0)) 36 | elif option == 'B': 37 | self.shortcut = nn.Sequential( 38 | nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False), 39 | nn.BatchNorm2d(self.expansion * planes) 40 | ) 41 | 42 | def forward(self, x): 43 | out = F.relu(self.bn1(self.conv1(x))) 44 | out = self.bn2(self.conv2(out)) 45 | out += self.shortcut(x) 46 | out = F.relu(out) 47 | return out 48 | 49 | class ResNet(nn.Module): 50 | def __init__(self, block, num_blocks, num_classes=10): 51 | super(ResNet, self).__init__() 52 | self.in_planes = 16 53 | 54 | self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1, bias=False) 55 | self.bn1 = nn.BatchNorm2d(16) 56 | self.layer1 = self._make_layer(block, 16, num_blocks[0], stride=1) 57 | self.layer2 = self._make_layer(block, 32, num_blocks[1], stride=2) 58 | self.layer3 = self._make_layer(block, 64, num_blocks[2], stride=2) 59 | self.linear = nn.Linear(64, num_classes) 60 | 61 | def _make_layer(self, block, planes, num_blocks, stride): 62 | strides = [stride] + [1]*(num_blocks-1) 63 | layers = [] 64 | for stride in strides: 65 | layers.append(block(self.in_planes, planes, stride)) 66 | self.in_planes = planes * block.expansion 67 | 68 | return nn.Sequential(*layers) 69 | 70 | def forward(self, x): 71 | out = F.relu(self.bn1(self.conv1(x))) 72 | out = self.layer1(out) 73 | out = self.layer2(out) 74 | out = self.layer3(out) 75 | out = F.avg_pool2d(out, out.size()[3]) 76 | out = out.view(out.size(0), -1) 77 | out = self.linear(out) 78 | return out 79 | 80 | def resnet_orig(pretrained=True, device='cpu'): 81 | net = ResNet(BasicBlock, [3, 3, 3]) 82 | if pretrained: 83 | script_dir = os.path.dirname(__file__) 84 | state_dict = torch.load(script_dir + '/state_dicts/resnet_orig.pt', map_location=device) 85 | net.load_state_dict(state_dict) 86 | return net -------------------------------------------------------------------------------- /dfme/dataloader.py: -------------------------------------------------------------------------------- 1 | from torchvision import datasets, transforms 2 | import torch 3 | 4 | 5 | def get_dataloader(args): 6 | if args.dataset.lower()=='mnist': 7 | train_loader = torch.utils.data.DataLoader( 8 | datasets.MNIST(args.data_root, train=True, download=True, 9 | transform=transforms.Compose([ 10 | transforms.Resize((32, 32)), 11 | transforms.ToTensor(), 12 | transforms.Normalize((0.1307,), (0.3081,)) 13 | ])), 14 | batch_size=args.batch_size, shuffle=True, num_workers=2) 15 | test_loader = torch.utils.data.DataLoader( 16 | datasets.MNIST(args.data_root, train=False, download=True, 17 | transform=transforms.Compose([ 18 | transforms.Resize((32, 32)), 19 | transforms.ToTensor(), 20 | transforms.Normalize((0.1307,), (0.3081,)) 21 | ])), 22 | batch_size=args.batch_size, shuffle=True, num_workers=2) 23 | 24 | 25 | elif args.dataset.lower()=='svhn': 26 | print("Loading SVHN data") 27 | train_loader = torch.utils.data.DataLoader( 28 | datasets.SVHN(args.data_root, split='train', download=True, 29 | transform=transforms.Compose([ 30 | transforms.Resize((32, 32)), 31 | transforms.ToTensor(), 32 | transforms.Normalize((0.43768206, 0.44376972, 0.47280434), (0.19803014, 0.20101564, 0.19703615)), 33 | # transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5)), 34 | ])), 35 | batch_size=args.batch_size, shuffle=True, num_workers=2) 36 | test_loader = torch.utils.data.DataLoader( 37 | datasets.SVHN(args.data_root, split='test', download=True, 38 | transform=transforms.Compose([ 39 | transforms.ToTensor(), 40 | transforms.Normalize((0.43768206, 0.44376972, 0.47280434), (0.19803014, 0.20101564, 0.19703615)), 41 | # transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5)), 42 | ])), 43 | batch_size=args.batch_size, shuffle=True, num_workers=2) 44 | elif args.dataset.lower()=='cifar10': 45 | train_loader = torch.utils.data.DataLoader( 46 | datasets.CIFAR10(args.data_root, train=True, download=True, 47 | transform=transforms.Compose([ 48 | transforms.RandomCrop(32, padding=4), 49 | transforms.RandomHorizontalFlip(), 50 | transforms.ToTensor(), 51 | transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), 52 | ])), 53 | batch_size=args.batch_size, shuffle=True, num_workers=2) 54 | test_loader = torch.utils.data.DataLoader( 55 | datasets.CIFAR10(args.data_root, train=False, download=True, 56 | transform=transforms.Compose([ 57 | transforms.ToTensor(), 58 | transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), 59 | ])), 60 | batch_size=args.batch_size, shuffle=True, num_workers=2) 61 | 62 | return train_loader, test_loader -------------------------------------------------------------------------------- /surrogate_benchmark/dataloader.py: -------------------------------------------------------------------------------- 1 | from torchvision import datasets, transforms 2 | from torch.utils.data import DataLoader, Dataset 3 | import PIL 4 | import ipdb 5 | import torch 6 | 7 | class RandDataset(Dataset): 8 | #Used for sampling Random queries for model Extraction Attacks on SVHN 9 | def __init__(self, batch_size, max_examples): 10 | self.batch_size = batch_size 11 | self.channels = 3 12 | self.pix = 32 13 | self.len = int(max_examples/batch_size) 14 | 15 | def __len__(self): 16 | return self.len 17 | 18 | def __getitem__(self, idx): 19 | z = torch.randn((self.batch_size, 3, 32, 32)) 20 | labels = torch.randn((self.batch_size,)) 21 | sample = [z,labels] 22 | 23 | return sample 24 | 25 | 26 | 27 | def data_loader(dataset, batch_size, max_examples): 28 | if dataset == "random": 29 | train_loader = RandDataset(batch_size = batch_size, max_examples = max_examples) 30 | return train_loader, train_loader 31 | 32 | func = {"svhn":datasets.SVHN, "svhn_skew":datasets.SVHN, "cifar10":datasets.CIFAR10, "cifar100":datasets.CIFAR100, "mnist":datasets.MNIST, "Imagenet":datasets.ImageNet,"MNIST-M":None} 33 | norm_mean = {"svhn":(0.438, 0.444, 0.473), "svhn_skew":(0.438, 0.444, 0.473), "cifar10":(0.4914, 0.4822, 0.4465), "cifar100":(0.4914, 0.4822, 0.4465), "mnist":(0.1307,), "Imagenet":(0.485, 0.456, 0.406),"MNIST-M":None} 34 | norm_std = {"svhn":(0.198, 0.201, 0.197), "svhn_skew":(0.198, 0.201, 0.197), "cifar10":(0.2023, 0.1994, 0.2010), "cifar100":(0.2023, 0.1994, 0.2010), "mnist": (0.3081,), "Imagenet":(0.229, 0.224, 0.225),"MNIST-M":None} 35 | 36 | 37 | tr_normalize = transforms.Normalize(norm_mean[dataset], norm_std[dataset]) 38 | transform_train = transforms.Compose([ 39 | transforms.Resize((32, 32), interpolation=PIL.Image.BILINEAR), 40 | transforms.RandomCrop(32, padding=4), 41 | transforms.RandomHorizontalFlip(), 42 | transforms.ToTensor(), tr_normalize, 43 | transforms.Lambda(lambda x: x.float())]) 44 | transform_test = transforms.Compose([transforms.ToTensor(), tr_normalize, transforms.Lambda(lambda x: x.float())]) 45 | 46 | data_source = func[dataset] 47 | try: 48 | d_train = data_source("../data", train=True, download=True, transform=transform_train) 49 | d_test = data_source("../data", train=False, download=True, transform=transform_test) 50 | except: 51 | d_train = data_source("../data", split='train' if dataset != "svhn_skew" else 'extra', download=True, transform=transform_train) 52 | d_test = data_source("../data", split='test', download=True, transform=transform_test) 53 | 54 | if dataset == 'svhn_skew': 55 | d_train.data = d_train.data[d_train.labels < 5] 56 | d_train.labels = d_train.labels[d_train.labels < 5] 57 | if dataset in ['svhn', 'svhn_skew']: 58 | ## Cap maximum size to 50_000 unique samples 59 | d_train.data = d_train.data[:50000] 60 | d_train.labels = d_train.labels[:50000] 61 | if dataset in ['mnist']: 62 | d_train.data = d_train.data[:50000] 63 | d_train.targets = d_train.targets[:50000] 64 | 65 | train_loader = DataLoader(d_train, batch_size = batch_size, shuffle=True) 66 | test_loader = DataLoader(d_test, batch_size = batch_size, shuffle=False) 67 | 68 | return train_loader, test_loader 69 | 70 | -------------------------------------------------------------------------------- /dfme/network/wrn.py: -------------------------------------------------------------------------------- 1 | import math 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | 6 | class BasicBlock(nn.Module): 7 | def __init__(self, in_planes, out_planes, stride, dropRate=0.0): 8 | super(BasicBlock, self).__init__() 9 | self.bn1 = nn.BatchNorm2d(in_planes) 10 | self.relu1 = nn.ReLU(inplace=True) 11 | self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, 12 | padding=1, bias=False) 13 | self.bn2 = nn.BatchNorm2d(out_planes) 14 | self.relu2 = nn.ReLU(inplace=True) 15 | self.conv2 = nn.Conv2d(out_planes, out_planes, kernel_size=3, stride=1, 16 | padding=1, bias=False) 17 | self.droprate = dropRate 18 | self.equalInOut = (in_planes == out_planes) 19 | self.convShortcut = (not self.equalInOut) and nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, 20 | padding=0, bias=False) or None 21 | def forward(self, x): 22 | if not self.equalInOut: 23 | x = self.relu1(self.bn1(x)) 24 | else: 25 | out = self.relu1(self.bn1(x)) 26 | out = self.relu2(self.bn2(self.conv1(out if self.equalInOut else x))) 27 | if self.droprate > 0: 28 | out = F.dropout(out, p=self.droprate, training=self.training) 29 | out = self.conv2(out) 30 | return torch.add(x if self.equalInOut else self.convShortcut(x), out) 31 | 32 | class NetworkBlock(nn.Module): 33 | def __init__(self, nb_layers, in_planes, out_planes, block, stride, dropRate=0.0): 34 | super(NetworkBlock, self).__init__() 35 | self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, dropRate) 36 | def _make_layer(self, block, in_planes, out_planes, nb_layers, stride, dropRate): 37 | layers = [] 38 | for i in range(nb_layers): 39 | layers.append(block(i == 0 and in_planes or out_planes, out_planes, i == 0 and stride or 1, dropRate)) 40 | return nn.Sequential(*layers) 41 | def forward(self, x): 42 | return self.layer(x) 43 | 44 | class WideResNet(nn.Module): 45 | def __init__(self, depth, num_classes, widen_factor=1, dropRate=0.0): 46 | super(WideResNet, self).__init__() 47 | nChannels = [16, 16*widen_factor, 32*widen_factor, 64*widen_factor] 48 | assert (depth - 4) % 6 == 0, 'depth should be 6n+4' 49 | n = (depth - 4) // 6 50 | block = BasicBlock 51 | # 1st conv before any network block 52 | self.conv1 = nn.Conv2d(3, nChannels[0], kernel_size=3, stride=1, 53 | padding=1, bias=False) 54 | # 1st block 55 | self.block1 = NetworkBlock(n, nChannels[0], nChannels[1], block, 1, dropRate) 56 | # 2nd block 57 | self.block2 = NetworkBlock(n, nChannels[1], nChannels[2], block, 2, dropRate) 58 | # 3rd block 59 | self.block3 = NetworkBlock(n, nChannels[2], nChannels[3], block, 2, dropRate) 60 | # global average pooling and classifier 61 | self.bn1 = nn.BatchNorm2d(nChannels[3]) 62 | self.relu = nn.ReLU(inplace=True) 63 | self.fc = nn.Linear(nChannels[3], num_classes) 64 | self.nChannels = nChannels[3] 65 | 66 | for m in self.modules(): 67 | if isinstance(m, nn.Conv2d): 68 | n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels 69 | m.weight.data.normal_(0, math.sqrt(2. / n)) 70 | elif isinstance(m, nn.BatchNorm2d): 71 | m.weight.data.fill_(1) 72 | m.bias.data.zero_() 73 | elif isinstance(m, nn.Linear): 74 | m.bias.data.zero_() 75 | 76 | def forward(self, x): 77 | out = self.conv1(x) 78 | out = self.block1(out) 79 | out = self.block2(out) 80 | out = self.block3(out) 81 | out = self.relu(self.bn1(out)) 82 | out = F.avg_pool2d(out, 8) 83 | out = out.view(-1, self.nChannels) 84 | return self.fc(out) 85 | 86 | -------------------------------------------------------------------------------- /surrogate_benchmark/wrn.py: -------------------------------------------------------------------------------- 1 | import math 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | 6 | __all__ = ['wrn'] 7 | 8 | class BasicBlock(nn.Module): 9 | def __init__(self, in_planes, out_planes, stride, dropRate=0.0): 10 | super(BasicBlock, self).__init__() 11 | self.bn1 = nn.BatchNorm2d(in_planes) 12 | self.relu1 = nn.ReLU(inplace=True) 13 | self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, 14 | padding=1, bias=False) 15 | self.bn2 = nn.BatchNorm2d(out_planes) 16 | self.relu2 = nn.ReLU(inplace=True) 17 | self.conv2 = nn.Conv2d(out_planes, out_planes, kernel_size=3, stride=1, 18 | padding=1, bias=False) 19 | self.droprate = dropRate 20 | self.equalInOut = (in_planes == out_planes) 21 | self.convShortcut = (not self.equalInOut) and nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, 22 | padding=0, bias=False) or None 23 | def forward(self, x): 24 | if not self.equalInOut: 25 | x = self.relu1(self.bn1(x)) 26 | else: 27 | out = self.relu1(self.bn1(x)) 28 | out = self.relu2(self.bn2(self.conv1(out if self.equalInOut else x))) 29 | if self.droprate > 0: 30 | out = F.dropout(out, p=self.droprate, training=self.training) 31 | out = self.conv2(out) 32 | return torch.add(x if self.equalInOut else self.convShortcut(x), out) 33 | 34 | class NetworkBlock(nn.Module): 35 | def __init__(self, nb_layers, in_planes, out_planes, block, stride, dropRate=0.0): 36 | super(NetworkBlock, self).__init__() 37 | self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, dropRate) 38 | def _make_layer(self, block, in_planes, out_planes, nb_layers, stride, dropRate): 39 | layers = [] 40 | for i in range(nb_layers): 41 | layers.append(block(i == 0 and in_planes or out_planes, out_planes, i == 0 and stride or 1, dropRate)) 42 | return nn.Sequential(*layers) 43 | def forward(self, x): 44 | return self.layer(x) 45 | 46 | class WideResNet(nn.Module): 47 | def __init__(self, depth, num_classes, widen_factor=1, dropRate=0.0): 48 | super(WideResNet, self).__init__() 49 | nChannels = [16, 16*widen_factor, 32*widen_factor, 64*widen_factor] 50 | assert (depth - 4) % 6 == 0, 'depth should be 6n+4' 51 | n = (depth - 4) // 6 52 | block = BasicBlock 53 | # 1st conv before any network block 54 | self.conv1 = nn.Conv2d(3, nChannels[0], kernel_size=3, stride=1, 55 | padding=1, bias=False) 56 | # 1st block 57 | self.block1 = NetworkBlock(n, nChannels[0], nChannels[1], block, 1, dropRate) 58 | # 2nd block 59 | self.block2 = NetworkBlock(n, nChannels[1], nChannels[2], block, 2, dropRate) 60 | # 3rd block 61 | self.block3 = NetworkBlock(n, nChannels[2], nChannels[3], block, 2, dropRate) 62 | # global average pooling and classifier 63 | self.bn1 = nn.BatchNorm2d(nChannels[3]) 64 | self.relu = nn.ReLU(inplace=True) 65 | self.fc = nn.Linear(nChannels[3], num_classes) 66 | self.nChannels = nChannels[3] 67 | 68 | for m in self.modules(): 69 | if isinstance(m, nn.Conv2d): 70 | n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels 71 | m.weight.data.normal_(0, math.sqrt(2. / n)) 72 | elif isinstance(m, nn.BatchNorm2d): 73 | m.weight.data.fill_(1) 74 | m.bias.data.zero_() 75 | elif isinstance(m, nn.Linear): 76 | m.bias.data.zero_() 77 | 78 | def forward(self, x): 79 | out = self.conv1(x) 80 | out = self.block1(out) 81 | out = self.block2(out) 82 | out = self.block3(out) 83 | out = self.relu(self.bn1(out)) 84 | out = F.avg_pool2d(out, 8) 85 | out = out.view(-1, self.nChannels) 86 | return self.fc(out) 87 | 88 | -------------------------------------------------------------------------------- /dfme/cifar10_models/mobilenetv2.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import os 4 | 5 | __all__ = ['MobileNetV2', 'mobilenet_v2'] 6 | 7 | 8 | class ConvBNReLU(nn.Sequential): 9 | def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1): 10 | padding = (kernel_size - 1) // 2 11 | super(ConvBNReLU, self).__init__( 12 | nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False), 13 | nn.BatchNorm2d(out_planes), 14 | nn.ReLU6(inplace=True) 15 | ) 16 | 17 | 18 | class InvertedResidual(nn.Module): 19 | def __init__(self, inp, oup, stride, expand_ratio): 20 | super(InvertedResidual, self).__init__() 21 | self.stride = stride 22 | assert stride in [1, 2] 23 | 24 | hidden_dim = int(round(inp * expand_ratio)) 25 | self.use_res_connect = self.stride == 1 and inp == oup 26 | 27 | layers = [] 28 | if expand_ratio != 1: 29 | # pw 30 | layers.append(ConvBNReLU(inp, hidden_dim, kernel_size=1)) 31 | layers.extend([ 32 | # dw 33 | ConvBNReLU(hidden_dim, hidden_dim, stride=stride, groups=hidden_dim), 34 | # pw-linear 35 | nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False), 36 | nn.BatchNorm2d(oup), 37 | ]) 38 | self.conv = nn.Sequential(*layers) 39 | 40 | def forward(self, x): 41 | if self.use_res_connect: 42 | return x + self.conv(x) 43 | else: 44 | return self.conv(x) 45 | 46 | 47 | class MobileNetV2(nn.Module): 48 | def __init__(self, num_classes=10, width_mult=1.0): 49 | super(MobileNetV2, self).__init__() 50 | block = InvertedResidual 51 | input_channel = 32 52 | last_channel = 1280 53 | 54 | ## CIFAR10 55 | inverted_residual_setting = [ 56 | # t, c, n, s 57 | [1, 16, 1, 1], 58 | [6, 24, 2, 1], # Stride 2 -> 1 for CIFAR-10 59 | [6, 32, 3, 2], 60 | [6, 64, 4, 2], 61 | [6, 96, 3, 1], 62 | [6, 160, 3, 2], 63 | [6, 320, 1, 1], 64 | ] 65 | ## END 66 | 67 | # building first layer 68 | input_channel = int(input_channel * width_mult) 69 | self.last_channel = int(last_channel * max(1.0, width_mult)) 70 | 71 | # CIFAR10: stride 2 -> 1 72 | features = [ConvBNReLU(3, input_channel, stride=1)] 73 | # END 74 | 75 | # building inverted residual blocks 76 | for t, c, n, s in inverted_residual_setting: 77 | output_channel = int(c * width_mult) 78 | for i in range(n): 79 | stride = s if i == 0 else 1 80 | features.append(block(input_channel, output_channel, stride, expand_ratio=t)) 81 | input_channel = output_channel 82 | # building last several layers 83 | features.append(ConvBNReLU(input_channel, self.last_channel, kernel_size=1)) 84 | # make it nn.Sequential 85 | self.features = nn.Sequential(*features) 86 | 87 | # building classifier 88 | self.classifier = nn.Sequential( 89 | nn.Dropout(0.2), 90 | nn.Linear(self.last_channel, num_classes), 91 | ) 92 | 93 | # weight initialization 94 | for m in self.modules(): 95 | if isinstance(m, nn.Conv2d): 96 | nn.init.kaiming_normal_(m.weight, mode='fan_out') 97 | if m.bias is not None: 98 | nn.init.zeros_(m.bias) 99 | elif isinstance(m, nn.BatchNorm2d): 100 | nn.init.ones_(m.weight) 101 | nn.init.zeros_(m.bias) 102 | elif isinstance(m, nn.Linear): 103 | nn.init.normal_(m.weight, 0, 0.01) 104 | nn.init.zeros_(m.bias) 105 | 106 | def forward(self, x): 107 | x = self.features(x) 108 | x = x.mean([2, 3]) 109 | x = self.classifier(x) 110 | return x 111 | 112 | 113 | def mobilenet_v2(pretrained=False, progress=True, device='cpu', **kwargs): 114 | """ 115 | Constructs a MobileNetV2 architecture from 116 | `"MobileNetV2: Inverted Residuals and Linear Bottlenecks" `_. 117 | 118 | Args: 119 | pretrained (bool): If True, returns a model pre-trained on ImageNet 120 | progress (bool): If True, displays a progress bar of the download to stderr 121 | """ 122 | model = MobileNetV2(**kwargs) 123 | if pretrained: 124 | script_dir = os.path.dirname(__file__) 125 | state_dict = torch.load(script_dir+'/state_dicts/mobilenet_v2.pt', map_location=device) 126 | model.load_state_dict(state_dict) 127 | return model 128 | -------------------------------------------------------------------------------- /dfme/network/resnet_8x.py: -------------------------------------------------------------------------------- 1 | # This part is borrowed from https://github.com/huawei-noah/Data-Efficient-Model-Compression 2 | 3 | import torch 4 | import torch.nn as nn 5 | import torch.nn.functional as F 6 | 7 | class BasicBlock(nn.Module): 8 | expansion = 1 9 | 10 | def __init__(self, in_planes, planes, stride=1): 11 | super(BasicBlock, self).__init__() 12 | self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) 13 | self.bn1 = nn.BatchNorm2d(planes) 14 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False) 15 | self.bn2 = nn.BatchNorm2d(planes) 16 | 17 | self.shortcut = nn.Sequential() 18 | if stride != 1 or in_planes != self.expansion*planes: 19 | self.shortcut = nn.Sequential( 20 | nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False), 21 | nn.BatchNorm2d(self.expansion*planes) 22 | ) 23 | 24 | def forward(self, x): 25 | out = F.relu(self.bn1(self.conv1(x))) 26 | out = self.bn2(self.conv2(out)) 27 | out += self.shortcut(x) 28 | out = F.relu(out) 29 | return out 30 | 31 | 32 | class Bottleneck(nn.Module): 33 | expansion = 4 34 | 35 | def __init__(self, in_planes, planes, stride=1): 36 | super(Bottleneck, self).__init__() 37 | self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False) 38 | self.bn1 = nn.BatchNorm2d(planes) 39 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) 40 | self.bn2 = nn.BatchNorm2d(planes) 41 | self.conv3 = nn.Conv2d(planes, self.expansion*planes, kernel_size=1, bias=False) 42 | self.bn3 = nn.BatchNorm2d(self.expansion*planes) 43 | 44 | self.shortcut = nn.Sequential() 45 | if stride != 1 or in_planes != self.expansion*planes: 46 | self.shortcut = nn.Sequential( 47 | nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False), 48 | nn.BatchNorm2d(self.expansion*planes) 49 | ) 50 | 51 | def forward(self, x): 52 | out = F.relu(self.bn1(self.conv1(x))) 53 | out = F.relu(self.bn2(self.conv2(out))) 54 | out = self.bn3(self.conv3(out)) 55 | out += self.shortcut(x) 56 | out = F.relu(out) 57 | return out 58 | 59 | 60 | class ResNet(nn.Module): 61 | def __init__(self, block, num_blocks, num_classes=10, normalize_coefs=None, normalize=False): 62 | super(ResNet, self).__init__() 63 | 64 | if normalize_coefs is not None: 65 | self.mean, self.std = normalize_coefs 66 | 67 | self.normalize = normalize 68 | 69 | self.in_planes = 64 70 | 71 | self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) 72 | self.bn1 = nn.BatchNorm2d(64) 73 | self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1) 74 | self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) 75 | self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) 76 | self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) 77 | self.linear = nn.Linear(512*block.expansion, num_classes) 78 | 79 | for m in self.modules(): 80 | if isinstance(m, nn.Conv2d): 81 | nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 82 | elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): 83 | nn.init.constant_(m.weight, 1) 84 | nn.init.constant_(m.bias, 0) 85 | 86 | def _make_layer(self, block, planes, num_blocks, stride): 87 | strides = [stride] + [1]*(num_blocks-1) 88 | layers = [] 89 | for stride in strides: 90 | layers.append(block(self.in_planes, planes, stride)) 91 | self.in_planes = planes * block.expansion 92 | return nn.Sequential(*layers) 93 | 94 | def forward(self, x, out_feature=False): 95 | 96 | if self.normalize: 97 | # Normalize according to the training data normalization statistics 98 | x -= self.mean 99 | x /= self.std 100 | 101 | out = F.relu(self.bn1(self.conv1(x))) 102 | out = self.layer1(out) 103 | out = self.layer2(out) 104 | out = self.layer3(out) 105 | out = self.layer4(out) 106 | out = F.avg_pool2d(out, 4) 107 | feature = out.view(out.size(0), -1) 108 | out = self.linear(feature) 109 | if out_feature == False: 110 | return out 111 | else: 112 | return out,feature 113 | 114 | 115 | def ResNet18_8x(num_classes=10): 116 | return ResNet(BasicBlock, [2,2,2,2], num_classes) 117 | 118 | def ResNet34_8x(num_classes=10, normalize_coefs=None, normalize=False): 119 | return ResNet(BasicBlock, [3,4,6,3], num_classes, normalize_coefs=normalize_coefs, normalize=normalize) 120 | 121 | def ResNet50_8x(num_classes=10): 122 | return ResNet(Bottleneck, [3,4,6,3], num_classes) 123 | 124 | def ResNet101_8x(num_classes=10): 125 | return ResNet(Bottleneck, [3,4,23,3], num_classes) 126 | 127 | def ResNet152_8x(num_classes=10): 128 | return ResNet(Bottleneck, [3,8,36,3], num_classes) 129 | 130 | -------------------------------------------------------------------------------- /surrogate_benchmark/resnet_8x.py: -------------------------------------------------------------------------------- 1 | # This part is borrowed from https://github.com/huawei-noah/Data-Efficient-Model-Compression 2 | 3 | import torch 4 | import torch.nn as nn 5 | import torch.nn.functional as F 6 | 7 | class BasicBlock(nn.Module): 8 | expansion = 1 9 | 10 | def __init__(self, in_planes, planes, stride=1): 11 | super(BasicBlock, self).__init__() 12 | self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) 13 | self.bn1 = nn.BatchNorm2d(planes) 14 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False) 15 | self.bn2 = nn.BatchNorm2d(planes) 16 | 17 | self.shortcut = nn.Sequential() 18 | if stride != 1 or in_planes != self.expansion*planes: 19 | self.shortcut = nn.Sequential( 20 | nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False), 21 | nn.BatchNorm2d(self.expansion*planes) 22 | ) 23 | 24 | def forward(self, x): 25 | out = F.relu(self.bn1(self.conv1(x))) 26 | out = self.bn2(self.conv2(out)) 27 | out += self.shortcut(x) 28 | out = F.relu(out) 29 | return out 30 | 31 | 32 | class Bottleneck(nn.Module): 33 | expansion = 4 34 | 35 | def __init__(self, in_planes, planes, stride=1): 36 | super(Bottleneck, self).__init__() 37 | self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False) 38 | self.bn1 = nn.BatchNorm2d(planes) 39 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) 40 | self.bn2 = nn.BatchNorm2d(planes) 41 | self.conv3 = nn.Conv2d(planes, self.expansion*planes, kernel_size=1, bias=False) 42 | self.bn3 = nn.BatchNorm2d(self.expansion*planes) 43 | 44 | self.shortcut = nn.Sequential() 45 | if stride != 1 or in_planes != self.expansion*planes: 46 | self.shortcut = nn.Sequential( 47 | nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False), 48 | nn.BatchNorm2d(self.expansion*planes) 49 | ) 50 | 51 | def forward(self, x): 52 | out = F.relu(self.bn1(self.conv1(x))) 53 | out = F.relu(self.bn2(self.conv2(out))) 54 | out = self.bn3(self.conv3(out)) 55 | out += self.shortcut(x) 56 | out = F.relu(out) 57 | return out 58 | 59 | 60 | class ResNet(nn.Module): 61 | def __init__(self, block, num_blocks, num_classes=10, normalize_coefs=None, normalize=False): 62 | super(ResNet, self).__init__() 63 | 64 | if normalize_coefs is not None: 65 | self.mean, self.std = normalize_coefs 66 | 67 | self.normalize = normalize 68 | 69 | self.in_planes = 64 70 | 71 | self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) 72 | self.bn1 = nn.BatchNorm2d(64) 73 | self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1) 74 | self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) 75 | self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) 76 | self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) 77 | self.linear = nn.Linear(512*block.expansion, num_classes) 78 | 79 | for m in self.modules(): 80 | if isinstance(m, nn.Conv2d): 81 | nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 82 | elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): 83 | nn.init.constant_(m.weight, 1) 84 | nn.init.constant_(m.bias, 0) 85 | 86 | def _make_layer(self, block, planes, num_blocks, stride): 87 | strides = [stride] + [1]*(num_blocks-1) 88 | layers = [] 89 | for stride in strides: 90 | layers.append(block(self.in_planes, planes, stride)) 91 | self.in_planes = planes * block.expansion 92 | return nn.Sequential(*layers) 93 | 94 | def forward(self, x, out_feature=False): 95 | 96 | if self.normalize: 97 | # Normalize according to the training data normalization statistics 98 | x -= self.mean 99 | x /= self.std 100 | 101 | out = F.relu(self.bn1(self.conv1(x))) 102 | out = self.layer1(out) 103 | out = self.layer2(out) 104 | out = self.layer3(out) 105 | out = self.layer4(out) 106 | out = F.avg_pool2d(out, 4) 107 | feature = out.view(out.size(0), -1) 108 | out = self.linear(feature) 109 | if out_feature == False: 110 | return out 111 | else: 112 | return out,feature 113 | 114 | 115 | def ResNet18_8x(num_classes=10): 116 | return ResNet(BasicBlock, [2,2,2,2], num_classes) 117 | 118 | def ResNet34_8x(num_classes=10, normalize_coefs=None, normalize=False): 119 | return ResNet(BasicBlock, [3,4,6,3], num_classes, normalize_coefs=normalize_coefs, normalize=normalize) 120 | 121 | def ResNet50_8x(num_classes=10): 122 | return ResNet(Bottleneck, [3,4,6,3], num_classes) 123 | 124 | def ResNet101_8x(num_classes=10): 125 | return ResNet(Bottleneck, [3,4,23,3], num_classes) 126 | 127 | def ResNet152_8x(num_classes=10): 128 | return ResNet(Bottleneck, [3,8,36,3], num_classes) 129 | 130 | -------------------------------------------------------------------------------- /dfme/cifar10_models/kt_wrn.py: -------------------------------------------------------------------------------- 1 | """ 2 | Code adapted from https://github.com/xternalz/WideResNet-pytorch 3 | Modifications = return activations for use in attention transfer, 4 | as done before e.g in https://github.com/BayesWatch/pytorch-moonshine 5 | """ 6 | 7 | 8 | import math 9 | import torch 10 | import torch.nn as nn 11 | import torch.nn.functional as F 12 | 13 | 14 | class BasicBlock(nn.Module): 15 | def __init__(self, in_planes, out_planes, stride, dropRate=0.0): 16 | super(BasicBlock, self).__init__() 17 | self.bn1 = nn.BatchNorm2d(in_planes) 18 | self.relu1 = nn.ReLU(inplace=True) 19 | self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, 20 | padding=1, bias=False) 21 | self.bn2 = nn.BatchNorm2d(out_planes) 22 | self.relu2 = nn.ReLU(inplace=True) 23 | self.conv2 = nn.Conv2d(out_planes, out_planes, kernel_size=3, stride=1, 24 | padding=1, bias=False) 25 | self.droprate = dropRate 26 | self.equalInOut = (in_planes == out_planes) 27 | self.convShortcut = (not self.equalInOut) and nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, 28 | padding=0, bias=False) or None 29 | 30 | def forward(self, x): 31 | if not self.equalInOut: 32 | x = self.relu1(self.bn1(x)) 33 | else: 34 | out = self.relu1(self.bn1(x)) 35 | out = self.relu2(self.bn2(self.conv1(out if self.equalInOut else x))) 36 | if self.droprate > 0: 37 | out = F.dropout(out, p=self.droprate, training=self.training) 38 | out = self.conv2(out) 39 | return torch.add(x if self.equalInOut else self.convShortcut(x), out) 40 | 41 | class NetworkBlock(nn.Module): 42 | def __init__(self, nb_layers, in_planes, out_planes, block, stride, dropRate=0.0): 43 | super(NetworkBlock, self).__init__() 44 | self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, dropRate) 45 | 46 | def _make_layer(self, block, in_planes, out_planes, nb_layers, stride, dropRate): 47 | layers = [] 48 | for i in range(int(nb_layers)): 49 | layers.append(block(i == 0 and in_planes or out_planes, out_planes, i == 0 and stride or 1, dropRate)) 50 | return nn.Sequential(*layers) 51 | 52 | def forward(self, x): 53 | return self.layer(x) 54 | 55 | class WideResNetKT(nn.Module): 56 | def __init__(self, depth, num_classes, widen_factor=1, dropRate=0.0): 57 | super(WideResNetKT, self).__init__() 58 | nChannels = [16, 16*widen_factor, 32*widen_factor, 64*widen_factor] 59 | assert((depth - 4) % 6 == 0) 60 | n = (depth - 4) / 6 61 | block = BasicBlock 62 | # 1st conv before any network block 63 | self.conv1 = nn.Conv2d(3, nChannels[0], kernel_size=3, stride=1, 64 | padding=1, bias=False) 65 | # 1st block 66 | self.block1 = NetworkBlock(n, nChannels[0], nChannels[1], block, 1, dropRate) 67 | # 2nd block 68 | self.block2 = NetworkBlock(n, nChannels[1], nChannels[2], block, 2, dropRate) 69 | # 3rd block 70 | self.block3 = NetworkBlock(n, nChannels[2], nChannels[3], block, 2, dropRate) 71 | # global average pooling and classifier 72 | self.bn1 = nn.BatchNorm2d(nChannels[3]) 73 | self.relu = nn.ReLU(inplace=True) 74 | self.fc = nn.Linear(nChannels[3], num_classes) 75 | self.nChannels = nChannels[3] 76 | 77 | for m in self.modules(): 78 | if isinstance(m, nn.Conv2d): 79 | n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels 80 | m.weight.data.normal_(0, math.sqrt(2. / n)) 81 | elif isinstance(m, nn.BatchNorm2d): 82 | m.weight.data.fill_(1) 83 | m.bias.data.zero_() 84 | elif isinstance(m, nn.Linear): 85 | m.bias.data.zero_() 86 | 87 | 88 | def forward(self, x): 89 | out = self.conv1(x) 90 | out = self.block1(out) 91 | # activation1 = out 92 | out = self.block2(out) 93 | # activation2 = out 94 | out = self.block3(out) 95 | # activation3 = out 96 | out = self.relu(self.bn1(out)) 97 | out = F.avg_pool2d(out, 8) 98 | out = out.view(-1, self.nChannels) 99 | return self.fc(out)#, activation1, activation2, activation3 100 | 101 | 102 | if __name__ == '__main__': 103 | import random 104 | import time 105 | from torchsummary import summary 106 | 107 | x = torch.FloatTensor(64, 3, 32, 32).uniform_(0, 1) 108 | 109 | ### WideResNets 110 | # Notation: W-depth-widening_factor 111 | #model = WideResNet(depth=16, num_classes=10, widen_factor=1, dropRate=0.0) 112 | #model = WideResNet(depth=16, num_classes=10, widen_factor=2, dropRate=0.0) 113 | #model = WideResNet(depth=16, num_classes=10, widen_factor=8, dropRate=0.0) 114 | #model = WideResNet(depth=16, num_classes=10, widen_factor=10, dropRate=0.0) 115 | #model = WideResNet(depth=22, num_classes=10, widen_factor=8, dropRate=0.0) 116 | #model = WideResNet(depth=34, num_classes=10, widen_factor=2, dropRate=0.0) 117 | #model = WideResNet(depth=40, num_classes=10, widen_factor=10, dropRate=0.0) 118 | #model = WideResNet(depth=40, num_classes=10, widen_factor=1, dropRate=0.0) 119 | model = WideResNet(depth=40, num_classes=10, widen_factor=2, dropRate=0.0) 120 | ###model = WideResNet(depth=50, num_classes=10, widen_factor=2, dropRate=0.0) 121 | 122 | t0 = time.time() 123 | output, *act = model(x) 124 | print("Time taken for forward pass: {} s".format(time.time() - t0)) 125 | print("\nOUTPUT SHPAE: ", output.shape) 126 | 127 | summary(model, input_size=(3, 32, 32)) 128 | 129 | -------------------------------------------------------------------------------- /dfme/network/gan.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import ipdb 5 | 6 | class Flatten(nn.Module): 7 | def __init__(self): 8 | super(Flatten, self).__init__() 9 | 10 | def forward(self, x): 11 | return x.view(x.shape[0], -1) 12 | 13 | class GeneratorA(nn.Module): 14 | def __init__(self, nz=100, ngf=64, nc=1, img_size=32, activation=None, final_bn=True): 15 | super(GeneratorA, self).__init__() 16 | 17 | if activation is None: 18 | raise ValueError("Provide a valid activation function") 19 | self.activation = activation 20 | 21 | self.init_size = img_size//4 22 | self.l1 = nn.Sequential(nn.Linear(nz, ngf*2*self.init_size**2)) 23 | 24 | self.conv_blocks0 = nn.Sequential( 25 | nn.BatchNorm2d(ngf*2), 26 | ) 27 | self.conv_blocks1 = nn.Sequential( 28 | nn.Conv2d(ngf*2, ngf*2, 3, stride=1, padding=1), 29 | nn.BatchNorm2d(ngf*2), 30 | nn.LeakyReLU(0.2, inplace=True), 31 | ) 32 | 33 | if final_bn: 34 | self.conv_blocks2 = nn.Sequential( 35 | nn.Conv2d(ngf*2, ngf, 3, stride=1, padding=1), 36 | nn.BatchNorm2d(ngf), 37 | nn.LeakyReLU(0.2, inplace=True), 38 | nn.Conv2d(ngf, nc, 3, stride=1, padding=1), 39 | # nn.Tanh(), 40 | nn.BatchNorm2d(nc, affine=False) 41 | ) 42 | else: 43 | self.conv_blocks2 = nn.Sequential( 44 | nn.Conv2d(ngf*2, ngf, 3, stride=1, padding=1), 45 | nn.BatchNorm2d(ngf), 46 | nn.LeakyReLU(0.2, inplace=True), 47 | nn.Conv2d(ngf, nc, 3, stride=1, padding=1), 48 | # nn.Tanh(), 49 | # nn.BatchNorm2d(nc, affine=False) 50 | ) 51 | 52 | def forward(self, z, pre_x=False): 53 | out = self.l1(z.view(z.shape[0],-1)) 54 | out = out.view(out.shape[0], -1, self.init_size, self.init_size) 55 | img = self.conv_blocks0(out) 56 | img = nn.functional.interpolate(img,scale_factor=2) 57 | img = self.conv_blocks1(img) 58 | img = nn.functional.interpolate(img,scale_factor=2) 59 | img = self.conv_blocks2(img) 60 | 61 | if pre_x : 62 | return img 63 | else: 64 | # img = nn.functional.interpolate(img, scale_factor=2) 65 | return self.activation(img) 66 | 67 | class GeneratorC(nn.Module): 68 | ''' 69 | Conditional Generator 70 | ''' 71 | def __init__(self, nz=100, num_classes=10, ngf=64, nc=1, img_size=32): 72 | super(GeneratorC, self).__init__() 73 | 74 | self.label_emb = nn.Embedding(num_classes, nz) 75 | 76 | self.init_size = img_size//4 77 | self.l1 = nn.Sequential(nn.Linear(nz*2, ngf*2*self.init_size**2)) 78 | 79 | self.conv_blocks0 = nn.Sequential( 80 | nn.BatchNorm2d(ngf*2), 81 | ) 82 | self.conv_blocks1 = nn.Sequential( 83 | nn.Conv2d(ngf*2, ngf*2, 3, stride=1, padding=1), 84 | nn.BatchNorm2d(ngf*2), 85 | nn.LeakyReLU(0.2, inplace=True), 86 | ) 87 | self.conv_blocks2 = nn.Sequential( 88 | nn.Conv2d(ngf*2, ngf, 3, stride=1, padding=1), 89 | nn.BatchNorm2d(ngf), 90 | nn.LeakyReLU(0.2, inplace=True), 91 | nn.Conv2d(ngf, nc, 3, stride=1, padding=1), 92 | nn.Tanh(), 93 | nn.BatchNorm2d(nc, affine=False) 94 | ) 95 | 96 | def forward(self, z, label): 97 | # Concatenate label embedding and image to produce input 98 | label_inp = self.label_emb(label) 99 | gen_input = torch.cat((label_inp, z), -1) 100 | 101 | out = self.l1(gen_input.view(gen_input.shape[0],-1)) 102 | out = out.view(out.shape[0], -1, self.init_size, self.init_size) 103 | img = self.conv_blocks0(out) 104 | img = nn.functional.interpolate(img,scale_factor=2) 105 | img = self.conv_blocks1(img) 106 | img = nn.functional.interpolate(img,scale_factor=2) 107 | img = self.conv_blocks2(img) 108 | return img 109 | 110 | 111 | class GeneratorB(nn.Module): 112 | """ Generator from DCGAN: https://arxiv.org/abs/1511.06434 113 | """ 114 | def __init__(self, nz=256, ngf=64, nc=3, img_size=64, slope=0.2): 115 | super(GeneratorB, self).__init__() 116 | if isinstance(img_size, (list, tuple)): 117 | self.init_size = ( img_size[0]//16, img_size[1]//16 ) 118 | else: 119 | self.init_size = ( img_size // 16, img_size // 16) 120 | 121 | self.project = nn.Sequential( 122 | Flatten(), 123 | nn.Linear(nz, ngf*8*self.init_size[0]*self.init_size[1]), 124 | ) 125 | 126 | self.main = nn.Sequential( 127 | nn.BatchNorm2d(ngf*8), 128 | 129 | nn.ConvTranspose2d(ngf*8, ngf*4, 4, 2, 1, bias=False), 130 | nn.BatchNorm2d(ngf*4), 131 | nn.LeakyReLU(slope, inplace=True), 132 | # 2x 133 | 134 | nn.ConvTranspose2d(ngf*4, ngf*2, 4, 2, 1, bias=False), 135 | nn.BatchNorm2d(ngf*2), 136 | nn.LeakyReLU(slope, inplace=True), 137 | # 4x 138 | 139 | nn.ConvTranspose2d(ngf*2, ngf, 4, 2, 1, bias=False), 140 | nn.BatchNorm2d(ngf), 141 | nn.LeakyReLU(slope, inplace=True), 142 | # 8x 143 | 144 | nn.ConvTranspose2d(ngf, ngf, 4, 2, 1, bias=False), 145 | nn.BatchNorm2d(ngf), 146 | nn.LeakyReLU(slope, inplace=True), 147 | # 16x 148 | 149 | nn.Conv2d(ngf, nc, 3,1,1), 150 | nn.Tanh(), 151 | ) 152 | 153 | for m in self.modules(): 154 | if isinstance(m, (nn.ConvTranspose2d, nn.Linear, nn.Conv2d)): 155 | nn.init.normal_(m.weight, 0.0, 0.02) 156 | if m.bias is not None: 157 | nn.init.constant_(m.bias, 0) 158 | if isinstance(m, (nn.BatchNorm2d)): 159 | nn.init.normal_(m.weight, 1.0, 0.02) 160 | nn.init.constant_(m.bias, 0) 161 | 162 | def forward(self, z): 163 | proj = self.project(z) 164 | proj = proj.view(proj.shape[0], -1, self.init_size[0], self.init_size[1]) 165 | output = self.main(proj) 166 | return output 167 | 168 | -------------------------------------------------------------------------------- /surrogate_benchmark/train.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import ipdb 3 | import torch.nn as nn 4 | import torch.optim as optim 5 | import sys, os, json 6 | import params 7 | from dataloader import * 8 | from wrn import WideResNet 9 | from resnet_8x import ResNet34_8x, ResNet18_8x 10 | 11 | import numpy as np 12 | from tqdm import tqdm 13 | import torch.nn.functional as F 14 | 15 | def step_lr(lr_max, epoch, num_epochs): 16 | """Step Scheduler""" 17 | ratio = epoch/float(num_epochs) 18 | if ratio < 0.3: return lr_max 19 | elif ratio < 0.6: return lr_max*0.2 20 | elif ratio <0.8: return lr_max*0.2*0.2 21 | else: return lr_max*0.2*0.2*0.2 22 | 23 | def lr_scheduler(args): 24 | """Learning Rate Scheduler Options""" 25 | if args.lr_mode == 1: 26 | lr_schedule = lambda t: np.interp([t], [0, args.epochs//2, args.epochs], [args.lr_min, args.lr_max, args.lr_min])[0] 27 | elif args.lr_mode == 0: 28 | lr_schedule = lambda t: step_lr(args.lr_max, t, args.epochs) 29 | return lr_schedule 30 | 31 | def epoch(args, loader, model, teacher = None, lr_schedule = None, epoch_i = None, opt=None, stop=False): 32 | """Extraction epoch over the dataset""" 33 | 34 | train_loss = 0 35 | train_acc = 0 36 | train_n = 0 37 | i = 0 38 | func = tqdm if stop == False else lambda x:x 39 | criterion_kl = nn.KLDivLoss(reduction = "batchmean") 40 | alpha, T = 1.0, args.temp 41 | # ipdb.set_trace() 42 | for batch in func(loader): 43 | X,y = batch[0].to(args.device), batch[1].to(args.device) 44 | if args.surrogate == "mnist": 45 | X = X.repeat(1,3, 1, 1) 46 | yp = model(X) 47 | 48 | with torch.no_grad(): 49 | t_p = teacher(X).detach() 50 | y = t_p.max(1)[1] 51 | 52 | loss = criterion_kl(F.log_softmax(yp/T, dim=1), F.softmax(t_p/T, dim=1))*(alpha * T * T) 53 | 54 | if opt: 55 | lr = lr_schedule(epoch_i + (i+1)/len(loader)) 56 | opt.param_groups[0].update(lr=lr) 57 | opt.zero_grad() 58 | loss.backward() 59 | opt.step() 60 | 61 | train_loss += loss.item()*y.size(0) 62 | train_acc += (yp.max(1)[1] == y).sum().item() 63 | train_n += y.size(0) 64 | i += 1 65 | if train_n >= 50000: 66 | break 67 | 68 | return train_loss / train_n, train_acc / train_n 69 | 70 | 71 | def epoch_test(args, loader, model, stop = False): 72 | """Evaluation epoch over the dataset""" 73 | test_loss = 0; test_acc = 0; test_n = 0 74 | func = lambda x:x 75 | with torch.no_grad(): 76 | for batch in func(loader): 77 | X,y = batch[0].to(args.device), batch[1].to(args.device) 78 | yp = model(X) 79 | loss = nn.CrossEntropyLoss()(yp,y) 80 | test_loss += loss.item()*y.size(0) 81 | test_acc += (yp.max(1)[1] == y).sum().item() 82 | test_n += y.size(0) 83 | if stop: 84 | break 85 | return test_loss / test_n, test_acc / test_n 86 | 87 | epoch_adversarial = epoch 88 | 89 | def trainer(args): 90 | train_loader, _ = data_loader(args.surrogate, args.batch_size,50000) 91 | _, test_loader = data_loader(args.target, args.batch_size,50000) 92 | 93 | def myprint(a): 94 | print(a); file.write(a); file.write("\n"); file.flush() 95 | 96 | file = open(f"{args.model_dir}/logs.txt", "w") 97 | 98 | student, teacher = get_student_teacher(args) 99 | student = student.to(args.device) 100 | teacher = teacher.to(args.device) 101 | 102 | #Test the victim model 103 | test_loss, test_acc = epoch_test(args, test_loader, teacher) 104 | print("Teacher Accuracy = ", test_acc) 105 | 106 | if args.opt_type == "SGD": 107 | opt = optim.SGD(student.parameters(), lr=0.1, momentum=0.9, weight_decay=5e-4) 108 | else: 109 | opt = optim.Adam(student.parameters(), lr=0.1) 110 | 111 | lr_schedule = lr_scheduler(args) 112 | t_start = 0 113 | 114 | train_func = epoch 115 | for t in range(t_start,args.epochs): 116 | lr = lr_schedule(t) 117 | student.train() 118 | train_loss, train_acc = epoch(args, train_loader, student, teacher = teacher, lr_schedule = lr_schedule, epoch_i = t, opt = opt) 119 | student.eval() 120 | test_loss, test_acc = epoch_test(args, test_loader, student) 121 | myprint(f'Epoch: {t}, Train Loss: {train_loss:.3f} Train Acc: {train_acc:.3f} Test Acc: {test_acc:.3f}, lr: {lr:.5f}') 122 | 123 | #Save final model 124 | torch.save(student.state_dict(), f"{args.model_dir}/final.pt") 125 | 126 | 127 | def get_student_teacher(args): 128 | #Load teacher weights and student architecture 129 | teacher = ResNet34_8x(num_classes=args.num_classes) 130 | teacher.load_state_dict( torch.load( args.ckpt, map_location=device) ) 131 | teacher.eval() 132 | student = ResNet18_8x(num_classes=args.num_classes) 133 | student.train() 134 | 135 | return student, teacher 136 | 137 | 138 | if __name__ == "__main__": 139 | parser = params.parse_args() 140 | args = parser.parse_args() 141 | args = params.add_config(args) if args.config_file != None else args 142 | print(args) 143 | 144 | target = args.target 145 | surrogate = args.surrogate 146 | targets_list = ["cifar10","svhn"] 147 | cifar_surrogates = ["cifar10","cifar100","mnist","random","svhn","random"] 148 | svhn_surrogates = ["mnist","cifar10","random","svhn","svhn_skew","random"] 149 | surrogates_list = {"cifar10": cifar_surrogates, "svhn":svhn_surrogates} 150 | 151 | assert (target in targets_list) 152 | assert (surrogate in surrogates_list[target]) 153 | 154 | device = torch.device(f"cuda:{args.device}" if torch.cuda.is_available() else "cpu") 155 | root = f"../models/{args.target}" 156 | model_dir = f"{root}/model_{args.surrogate}/temp_{args.temp}_lr_mode_{args.lr_mode}"; print("Model Directory:", model_dir); args.model_dir = model_dir 157 | args.model_dir = model_dir 158 | 159 | if(not os.path.exists(model_dir)): 160 | os.makedirs(model_dir) 161 | 162 | with open(f"{model_dir}/model_info.txt", "w") as f: 163 | json.dump(args.__dict__, f, indent=2) 164 | args.device = device 165 | print(device) 166 | torch.cuda.set_device(device); torch.manual_seed(args.seed) 167 | args.num_classes = 10 168 | args.ckpt = f"../dfme/checkpoint/teacher/{args.target}-resnet34_8x.pt" 169 | trainer(args) 170 | -------------------------------------------------------------------------------- /dfme/cifar10_models/vgg.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import os 4 | 5 | __all__ = [ 6 | 'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn', 7 | 'vgg19_bn', 'vgg19', 8 | ] 9 | 10 | class VGG(nn.Module): 11 | 12 | def __init__(self, features, num_classes=10, init_weights=True): 13 | super(VGG, self).__init__() 14 | self.features = features 15 | self.avgpool = nn.AdaptiveAvgPool2d((7, 7)) 16 | self.classifier = nn.Sequential( 17 | nn.Linear(512 * 7 * 7, 4096), 18 | nn.ReLU(True), 19 | nn.Dropout(), 20 | nn.Linear(4096, 4096), 21 | nn.ReLU(True), 22 | nn.Dropout(), 23 | nn.Linear(4096, num_classes), 24 | ) 25 | if init_weights: 26 | self._initialize_weights() 27 | 28 | def forward(self, x): 29 | x = self.features(x) 30 | x = self.avgpool(x) 31 | x = x.view(x.size(0), -1) 32 | x = self.classifier(x) 33 | return x 34 | 35 | def _initialize_weights(self): 36 | for m in self.modules(): 37 | if isinstance(m, nn.Conv2d): 38 | nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 39 | if m.bias is not None: 40 | nn.init.constant_(m.bias, 0) 41 | elif isinstance(m, nn.BatchNorm2d): 42 | nn.init.constant_(m.weight, 1) 43 | nn.init.constant_(m.bias, 0) 44 | elif isinstance(m, nn.Linear): 45 | nn.init.normal_(m.weight, 0, 0.01) 46 | nn.init.constant_(m.bias, 0) 47 | 48 | 49 | def make_layers(cfg, batch_norm=False): 50 | layers = [] 51 | in_channels = 3 52 | for v in cfg: 53 | if v == 'M': 54 | layers += [nn.MaxPool2d(kernel_size=2, stride=2)] 55 | else: 56 | conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1) 57 | if batch_norm: 58 | layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)] 59 | else: 60 | layers += [conv2d, nn.ReLU(inplace=True)] 61 | in_channels = v 62 | return nn.Sequential(*layers) 63 | 64 | 65 | cfgs = { 66 | 'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 67 | 'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'], 68 | 'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'], 69 | 'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'], 70 | } 71 | 72 | 73 | def _vgg(arch, cfg, batch_norm, pretrained, progress, device, **kwargs): 74 | if pretrained: 75 | kwargs['init_weights'] = False 76 | model = VGG(make_layers(cfgs[cfg], batch_norm=batch_norm), **kwargs) 77 | if pretrained: 78 | script_dir = os.path.dirname(__file__) 79 | state_dict = torch.load(script_dir + '/state_dicts/'+arch+'.pt', map_location=device) 80 | model.load_state_dict(state_dict) 81 | return model 82 | 83 | 84 | def vgg11(pretrained=False, progress=True, device='cpu', **kwargs): 85 | """VGG 11-layer model (configuration "A") 86 | 87 | Args: 88 | pretrained (bool): If True, returns a model pre-trained on ImageNet 89 | progress (bool): If True, displays a progress bar of the download to stderr 90 | """ 91 | return _vgg('vgg11', 'A', False, pretrained, progress, device, **kwargs) 92 | 93 | 94 | def vgg11_bn(pretrained=False, progress=True, device='cpu', **kwargs): 95 | """VGG 11-layer model (configuration "A") with batch normalization 96 | 97 | Args: 98 | pretrained (bool): If True, returns a model pre-trained on ImageNet 99 | progress (bool): If True, displays a progress bar of the download to stderr 100 | """ 101 | return _vgg('vgg11_bn', 'A', True, pretrained, progress, device, **kwargs) 102 | 103 | 104 | def vgg13(pretrained=False, progress=True, device='cpu', **kwargs): 105 | """VGG 13-layer model (configuration "B") 106 | 107 | Args: 108 | pretrained (bool): If True, returns a model pre-trained on ImageNet 109 | progress (bool): If True, displays a progress bar of the download to stderr 110 | """ 111 | return _vgg('vgg13', 'B', False, pretrained, progress, device, **kwargs) 112 | 113 | 114 | def vgg13_bn(pretrained=False, progress=True, device='cpu', **kwargs): 115 | """VGG 13-layer model (configuration "B") with batch normalization 116 | 117 | Args: 118 | pretrained (bool): If True, returns a model pre-trained on ImageNet 119 | progress (bool): If True, displays a progress bar of the download to stderr 120 | """ 121 | return _vgg('vgg13_bn', 'B', True, pretrained, progress, device, **kwargs) 122 | 123 | 124 | def vgg16(pretrained=False, progress=True, device='cpu', **kwargs): 125 | """VGG 16-layer model (configuration "D") 126 | 127 | Args: 128 | pretrained (bool): If True, returns a model pre-trained on ImageNet 129 | progress (bool): If True, displays a progress bar of the download to stderr 130 | """ 131 | return _vgg('vgg16', 'D', False, pretrained, progress, device, **kwargs) 132 | 133 | 134 | def vgg16_bn(pretrained=False, progress=True, device='cpu', **kwargs): 135 | """VGG 16-layer model (configuration "D") with batch normalization 136 | 137 | Args: 138 | pretrained (bool): If True, returns a model pre-trained on ImageNet 139 | progress (bool): If True, displays a progress bar of the download to stderr 140 | """ 141 | return _vgg('vgg16_bn', 'D', True, pretrained, progress, device, **kwargs) 142 | 143 | 144 | def vgg19(pretrained=False, progress=True, device='cpu', **kwargs): 145 | """VGG 19-layer model (configuration "E") 146 | 147 | Args: 148 | pretrained (bool): If True, returns a model pre-trained on ImageNet 149 | progress (bool): If True, displays a progress bar of the download to stderr 150 | """ 151 | return _vgg('vgg19', 'E', False, pretrained, progress, device, **kwargs) 152 | 153 | 154 | def vgg19_bn(pretrained=False, progress=True, device='cpu', **kwargs): 155 | """VGG 19-layer model (configuration 'E') with batch normalization 156 | 157 | Args: 158 | pretrained (bool): If True, returns a model pre-trained on ImageNet 159 | progress (bool): If True, displays a progress bar of the download to stderr 160 | """ 161 | return _vgg('vgg19_bn', 'E', True, pretrained, progress, device, **kwargs) 162 | -------------------------------------------------------------------------------- /dfme/cifar10_models/densenet.py: -------------------------------------------------------------------------------- 1 | import re 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | from collections import OrderedDict 6 | import os 7 | 8 | __all__ = ['DenseNet', 'densenet121', 'densenet169', 'densenet201', 'densenet161'] 9 | 10 | class _DenseLayer(nn.Sequential): 11 | def __init__(self, num_input_features, growth_rate, bn_size, drop_rate): 12 | super(_DenseLayer, self).__init__() 13 | self.add_module('norm1', nn.BatchNorm2d(num_input_features)), 14 | self.add_module('relu1', nn.ReLU(inplace=True)), 15 | self.add_module('conv1', nn.Conv2d(num_input_features, bn_size * 16 | growth_rate, kernel_size=1, stride=1, 17 | bias=False)), 18 | self.add_module('norm2', nn.BatchNorm2d(bn_size * growth_rate)), 19 | self.add_module('relu2', nn.ReLU(inplace=True)), 20 | self.add_module('conv2', nn.Conv2d(bn_size * growth_rate, growth_rate, 21 | kernel_size=3, stride=1, padding=1, 22 | bias=False)), 23 | self.drop_rate = drop_rate 24 | 25 | def forward(self, x): 26 | new_features = super(_DenseLayer, self).forward(x) 27 | if self.drop_rate > 0: 28 | new_features = F.dropout(new_features, p=self.drop_rate, 29 | training=self.training) 30 | return torch.cat([x, new_features], 1) 31 | 32 | 33 | class _DenseBlock(nn.Sequential): 34 | def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate): 35 | super(_DenseBlock, self).__init__() 36 | for i in range(num_layers): 37 | layer = _DenseLayer(num_input_features + i * growth_rate, growth_rate, 38 | bn_size, drop_rate) 39 | self.add_module('denselayer%d' % (i + 1), layer) 40 | 41 | 42 | class _Transition(nn.Sequential): 43 | def __init__(self, num_input_features, num_output_features): 44 | super(_Transition, self).__init__() 45 | self.add_module('norm', nn.BatchNorm2d(num_input_features)) 46 | self.add_module('relu', nn.ReLU(inplace=True)) 47 | self.add_module('conv', nn.Conv2d(num_input_features, num_output_features, 48 | kernel_size=1, stride=1, bias=False)) 49 | self.add_module('pool', nn.AvgPool2d(kernel_size=2, stride=2)) 50 | 51 | 52 | class DenseNet(nn.Module): 53 | r"""Densenet-BC model class, based on 54 | `"Densely Connected Convolutional Networks" `_ 55 | 56 | Args: 57 | growth_rate (int) - how many filters to add each layer (`k` in paper) 58 | block_config (list of 4 ints) - how many layers in each pooling block 59 | num_init_features (int) - the number of filters to learn in the first convolution layer 60 | bn_size (int) - multiplicative factor for number of bottle neck layers 61 | (i.e. bn_size * k features in the bottleneck layer) 62 | drop_rate (float) - dropout rate after each dense layer 63 | num_classes (int) - number of classification classes 64 | """ 65 | 66 | def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16), 67 | num_init_features=64, bn_size=4, drop_rate=0, num_classes=10): 68 | 69 | super(DenseNet, self).__init__() 70 | 71 | # First convolution 72 | 73 | # CIFAR-10: kernel_size 7 ->3, stride 2->1, padding 3->1 74 | self.features = nn.Sequential(OrderedDict([ 75 | ('conv0', nn.Conv2d(3, num_init_features, kernel_size=3, stride=1, 76 | padding=1, bias=False)), 77 | ('norm0', nn.BatchNorm2d(num_init_features)), 78 | ('relu0', nn.ReLU(inplace=True)), 79 | ('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)), 80 | ])) 81 | ## END 82 | 83 | # Each denseblock 84 | num_features = num_init_features 85 | for i, num_layers in enumerate(block_config): 86 | block = _DenseBlock(num_layers=num_layers, num_input_features=num_features, 87 | bn_size=bn_size, growth_rate=growth_rate, 88 | drop_rate=drop_rate) 89 | self.features.add_module('denseblock%d' % (i + 1), block) 90 | num_features = num_features + num_layers * growth_rate 91 | if i != len(block_config) - 1: 92 | trans = _Transition(num_input_features=num_features, 93 | num_output_features=num_features // 2) 94 | self.features.add_module('transition%d' % (i + 1), trans) 95 | num_features = num_features // 2 96 | 97 | # Final batch norm 98 | self.features.add_module('norm5', nn.BatchNorm2d(num_features)) 99 | 100 | # Linear layer 101 | self.classifier = nn.Linear(num_features, num_classes) 102 | 103 | # Official init from torch repo. 104 | for m in self.modules(): 105 | if isinstance(m, nn.Conv2d): 106 | nn.init.kaiming_normal_(m.weight) 107 | elif isinstance(m, nn.BatchNorm2d): 108 | nn.init.constant_(m.weight, 1) 109 | nn.init.constant_(m.bias, 0) 110 | elif isinstance(m, nn.Linear): 111 | nn.init.constant_(m.bias, 0) 112 | 113 | def forward(self, x): 114 | features = self.features(x) 115 | out = F.relu(features, inplace=True) 116 | out = F.adaptive_avg_pool2d(out, (1, 1)).view(features.size(0), -1) 117 | out = self.classifier(out) 118 | return out 119 | 120 | def _densenet(arch, growth_rate, block_config, num_init_features, pretrained, progress, device, **kwargs): 121 | model = DenseNet(growth_rate, block_config, num_init_features, **kwargs) 122 | if pretrained: 123 | script_dir = os.path.dirname(__file__) 124 | state_dict = torch.load(script_dir + '/state_dicts/'+arch+'.pt', map_location=device) 125 | model.load_state_dict(state_dict) 126 | return model 127 | 128 | 129 | def densenet121(pretrained=False, progress=True, device='cpu', **kwargs): 130 | r"""Densenet-121 model from 131 | `"Densely Connected Convolutional Networks" `_ 132 | 133 | Args: 134 | pretrained (bool): If True, returns a model pre-trained on ImageNet 135 | progress (bool): If True, displays a progress bar of the download to stderr 136 | """ 137 | return _densenet('densenet121', 32, (6, 12, 24, 16), 64, pretrained, progress, device, 138 | **kwargs) 139 | 140 | 141 | def densenet161(pretrained=False, progress=True, device='cpu', **kwargs): 142 | r"""Densenet-161 model from 143 | `"Densely Connected Convolutional Networks" `_ 144 | 145 | Args: 146 | pretrained (bool): If True, returns a model pre-trained on ImageNet 147 | progress (bool): If True, displays a progress bar of the download to stderr 148 | """ 149 | return _densenet('densenet161', 48, (6, 12, 36, 24), 96, pretrained, progress, device, 150 | **kwargs) 151 | 152 | 153 | def densenet169(pretrained=False, progress=True, device='cpu', **kwargs): 154 | r"""Densenet-169 model from 155 | `"Densely Connected Convolutional Networks" `_ 156 | 157 | Args: 158 | pretrained (bool): If True, returns a model pre-trained on ImageNet 159 | progress (bool): If True, displays a progress bar of the download to stderr 160 | """ 161 | return _densenet('densenet169', 32, (6, 12, 32, 32), 64, pretrained, progress, device, 162 | **kwargs) 163 | 164 | 165 | def densenet201(pretrained=False, progress=True, device='cpu', **kwargs): 166 | r"""Densenet-201 model from 167 | `"Densely Connected Convolutional Networks" `_ 168 | 169 | Args: 170 | pretrained (bool): If True, returns a model pre-trained on ImageNet 171 | progress (bool): If True, displays a progress bar of the download to stderr 172 | """ 173 | return _densenet('densenet201', 32, (6, 12, 48, 32), 64, pretrained, progress, device, 174 | **kwargs) 175 | -------------------------------------------------------------------------------- /dfme/cifar10_models/googlenet.py: -------------------------------------------------------------------------------- 1 | import warnings 2 | from collections import namedtuple 3 | import torch 4 | import torch.nn as nn 5 | import torch.nn.functional as F 6 | import os 7 | 8 | __all__ = ['GoogLeNet', 'googlenet'] 9 | 10 | 11 | _GoogLeNetOuputs = namedtuple('GoogLeNetOuputs', ['logits', 'aux_logits2', 'aux_logits1']) 12 | 13 | 14 | def googlenet(pretrained=False, progress=True, device='cpu', **kwargs): 15 | r"""GoogLeNet (Inception v1) model architecture from 16 | `"Going Deeper with Convolutions" `_. 17 | 18 | Args: 19 | pretrained (bool): If True, returns a model pre-trained on ImageNet 20 | progress (bool): If True, displays a progress bar of the download to stderr 21 | aux_logits (bool): If True, adds two auxiliary branches that can improve training. 22 | Default: *False* when pretrained is True otherwise *True* 23 | transform_input (bool): If True, preprocesses the input according to the method with which it 24 | was trained on ImageNet. Default: *False* 25 | """ 26 | model = GoogLeNet() 27 | if pretrained: 28 | script_dir = os.path.dirname(__file__) 29 | state_dict = torch.load(script_dir + '/state_dicts/googlenet.pt', map_location=device) 30 | model.load_state_dict(state_dict) 31 | return model 32 | 33 | 34 | class GoogLeNet(nn.Module): 35 | 36 | ## CIFAR10: aux_logits True->False 37 | def __init__(self, num_classes=10, aux_logits=False, transform_input=False): 38 | super(GoogLeNet, self).__init__() 39 | self.aux_logits = aux_logits 40 | self.transform_input = transform_input 41 | 42 | ## CIFAR10: out_channels 64->192, kernel_size 7->3, stride 2->1, padding 3->1 43 | self.conv1 = BasicConv2d(3, 192, kernel_size=3, stride=1, padding=1) 44 | # self.maxpool1 = nn.MaxPool2d(3, stride=2, ceil_mode=True) 45 | # self.conv2 = BasicConv2d(64, 64, kernel_size=1) 46 | # self.conv3 = BasicConv2d(64, 192, kernel_size=3, padding=1) 47 | # self.maxpool2 = nn.MaxPool2d(3, stride=2, ceil_mode=True) 48 | ## END 49 | 50 | self.inception3a = Inception(192, 64, 96, 128, 16, 32, 32) 51 | self.inception3b = Inception(256, 128, 128, 192, 32, 96, 64) 52 | 53 | ## CIFAR10: padding 0->1, ciel_model True->False 54 | self.maxpool3 = nn.MaxPool2d(3, stride=2, padding=1, ceil_mode=False) 55 | ## END 56 | 57 | self.inception4a = Inception(480, 192, 96, 208, 16, 48, 64) 58 | self.inception4b = Inception(512, 160, 112, 224, 24, 64, 64) 59 | self.inception4c = Inception(512, 128, 128, 256, 24, 64, 64) 60 | self.inception4d = Inception(512, 112, 144, 288, 32, 64, 64) 61 | self.inception4e = Inception(528, 256, 160, 320, 32, 128, 128) 62 | 63 | ## CIFAR10: kernel_size 2->3, padding 0->1, ciel_model True->False 64 | self.maxpool4 = nn.MaxPool2d(3, stride=2, padding=1, ceil_mode=False) 65 | ## END 66 | 67 | self.inception5a = Inception(832, 256, 160, 320, 32, 128, 128) 68 | self.inception5b = Inception(832, 384, 192, 384, 48, 128, 128) 69 | 70 | if aux_logits: 71 | self.aux1 = InceptionAux(512, num_classes) 72 | self.aux2 = InceptionAux(528, num_classes) 73 | 74 | self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) 75 | self.dropout = nn.Dropout(0.2) 76 | self.fc = nn.Linear(1024, num_classes) 77 | 78 | # if init_weights: 79 | # self._initialize_weights() 80 | 81 | # def _initialize_weights(self): 82 | # for m in self.modules(): 83 | # if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear): 84 | # import scipy.stats as stats 85 | # X = stats.truncnorm(-2, 2, scale=0.01) 86 | # values = torch.as_tensor(X.rvs(m.weight.numel()), dtype=m.weight.dtype) 87 | # values = values.view(m.weight.size()) 88 | # with torch.no_grad(): 89 | # m.weight.copy_(values) 90 | # elif isinstance(m, nn.BatchNorm2d): 91 | # nn.init.constant_(m.weight, 1) 92 | # nn.init.constant_(m.bias, 0) 93 | 94 | def forward(self, x): 95 | if self.transform_input: 96 | x_ch0 = torch.unsqueeze(x[:, 0], 1) * (0.229 / 0.5) + (0.485 - 0.5) / 0.5 97 | x_ch1 = torch.unsqueeze(x[:, 1], 1) * (0.224 / 0.5) + (0.456 - 0.5) / 0.5 98 | x_ch2 = torch.unsqueeze(x[:, 2], 1) * (0.225 / 0.5) + (0.406 - 0.5) / 0.5 99 | x = torch.cat((x_ch0, x_ch1, x_ch2), 1) 100 | 101 | # N x 3 x 224 x 224 102 | x = self.conv1(x) 103 | 104 | ## CIFAR10 105 | # N x 64 x 112 x 112 106 | # x = self.maxpool1(x) 107 | # N x 64 x 56 x 56 108 | # x = self.conv2(x) 109 | # N x 64 x 56 x 56 110 | # x = self.conv3(x) 111 | # N x 192 x 56 x 56 112 | # x = self.maxpool2(x) 113 | ## END 114 | 115 | # N x 192 x 28 x 28 116 | x = self.inception3a(x) 117 | # N x 256 x 28 x 28 118 | x = self.inception3b(x) 119 | # N x 480 x 28 x 28 120 | x = self.maxpool3(x) 121 | # N x 480 x 14 x 14 122 | x = self.inception4a(x) 123 | # N x 512 x 14 x 14 124 | if self.training and self.aux_logits: 125 | aux1 = self.aux1(x) 126 | 127 | x = self.inception4b(x) 128 | # N x 512 x 14 x 14 129 | x = self.inception4c(x) 130 | # N x 512 x 14 x 14 131 | x = self.inception4d(x) 132 | # N x 528 x 14 x 14 133 | if self.training and self.aux_logits: 134 | aux2 = self.aux2(x) 135 | 136 | x = self.inception4e(x) 137 | # N x 832 x 14 x 14 138 | x = self.maxpool4(x) 139 | # N x 832 x 7 x 7 140 | x = self.inception5a(x) 141 | # N x 832 x 7 x 7 142 | x = self.inception5b(x) 143 | # N x 1024 x 7 x 7 144 | 145 | x = self.avgpool(x) 146 | # N x 1024 x 1 x 1 147 | x = x.view(x.size(0), -1) 148 | # N x 1024 149 | x = self.dropout(x) 150 | x = self.fc(x) 151 | # N x 1000 (num_classes) 152 | if self.training and self.aux_logits: 153 | return _GoogLeNetOuputs(x, aux2, aux1) 154 | return x 155 | 156 | 157 | class Inception(nn.Module): 158 | 159 | def __init__(self, in_channels, ch1x1, ch3x3red, ch3x3, ch5x5red, ch5x5, pool_proj): 160 | super(Inception, self).__init__() 161 | 162 | self.branch1 = BasicConv2d(in_channels, ch1x1, kernel_size=1) 163 | 164 | self.branch2 = nn.Sequential( 165 | BasicConv2d(in_channels, ch3x3red, kernel_size=1), 166 | BasicConv2d(ch3x3red, ch3x3, kernel_size=3, padding=1) 167 | ) 168 | 169 | self.branch3 = nn.Sequential( 170 | BasicConv2d(in_channels, ch5x5red, kernel_size=1), 171 | BasicConv2d(ch5x5red, ch5x5, kernel_size=3, padding=1) 172 | ) 173 | 174 | self.branch4 = nn.Sequential( 175 | nn.MaxPool2d(kernel_size=3, stride=1, padding=1, ceil_mode=True), 176 | BasicConv2d(in_channels, pool_proj, kernel_size=1) 177 | ) 178 | 179 | def forward(self, x): 180 | branch1 = self.branch1(x) 181 | branch2 = self.branch2(x) 182 | branch3 = self.branch3(x) 183 | branch4 = self.branch4(x) 184 | 185 | outputs = [branch1, branch2, branch3, branch4] 186 | return torch.cat(outputs, 1) 187 | 188 | 189 | class InceptionAux(nn.Module): 190 | 191 | def __init__(self, in_channels, num_classes): 192 | super(InceptionAux, self).__init__() 193 | self.conv = BasicConv2d(in_channels, 128, kernel_size=1) 194 | 195 | self.fc1 = nn.Linear(2048, 1024) 196 | self.fc2 = nn.Linear(1024, num_classes) 197 | 198 | def forward(self, x): 199 | # aux1: N x 512 x 14 x 14, aux2: N x 528 x 14 x 14 200 | x = F.adaptive_avg_pool2d(x, (4, 4)) 201 | # aux1: N x 512 x 4 x 4, aux2: N x 528 x 4 x 4 202 | x = self.conv(x) 203 | # N x 128 x 4 x 4 204 | x = x.view(x.size(0), -1) 205 | # N x 2048 206 | x = F.relu(self.fc1(x), inplace=True) 207 | # N x 2048 208 | x = F.dropout(x, 0.7, training=self.training) 209 | # N x 2048 210 | x = self.fc2(x) 211 | # N x 1024 212 | 213 | return x 214 | 215 | 216 | class BasicConv2d(nn.Module): 217 | 218 | def __init__(self, in_channels, out_channels, **kwargs): 219 | super(BasicConv2d, self).__init__() 220 | self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs) 221 | self.bn = nn.BatchNorm2d(out_channels, eps=0.001) 222 | 223 | def forward(self, x): 224 | x = self.conv(x) 225 | x = self.bn(x) 226 | return F.relu(x, inplace=True) 227 | -------------------------------------------------------------------------------- /dfme/approximate_gradients.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | import scipy.linalg 6 | import matplotlib.pyplot as plt 7 | import network 8 | from tqdm import tqdm 9 | import torchvision.models as models 10 | from time import time 11 | 12 | # from cifar10_models import * 13 | 14 | 15 | def estimate_gradient_objective(args, victim_model, clone_model, x, epsilon = 1e-7, m = 5, verb=False, num_classes=10, device = "cpu", pre_x=False): 16 | # Sampling from unit sphere is the method 3 from this website: 17 | # http://extremelearning.com.au/how-to-generate-uniformly-random-points-on-n-spheres-and-n-balls/ 18 | #x = torch.Tensor(np.arange(2*1*7*7).reshape(-1, 1, 7, 7)) 19 | 20 | if pre_x and args.G_activation is None: 21 | raise ValueError(args.G_activation) 22 | 23 | clone_model.eval() 24 | victim_model.eval() 25 | with torch.no_grad(): 26 | # Sample unit noise vector 27 | N = x.size(0) 28 | C = x.size(1) 29 | S = x.size(2) 30 | dim = S**2 * C 31 | 32 | u = np.random.randn(N * m * dim).reshape(-1, m, dim) # generate random points from normal distribution 33 | 34 | d = np.sqrt(np.sum(u ** 2, axis = 2)).reshape(-1, m, 1) # map to a uniform distribution on a unit sphere 35 | u = torch.Tensor(u / d).view(-1, m, C, S, S) 36 | u = torch.cat((u, torch.zeros(N, 1, C, S, S)), dim = 1) # Shape N, m + 1, S^2 37 | 38 | 39 | 40 | u = u.view(-1, m + 1, C, S, S) 41 | 42 | evaluation_points = (x.view(-1, 1, C, S, S).cpu() + epsilon * u).view(-1, C, S, S) 43 | if pre_x: 44 | evaluation_points = args.G_activation(evaluation_points) # Apply args.G_activation function 45 | 46 | # Compute the approximation sequentially to allow large values of m 47 | pred_victim = [] 48 | pred_clone = [] 49 | max_number_points = 32*156 # Hardcoded value to split the large evaluation_points tensor to fit in GPU 50 | 51 | for i in (range(N * m // max_number_points + 1)): 52 | pts = evaluation_points[i * max_number_points: (i+1) * max_number_points] 53 | pts = pts.to(device) 54 | 55 | pred_victim_pts = victim_model(pts).detach() 56 | pred_clone_pts = clone_model(pts) 57 | 58 | pred_victim.append(pred_victim_pts) 59 | pred_clone.append(pred_clone_pts) 60 | 61 | 62 | 63 | pred_victim = torch.cat(pred_victim, dim=0).to(device) 64 | pred_clone = torch.cat(pred_clone, dim=0).to(device) 65 | 66 | u = u.to(device) 67 | 68 | if args.loss == "l1": 69 | loss_fn = F.l1_loss 70 | if args.no_logits: 71 | pred_victim = F.log_softmax(pred_victim, dim=1).detach() 72 | if args.logit_correction == 'min': 73 | pred_victim -= pred_victim.min(dim=1).values.view(-1, 1).detach() 74 | elif args.logit_correction == 'mean': 75 | pred_victim -= pred_victim.mean(dim=1).view(-1, 1).detach() 76 | 77 | 78 | elif args.loss == "kl": 79 | loss_fn = F.kl_div 80 | pred_clone = F.log_softmax(pred_clone, dim=1) 81 | pred_victim = F.softmax(pred_victim.detach(), dim=1) 82 | 83 | else: 84 | raise ValueError(args.loss) 85 | 86 | # Compute loss 87 | if args.loss == "kl": 88 | loss_values = - loss_fn(pred_clone, pred_victim, reduction='none').sum(dim = 1).view(-1, m + 1) 89 | else: 90 | loss_values = - loss_fn(pred_clone, pred_victim, reduction='none').mean(dim = 1).view(-1, m + 1) 91 | 92 | # Compute difference following each direction 93 | differences = loss_values[:, :-1] - loss_values[:, -1].view(-1, 1) 94 | differences = differences.view(-1, m, 1, 1, 1) 95 | 96 | # Formula for Forward Finite Differences 97 | gradient_estimates = 1 / epsilon * differences * u[:, :-1] 98 | if args.forward_differences: 99 | gradient_estimates *= dim 100 | 101 | if args.loss == "kl": 102 | gradient_estimates = gradient_estimates.mean(dim = 1).view(-1, C, S, S) 103 | else: 104 | gradient_estimates = gradient_estimates.mean(dim = 1).view(-1, C, S, S) / (num_classes * N) 105 | 106 | clone_model.train() 107 | loss_G = loss_values[:, -1].mean() 108 | return gradient_estimates.detach(), loss_G 109 | 110 | 111 | def compute_gradient(args, victim_model, clone_model, x, pre_x=False, device="cpu"): 112 | if pre_x and args.G_activation is None: 113 | raise ValueError(args.G_activation) 114 | 115 | clone_model.eval() 116 | N = x.size(0) 117 | x_copy = x.clone().detach().requires_grad_(True) 118 | x_ = x_copy.to(device) 119 | 120 | 121 | if pre_x: 122 | x_ = args.G_activation(x_) 123 | 124 | 125 | pred_victim = victim_model(x_) 126 | pred_clone = clone_model(x_) 127 | 128 | if args.loss == "l1": 129 | loss_fn = F.l1_loss 130 | if args.no_logits: 131 | pred_victim_no_logits = F.log_softmax(pred_victim, dim=1) 132 | if args.logit_correction == 'min': 133 | pred_victim = pred_victim_no_logits - pred_victim_no_logits.min(dim=1).values.view(-1, 1) 134 | elif args.logit_correction == 'mean': 135 | pred_victim = pred_victim_no_logits - pred_victim_no_logits.mean(dim=1).view(-1, 1) 136 | else: 137 | pred_victim = pred_victim_no_logits 138 | 139 | elif args.loss == "kl": 140 | loss_fn = F.kl_div 141 | pred_clone = F.log_softmax(pred_clone, dim=1) 142 | pred_victim = F.softmax(pred_victim, dim=1) 143 | 144 | else: 145 | raise ValueError(args.loss) 146 | 147 | 148 | loss_values = -loss_fn(pred_clone, pred_victim, reduction='mean') 149 | # print("True mean loss", loss_values) 150 | loss_values.backward() 151 | 152 | clone_model.train() 153 | 154 | return x_copy.grad, loss_values 155 | 156 | 157 | class Args(dict): 158 | def __init__(self, **args): 159 | for k,v in args.items(): 160 | self[k] = v 161 | 162 | 163 | 164 | def get_classifier(classifier, pretrained=True, resnet34_8x_file=None, num_classes=10): 165 | if classifier == "none": 166 | return NullTeacher(num_classes=num_classes) 167 | else: 168 | raise ValueError("Only Null Teacher should be used") 169 | if classifier == 'vgg11_bn': 170 | return vgg11_bn(pretrained=pretrained, num_classes=num_classes) 171 | elif classifier == 'vgg13_bn': 172 | return vgg13_bn(pretrained=pretrained, num_classes=num_classes) 173 | elif classifier == 'vgg16_bn': 174 | return vgg16_bn(pretrained=pretrained, num_classes=num_classes) 175 | elif classifier == 'vgg19_bn': 176 | return vgg19_bn(pretrained=pretrained, num_classes=num_classes) 177 | if classifier == 'vgg11': 178 | return models.vgg11(pretrained=pretrained, num_classes=num_classes) 179 | elif classifier == 'vgg13': 180 | return models.vgg13(pretrained=pretrained, num_classes=num_classes) 181 | elif classifier == 'vgg16': 182 | return models.vgg16(pretrained=pretrained, num_classes=num_classes) 183 | elif classifier == 'vgg19': 184 | return models.vgg19(pretrained=pretrained, num_classes=num_classes) 185 | elif classifier == 'resnet18': 186 | return resnet18(pretrained=pretrained, num_classes=num_classes) 187 | elif classifier == 'resnet34': 188 | return resnet34(pretrained=pretrained, num_classes=num_classes) 189 | elif classifier == 'resnet50': 190 | return resnet50(pretrained=pretrained, num_classes=num_classes) 191 | elif classifier == 'densenet121': 192 | return densenet121(pretrained=pretrained, num_classes=num_classes) 193 | elif classifier == 'densenet161': 194 | return densenet161(pretrained=pretrained, num_classes=num_classes) 195 | elif classifier == 'densenet169': 196 | return densenet169(pretrained=pretrained, num_classes=num_classes) 197 | elif classifier == 'mobilenet_v2': 198 | return mobilenet_v2(pretrained=pretrained, num_classes=num_classes) 199 | elif classifier == 'googlenet': 200 | return googlenet(pretrained=pretrained, num_classes=num_classes) 201 | elif classifier == 'inception_v3': 202 | return inception_v3(pretrained=pretrained, num_classes=num_classes) 203 | elif classifier == "resnet34_8x": 204 | net = network.resnet_8x.ResNet34_8x(num_classes=num_classes) 205 | if pretrained: 206 | if resnet34_8x_file is not None: 207 | net.load_state_dict( torch.load( resnet34_8x_file) ) 208 | else: 209 | raise ValueError("Cannot load pretrained resnet34_8x from here") 210 | 211 | return net 212 | 213 | else: 214 | raise NameError(f'Please enter a valid classifier {classifier}') 215 | 216 | classifiers = [ 217 | "resnet34_8x", # Default DFAD 218 | # "vgg11", 219 | # "vgg13", 220 | # "vgg16", 221 | # "vgg19", 222 | "vgg11_bn", 223 | "vgg13_bn", 224 | "vgg16_bn", 225 | "vgg19_bn", 226 | "resnet18", 227 | "resnet34", 228 | "resnet50", 229 | "densenet121", 230 | "densenet161", 231 | "densenet169", 232 | "mobilenet_v2", 233 | "googlenet", 234 | "inception_v3", 235 | ] 236 | 237 | -------------------------------------------------------------------------------- /dfme/cifar10_models/resnet.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import os 4 | 5 | __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 6 | 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d'] 7 | 8 | def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): 9 | """3x3 convolution with padding""" 10 | return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, 11 | padding=dilation, groups=groups, bias=False, dilation=dilation) 12 | 13 | 14 | def conv1x1(in_planes, out_planes, stride=1): 15 | """1x1 convolution""" 16 | return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) 17 | 18 | 19 | class BasicBlock(nn.Module): 20 | expansion = 1 21 | 22 | def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, 23 | base_width=64, dilation=1, norm_layer=None): 24 | super(BasicBlock, self).__init__() 25 | if norm_layer is None: 26 | norm_layer = nn.BatchNorm2d 27 | if groups != 1 or base_width != 64: 28 | raise ValueError('BasicBlock only supports groups=1 and base_width=64') 29 | if dilation > 1: 30 | raise NotImplementedError("Dilation > 1 not supported in BasicBlock") 31 | # Both self.conv1 and self.downsample layers downsample the input when stride != 1 32 | self.conv1 = conv3x3(inplanes, planes, stride) 33 | self.bn1 = norm_layer(planes) 34 | self.relu = nn.ReLU(inplace=True) 35 | self.conv2 = conv3x3(planes, planes) 36 | self.bn2 = norm_layer(planes) 37 | self.downsample = downsample 38 | self.stride = stride 39 | 40 | def forward(self, x): 41 | identity = x 42 | 43 | out = self.conv1(x) 44 | out = self.bn1(out) 45 | out = self.relu(out) 46 | 47 | out = self.conv2(out) 48 | out = self.bn2(out) 49 | 50 | if self.downsample is not None: 51 | identity = self.downsample(x) 52 | 53 | out += identity 54 | out = self.relu(out) 55 | 56 | return out 57 | 58 | 59 | class Bottleneck(nn.Module): 60 | expansion = 4 61 | 62 | def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, 63 | base_width=64, dilation=1, norm_layer=None): 64 | super(Bottleneck, self).__init__() 65 | if norm_layer is None: 66 | norm_layer = nn.BatchNorm2d 67 | width = int(planes * (base_width / 64.)) * groups 68 | # Both self.conv2 and self.downsample layers downsample the input when stride != 1 69 | self.conv1 = conv1x1(inplanes, width) 70 | self.bn1 = norm_layer(width) 71 | self.conv2 = conv3x3(width, width, stride, groups, dilation) 72 | self.bn2 = norm_layer(width) 73 | self.conv3 = conv1x1(width, planes * self.expansion) 74 | self.bn3 = norm_layer(planes * self.expansion) 75 | self.relu = nn.ReLU(inplace=True) 76 | self.downsample = downsample 77 | self.stride = stride 78 | 79 | def forward(self, x): 80 | identity = x 81 | 82 | out = self.conv1(x) 83 | out = self.bn1(out) 84 | out = self.relu(out) 85 | 86 | out = self.conv2(out) 87 | out = self.bn2(out) 88 | out = self.relu(out) 89 | 90 | out = self.conv3(out) 91 | out = self.bn3(out) 92 | 93 | if self.downsample is not None: 94 | identity = self.downsample(x) 95 | 96 | out += identity 97 | out = self.relu(out) 98 | 99 | return out 100 | 101 | 102 | class ResNet(nn.Module): 103 | 104 | def __init__(self, block, layers, num_classes=10, zero_init_residual=False, 105 | groups=1, width_per_group=64, replace_stride_with_dilation=None, 106 | norm_layer=None): 107 | super(ResNet, self).__init__() 108 | if norm_layer is None: 109 | norm_layer = nn.BatchNorm2d 110 | self._norm_layer = norm_layer 111 | 112 | self.inplanes = 64 113 | self.dilation = 1 114 | if replace_stride_with_dilation is None: 115 | # each element in the tuple indicates if we should replace 116 | # the 2x2 stride with a dilated convolution instead 117 | replace_stride_with_dilation = [False, False, False] 118 | if len(replace_stride_with_dilation) != 3: 119 | raise ValueError("replace_stride_with_dilation should be None " 120 | "or a 3-element tuple, got {}".format(replace_stride_with_dilation)) 121 | self.groups = groups 122 | self.base_width = width_per_group 123 | 124 | ## CIFAR10: kernel_size 7 -> 3, stride 2 -> 1, padding 3->1 125 | self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=3, stride=1, padding=1, bias=False) 126 | ## END 127 | 128 | self.bn1 = norm_layer(self.inplanes) 129 | self.relu = nn.ReLU(inplace=True) 130 | self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) 131 | self.layer1 = self._make_layer(block, 64, layers[0]) 132 | self.layer2 = self._make_layer(block, 128, layers[1], stride=2, 133 | dilate=replace_stride_with_dilation[0]) 134 | self.layer3 = self._make_layer(block, 256, layers[2], stride=2, 135 | dilate=replace_stride_with_dilation[1]) 136 | self.layer4 = self._make_layer(block, 512, layers[3], stride=2, 137 | dilate=replace_stride_with_dilation[2]) 138 | self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) 139 | self.fc = nn.Linear(512 * block.expansion, num_classes) 140 | 141 | for m in self.modules(): 142 | if isinstance(m, nn.Conv2d): 143 | nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 144 | elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): 145 | nn.init.constant_(m.weight, 1) 146 | nn.init.constant_(m.bias, 0) 147 | 148 | # Zero-initialize the last BN in each residual branch, 149 | # so that the residual branch starts with zeros, and each residual block behaves like an identity. 150 | # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 151 | if zero_init_residual: 152 | for m in self.modules(): 153 | if isinstance(m, Bottleneck): 154 | nn.init.constant_(m.bn3.weight, 0) 155 | elif isinstance(m, BasicBlock): 156 | nn.init.constant_(m.bn2.weight, 0) 157 | 158 | def _make_layer(self, block, planes, blocks, stride=1, dilate=False): 159 | norm_layer = self._norm_layer 160 | downsample = None 161 | previous_dilation = self.dilation 162 | if dilate: 163 | self.dilation *= stride 164 | stride = 1 165 | if stride != 1 or self.inplanes != planes * block.expansion: 166 | downsample = nn.Sequential( 167 | conv1x1(self.inplanes, planes * block.expansion, stride), 168 | norm_layer(planes * block.expansion), 169 | ) 170 | 171 | layers = [] 172 | layers.append(block(self.inplanes, planes, stride, downsample, self.groups, 173 | self.base_width, previous_dilation, norm_layer)) 174 | self.inplanes = planes * block.expansion 175 | for _ in range(1, blocks): 176 | layers.append(block(self.inplanes, planes, groups=self.groups, 177 | base_width=self.base_width, dilation=self.dilation, 178 | norm_layer=norm_layer)) 179 | 180 | return nn.Sequential(*layers) 181 | 182 | def forward(self, x): 183 | x = self.conv1(x) 184 | x = self.bn1(x) 185 | x = self.relu(x) 186 | x = self.maxpool(x) 187 | 188 | x = self.layer1(x) 189 | x = self.layer2(x) 190 | x = self.layer3(x) 191 | x = self.layer4(x) 192 | 193 | x = self.avgpool(x) 194 | x = x.reshape(x.size(0), -1) 195 | x = self.fc(x) 196 | 197 | return x 198 | 199 | 200 | def _resnet(arch, block, layers, pretrained, progress, device, **kwargs): 201 | model = ResNet(block, layers, **kwargs) 202 | if pretrained: 203 | script_dir = os.path.dirname(__file__) 204 | state_dict = torch.load(script_dir + '/state_dicts/'+arch+'.pt', map_location=device) 205 | model.load_state_dict(state_dict) 206 | return model 207 | 208 | 209 | def resnet18(pretrained=False, progress=True, device='cpu', **kwargs): 210 | """Constructs a ResNet-18 model. 211 | 212 | Args: 213 | pretrained (bool): If True, returns a model pre-trained on ImageNet 214 | progress (bool): If True, displays a progress bar of the download to stderr 215 | """ 216 | return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress, device, 217 | **kwargs) 218 | 219 | 220 | def resnet34(pretrained=False, progress=True, device='cpu', **kwargs): 221 | """Constructs a ResNet-34 model. 222 | 223 | Args: 224 | pretrained (bool): If True, returns a model pre-trained on ImageNet 225 | progress (bool): If True, displays a progress bar of the download to stderr 226 | """ 227 | return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress, device, 228 | **kwargs) 229 | 230 | 231 | def resnet50(pretrained=False, progress=True, device='cpu', **kwargs): 232 | """Constructs a ResNet-50 model. 233 | 234 | Args: 235 | pretrained (bool): If True, returns a model pre-trained on ImageNet 236 | progress (bool): If True, displays a progress bar of the download to stderr 237 | """ 238 | return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress, device, 239 | **kwargs) 240 | 241 | 242 | def resnet101(pretrained=False, progress=True, device='cpu', **kwargs): 243 | """Constructs a ResNet-101 model. 244 | 245 | Args: 246 | pretrained (bool): If True, returns a model pre-trained on ImageNet 247 | progress (bool): If True, displays a progress bar of the download to stderr 248 | """ 249 | return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress, device, 250 | **kwargs) 251 | 252 | 253 | def resnet152(pretrained=False, progress=True, device='cpu', **kwargs): 254 | """Constructs a ResNet-152 model. 255 | 256 | Args: 257 | pretrained (bool): If True, returns a model pre-trained on ImageNet 258 | progress (bool): If True, displays a progress bar of the download to stderr 259 | """ 260 | return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress, device, 261 | **kwargs) 262 | 263 | 264 | def resnext50_32x4d(pretrained=False, progress=True, device='cpu', **kwargs): 265 | """Constructs a ResNeXt-50 32x4d model. 266 | 267 | Args: 268 | pretrained (bool): If True, returns a model pre-trained on ImageNet 269 | progress (bool): If True, displays a progress bar of the download to stderr 270 | """ 271 | kwargs['groups'] = 32 272 | kwargs['width_per_group'] = 4 273 | return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3], 274 | pretrained, progress, device, **kwargs) 275 | 276 | 277 | def resnext101_32x8d(pretrained=False, progress=True, device='cpu', **kwargs): 278 | """Constructs a ResNeXt-101 32x8d model. 279 | 280 | Args: 281 | pretrained (bool): If True, returns a model pre-trained on ImageNet 282 | progress (bool): If True, displays a progress bar of the download to stderr 283 | """ 284 | kwargs['groups'] = 32 285 | kwargs['width_per_group'] = 8 286 | return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3], 287 | pretrained, progress, device, **kwargs) 288 | -------------------------------------------------------------------------------- /dfme/cifar10_models/inception.py: -------------------------------------------------------------------------------- 1 | from collections import namedtuple 2 | import torch 3 | import torch.nn as nn 4 | import torch.nn.functional as F 5 | import os 6 | 7 | __all__ = ['Inception3', 'inception_v3'] 8 | 9 | 10 | _InceptionOuputs = namedtuple('InceptionOuputs', ['logits', 'aux_logits']) 11 | 12 | 13 | def inception_v3(pretrained=False, progress=True, device='cpu', **kwargs): 14 | r"""Inception v3 model architecture from 15 | `"Rethinking the Inception Architecture for Computer Vision" `_. 16 | 17 | .. note:: 18 | **Important**: In contrast to the other models the inception_v3 expects tensors with a size of 19 | N x 3 x 299 x 299, so ensure your images are sized accordingly. 20 | 21 | Args: 22 | pretrained (bool): If True, returns a model pre-trained on ImageNet 23 | progress (bool): If True, displays a progress bar of the download to stderr 24 | aux_logits (bool): If True, add an auxiliary branch that can improve training. 25 | Default: *True* 26 | transform_input (bool): If True, preprocesses the input according to the method with which it 27 | was trained on ImageNet. Default: *False* 28 | """ 29 | model = Inception3() 30 | if pretrained: 31 | script_dir = os.path.dirname(__file__) 32 | state_dict = torch.load(script_dir + '/state_dicts/inception_v3.pt', map_location=device) 33 | model.load_state_dict(state_dict) 34 | return model 35 | 36 | class Inception3(nn.Module): 37 | ## CIFAR10: aux_logits True->False 38 | def __init__(self, num_classes=10, aux_logits=False, transform_input=False): 39 | super(Inception3, self).__init__() 40 | self.aux_logits = aux_logits 41 | self.transform_input = transform_input 42 | 43 | ## CIFAR10: stride 2->1, padding 0 -> 1 44 | self.Conv2d_1a_3x3 = BasicConv2d(3, 192, kernel_size=3, stride=1, padding=1) 45 | # self.Conv2d_2a_3x3 = BasicConv2d(32, 32, kernel_size=3) 46 | # self.Conv2d_2b_3x3 = BasicConv2d(32, 64, kernel_size=3, padding=1) 47 | # self.Conv2d_3b_1x1 = BasicConv2d(64, 80, kernel_size=1) 48 | # self.Conv2d_4a_3x3 = BasicConv2d(80, 192, kernel_size=3) 49 | self.Mixed_5b = InceptionA(192, pool_features=32) 50 | self.Mixed_5c = InceptionA(256, pool_features=64) 51 | self.Mixed_5d = InceptionA(288, pool_features=64) 52 | self.Mixed_6a = InceptionB(288) 53 | self.Mixed_6b = InceptionC(768, channels_7x7=128) 54 | self.Mixed_6c = InceptionC(768, channels_7x7=160) 55 | self.Mixed_6d = InceptionC(768, channels_7x7=160) 56 | self.Mixed_6e = InceptionC(768, channels_7x7=192) 57 | if aux_logits: 58 | self.AuxLogits = InceptionAux(768, num_classes) 59 | self.Mixed_7a = InceptionD(768) 60 | self.Mixed_7b = InceptionE(1280) 61 | self.Mixed_7c = InceptionE(2048) 62 | self.fc = nn.Linear(2048, num_classes) 63 | 64 | # for m in self.modules(): 65 | # if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear): 66 | # import scipy.stats as stats 67 | # stddev = m.stddev if hasattr(m, 'stddev') else 0.1 68 | # X = stats.truncnorm(-2, 2, scale=stddev) 69 | # values = torch.as_tensor(X.rvs(m.weight.numel()), dtype=m.weight.dtype) 70 | # values = values.view(m.weight.size()) 71 | # with torch.no_grad(): 72 | # m.weight.copy_(values) 73 | # elif isinstance(m, nn.BatchNorm2d): 74 | # nn.init.constant_(m.weight, 1) 75 | # nn.init.constant_(m.bias, 0) 76 | 77 | def forward(self, x): 78 | if self.transform_input: 79 | x_ch0 = torch.unsqueeze(x[:, 0], 1) * (0.229 / 0.5) + (0.485 - 0.5) / 0.5 80 | x_ch1 = torch.unsqueeze(x[:, 1], 1) * (0.224 / 0.5) + (0.456 - 0.5) / 0.5 81 | x_ch2 = torch.unsqueeze(x[:, 2], 1) * (0.225 / 0.5) + (0.406 - 0.5) / 0.5 82 | x = torch.cat((x_ch0, x_ch1, x_ch2), 1) 83 | # N x 3 x 299 x 299 84 | x = self.Conv2d_1a_3x3(x) 85 | 86 | ## CIFAR10 87 | # N x 32 x 149 x 149 88 | # x = self.Conv2d_2a_3x3(x) 89 | # N x 32 x 147 x 147 90 | # x = self.Conv2d_2b_3x3(x) 91 | # N x 64 x 147 x 147 92 | # x = F.max_pool2d(x, kernel_size=3, stride=2) 93 | # N x 64 x 73 x 73 94 | # x = self.Conv2d_3b_1x1(x) 95 | # N x 80 x 73 x 73 96 | # x = self.Conv2d_4a_3x3(x) 97 | # N x 192 x 71 x 71 98 | # x = F.max_pool2d(x, kernel_size=3, stride=2) 99 | # N x 192 x 35 x 35 100 | x = self.Mixed_5b(x) 101 | # N x 256 x 35 x 35 102 | x = self.Mixed_5c(x) 103 | # N x 288 x 35 x 35 104 | x = self.Mixed_5d(x) 105 | # N x 288 x 35 x 35 106 | x = self.Mixed_6a(x) 107 | # N x 768 x 17 x 17 108 | x = self.Mixed_6b(x) 109 | # N x 768 x 17 x 17 110 | x = self.Mixed_6c(x) 111 | # N x 768 x 17 x 17 112 | x = self.Mixed_6d(x) 113 | # N x 768 x 17 x 17 114 | x = self.Mixed_6e(x) 115 | # N x 768 x 17 x 17 116 | if self.training and self.aux_logits: 117 | aux = self.AuxLogits(x) 118 | # N x 768 x 17 x 17 119 | x = self.Mixed_7a(x) 120 | # N x 1280 x 8 x 8 121 | x = self.Mixed_7b(x) 122 | # N x 2048 x 8 x 8 123 | x = self.Mixed_7c(x) 124 | # N x 2048 x 8 x 8 125 | # Adaptive average pooling 126 | x = F.adaptive_avg_pool2d(x, (1, 1)) 127 | # N x 2048 x 1 x 1 128 | x = F.dropout(x, training=self.training) 129 | # N x 2048 x 1 x 1 130 | x = x.view(x.size(0), -1) 131 | # N x 2048 132 | x = self.fc(x) 133 | # N x 1000 (num_classes) 134 | if self.training and self.aux_logits: 135 | return _InceptionOuputs(x, aux) 136 | return x 137 | 138 | 139 | class InceptionA(nn.Module): 140 | 141 | def __init__(self, in_channels, pool_features): 142 | super(InceptionA, self).__init__() 143 | self.branch1x1 = BasicConv2d(in_channels, 64, kernel_size=1) 144 | 145 | self.branch5x5_1 = BasicConv2d(in_channels, 48, kernel_size=1) 146 | self.branch5x5_2 = BasicConv2d(48, 64, kernel_size=5, padding=2) 147 | 148 | self.branch3x3dbl_1 = BasicConv2d(in_channels, 64, kernel_size=1) 149 | self.branch3x3dbl_2 = BasicConv2d(64, 96, kernel_size=3, padding=1) 150 | self.branch3x3dbl_3 = BasicConv2d(96, 96, kernel_size=3, padding=1) 151 | 152 | self.branch_pool = BasicConv2d(in_channels, pool_features, kernel_size=1) 153 | 154 | def forward(self, x): 155 | branch1x1 = self.branch1x1(x) 156 | 157 | branch5x5 = self.branch5x5_1(x) 158 | branch5x5 = self.branch5x5_2(branch5x5) 159 | 160 | branch3x3dbl = self.branch3x3dbl_1(x) 161 | branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) 162 | branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl) 163 | 164 | branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1) 165 | branch_pool = self.branch_pool(branch_pool) 166 | 167 | outputs = [branch1x1, branch5x5, branch3x3dbl, branch_pool] 168 | return torch.cat(outputs, 1) 169 | 170 | 171 | class InceptionB(nn.Module): 172 | 173 | def __init__(self, in_channels): 174 | super(InceptionB, self).__init__() 175 | self.branch3x3 = BasicConv2d(in_channels, 384, kernel_size=3, stride=2) 176 | 177 | self.branch3x3dbl_1 = BasicConv2d(in_channels, 64, kernel_size=1) 178 | self.branch3x3dbl_2 = BasicConv2d(64, 96, kernel_size=3, padding=1) 179 | self.branch3x3dbl_3 = BasicConv2d(96, 96, kernel_size=3, stride=2) 180 | 181 | def forward(self, x): 182 | branch3x3 = self.branch3x3(x) 183 | 184 | branch3x3dbl = self.branch3x3dbl_1(x) 185 | branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) 186 | branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl) 187 | 188 | branch_pool = F.max_pool2d(x, kernel_size=3, stride=2) 189 | 190 | outputs = [branch3x3, branch3x3dbl, branch_pool] 191 | return torch.cat(outputs, 1) 192 | 193 | 194 | class InceptionC(nn.Module): 195 | 196 | def __init__(self, in_channels, channels_7x7): 197 | super(InceptionC, self).__init__() 198 | self.branch1x1 = BasicConv2d(in_channels, 192, kernel_size=1) 199 | 200 | c7 = channels_7x7 201 | self.branch7x7_1 = BasicConv2d(in_channels, c7, kernel_size=1) 202 | self.branch7x7_2 = BasicConv2d(c7, c7, kernel_size=(1, 7), padding=(0, 3)) 203 | self.branch7x7_3 = BasicConv2d(c7, 192, kernel_size=(7, 1), padding=(3, 0)) 204 | 205 | self.branch7x7dbl_1 = BasicConv2d(in_channels, c7, kernel_size=1) 206 | self.branch7x7dbl_2 = BasicConv2d(c7, c7, kernel_size=(7, 1), padding=(3, 0)) 207 | self.branch7x7dbl_3 = BasicConv2d(c7, c7, kernel_size=(1, 7), padding=(0, 3)) 208 | self.branch7x7dbl_4 = BasicConv2d(c7, c7, kernel_size=(7, 1), padding=(3, 0)) 209 | self.branch7x7dbl_5 = BasicConv2d(c7, 192, kernel_size=(1, 7), padding=(0, 3)) 210 | 211 | self.branch_pool = BasicConv2d(in_channels, 192, kernel_size=1) 212 | 213 | def forward(self, x): 214 | branch1x1 = self.branch1x1(x) 215 | 216 | branch7x7 = self.branch7x7_1(x) 217 | branch7x7 = self.branch7x7_2(branch7x7) 218 | branch7x7 = self.branch7x7_3(branch7x7) 219 | 220 | branch7x7dbl = self.branch7x7dbl_1(x) 221 | branch7x7dbl = self.branch7x7dbl_2(branch7x7dbl) 222 | branch7x7dbl = self.branch7x7dbl_3(branch7x7dbl) 223 | branch7x7dbl = self.branch7x7dbl_4(branch7x7dbl) 224 | branch7x7dbl = self.branch7x7dbl_5(branch7x7dbl) 225 | 226 | branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1) 227 | branch_pool = self.branch_pool(branch_pool) 228 | 229 | outputs = [branch1x1, branch7x7, branch7x7dbl, branch_pool] 230 | return torch.cat(outputs, 1) 231 | 232 | 233 | class InceptionD(nn.Module): 234 | 235 | def __init__(self, in_channels): 236 | super(InceptionD, self).__init__() 237 | self.branch3x3_1 = BasicConv2d(in_channels, 192, kernel_size=1) 238 | self.branch3x3_2 = BasicConv2d(192, 320, kernel_size=3, stride=2) 239 | 240 | self.branch7x7x3_1 = BasicConv2d(in_channels, 192, kernel_size=1) 241 | self.branch7x7x3_2 = BasicConv2d(192, 192, kernel_size=(1, 7), padding=(0, 3)) 242 | self.branch7x7x3_3 = BasicConv2d(192, 192, kernel_size=(7, 1), padding=(3, 0)) 243 | self.branch7x7x3_4 = BasicConv2d(192, 192, kernel_size=3, stride=2) 244 | 245 | def forward(self, x): 246 | branch3x3 = self.branch3x3_1(x) 247 | branch3x3 = self.branch3x3_2(branch3x3) 248 | 249 | branch7x7x3 = self.branch7x7x3_1(x) 250 | branch7x7x3 = self.branch7x7x3_2(branch7x7x3) 251 | branch7x7x3 = self.branch7x7x3_3(branch7x7x3) 252 | branch7x7x3 = self.branch7x7x3_4(branch7x7x3) 253 | 254 | branch_pool = F.max_pool2d(x, kernel_size=3, stride=2) 255 | outputs = [branch3x3, branch7x7x3, branch_pool] 256 | return torch.cat(outputs, 1) 257 | 258 | 259 | class InceptionE(nn.Module): 260 | 261 | def __init__(self, in_channels): 262 | super(InceptionE, self).__init__() 263 | self.branch1x1 = BasicConv2d(in_channels, 320, kernel_size=1) 264 | 265 | self.branch3x3_1 = BasicConv2d(in_channels, 384, kernel_size=1) 266 | self.branch3x3_2a = BasicConv2d(384, 384, kernel_size=(1, 3), padding=(0, 1)) 267 | self.branch3x3_2b = BasicConv2d(384, 384, kernel_size=(3, 1), padding=(1, 0)) 268 | 269 | self.branch3x3dbl_1 = BasicConv2d(in_channels, 448, kernel_size=1) 270 | self.branch3x3dbl_2 = BasicConv2d(448, 384, kernel_size=3, padding=1) 271 | self.branch3x3dbl_3a = BasicConv2d(384, 384, kernel_size=(1, 3), padding=(0, 1)) 272 | self.branch3x3dbl_3b = BasicConv2d(384, 384, kernel_size=(3, 1), padding=(1, 0)) 273 | 274 | self.branch_pool = BasicConv2d(in_channels, 192, kernel_size=1) 275 | 276 | def forward(self, x): 277 | branch1x1 = self.branch1x1(x) 278 | 279 | branch3x3 = self.branch3x3_1(x) 280 | branch3x3 = [ 281 | self.branch3x3_2a(branch3x3), 282 | self.branch3x3_2b(branch3x3), 283 | ] 284 | branch3x3 = torch.cat(branch3x3, 1) 285 | 286 | branch3x3dbl = self.branch3x3dbl_1(x) 287 | branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl) 288 | branch3x3dbl = [ 289 | self.branch3x3dbl_3a(branch3x3dbl), 290 | self.branch3x3dbl_3b(branch3x3dbl), 291 | ] 292 | branch3x3dbl = torch.cat(branch3x3dbl, 1) 293 | 294 | branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1) 295 | branch_pool = self.branch_pool(branch_pool) 296 | 297 | outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool] 298 | return torch.cat(outputs, 1) 299 | 300 | 301 | class InceptionAux(nn.Module): 302 | 303 | def __init__(self, in_channels, num_classes): 304 | super(InceptionAux, self).__init__() 305 | self.conv0 = BasicConv2d(in_channels, 128, kernel_size=1) 306 | self.conv1 = BasicConv2d(128, 768, kernel_size=5) 307 | self.conv1.stddev = 0.01 308 | self.fc = nn.Linear(768, num_classes) 309 | self.fc.stddev = 0.001 310 | 311 | def forward(self, x): 312 | # N x 768 x 17 x 17 313 | x = F.avg_pool2d(x, kernel_size=5, stride=3) 314 | # N x 768 x 5 x 5 315 | x = self.conv0(x) 316 | # N x 128 x 5 x 5 317 | x = self.conv1(x) 318 | # N x 768 x 1 x 1 319 | # Adaptive average pooling 320 | x = F.adaptive_avg_pool2d(x, (1, 1)) 321 | # N x 768 x 1 x 1 322 | x = x.view(x.size(0), -1) 323 | # N x 768 324 | x = self.fc(x) 325 | # N x 1000 326 | return x 327 | 328 | 329 | class BasicConv2d(nn.Module): 330 | 331 | def __init__(self, in_channels, out_channels, **kwargs): 332 | super(BasicConv2d, self).__init__() 333 | self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs) 334 | self.bn = nn.BatchNorm2d(out_channels, eps=0.001) 335 | 336 | def forward(self, x): 337 | x = self.conv(x) 338 | x = self.bn(x) 339 | return F.relu(x, inplace=True) 340 | -------------------------------------------------------------------------------- /dfme/train.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import argparse, ipdb, json 3 | import torch 4 | import torch.nn.functional as F 5 | import torch.nn as nn 6 | import torch.optim as optim 7 | import network 8 | from dataloader import get_dataloader 9 | import os, random 10 | import numpy as np 11 | import torchvision 12 | from pprint import pprint 13 | from time import time 14 | 15 | from approximate_gradients import * 16 | 17 | import torchvision.models as models 18 | from my_utils import * 19 | 20 | 21 | print("torch version", torch.__version__) 22 | 23 | def myprint(a): 24 | """Log the print statements""" 25 | global file 26 | print(a); file.write(a); file.write("\n"); file.flush() 27 | 28 | 29 | def student_loss(args, s_logit, t_logit, return_t_logits=False): 30 | """Kl/ L1 Loss for student""" 31 | print_logits = False 32 | if args.loss == "l1": 33 | loss_fn = F.l1_loss 34 | loss = loss_fn(s_logit, t_logit.detach()) 35 | elif args.loss == "kl": 36 | loss_fn = F.kl_div 37 | s_logit = F.log_softmax(s_logit, dim=1) 38 | t_logit = F.softmax(t_logit, dim=1) 39 | loss = loss_fn(s_logit, t_logit.detach(), reduction="batchmean") 40 | else: 41 | raise ValueError(args.loss) 42 | 43 | if return_t_logits: 44 | return loss, t_logit.detach() 45 | else: 46 | return loss 47 | 48 | def generator_loss(args, s_logit, t_logit, z = None, z_logit = None, reduction="mean"): 49 | assert 0 50 | 51 | loss = - F.l1_loss( s_logit, t_logit , reduction=reduction) 52 | 53 | 54 | return loss 55 | 56 | 57 | def train(args, teacher, student, generator, device, optimizer, epoch): 58 | """Main Loop for one epoch of Training Generator and Student""" 59 | global file 60 | teacher.eval() 61 | student.train() 62 | 63 | optimizer_S, optimizer_G = optimizer 64 | 65 | gradients = [] 66 | 67 | 68 | for i in range(args.epoch_itrs): 69 | """Repeat epoch_itrs times per epoch""" 70 | for _ in range(args.g_iter): 71 | #Sample Random Noise 72 | z = torch.randn((args.batch_size, args.nz)).to(device) 73 | optimizer_G.zero_grad() 74 | generator.train() 75 | #Get fake image from generator 76 | fake = generator(z, pre_x=args.approx_grad) # pre_x returns the output of G before applying the activation 77 | 78 | 79 | ## APPOX GRADIENT 80 | approx_grad_wrt_x, loss_G = estimate_gradient_objective(args, teacher, student, fake, 81 | epsilon = args.grad_epsilon, m = args.grad_m, num_classes=args.num_classes, 82 | device=device, pre_x=True) 83 | 84 | fake.backward(approx_grad_wrt_x) 85 | 86 | optimizer_G.step() 87 | 88 | if i == 0 and args.rec_grad_norm: 89 | x_true_grad = measure_true_grad_norm(args, fake) 90 | 91 | for _ in range(args.d_iter): 92 | z = torch.randn((args.batch_size, args.nz)).to(device) 93 | fake = generator(z).detach() 94 | optimizer_S.zero_grad() 95 | 96 | with torch.no_grad(): 97 | t_logit = teacher(fake) 98 | 99 | # Correction for the fake logits 100 | if args.loss == "l1" and args.no_logits: 101 | t_logit = F.log_softmax(t_logit, dim=1).detach() 102 | if args.logit_correction == 'min': 103 | t_logit -= t_logit.min(dim=1).values.view(-1, 1).detach() 104 | elif args.logit_correction == 'mean': 105 | t_logit -= t_logit.mean(dim=1).view(-1, 1).detach() 106 | 107 | 108 | s_logit = student(fake) 109 | 110 | 111 | loss_S = student_loss(args, s_logit, t_logit) 112 | loss_S.backward() 113 | optimizer_S.step() 114 | 115 | # Log Results 116 | if i % args.log_interval == 0: 117 | myprint(f'Train Epoch: {epoch} [{i}/{args.epoch_itrs} ({100*float(i)/float(args.epoch_itrs):.0f}%)]\tG_Loss: {loss_G.item():.6f} S_loss: {loss_S.item():.6f}') 118 | 119 | if i == 0: 120 | with open(args.log_dir + "/loss.csv", "a") as f: 121 | f.write("%d,%f,%f\n"%(epoch, loss_G, loss_S)) 122 | 123 | 124 | if args.rec_grad_norm and i == 0: 125 | 126 | G_grad_norm, S_grad_norm = compute_grad_norms(generator, student) 127 | if i == 0: 128 | with open(args.log_dir + "/norm_grad.csv", "a") as f: 129 | f.write("%d,%f,%f,%f\n"%(epoch, G_grad_norm, S_grad_norm, x_true_grad)) 130 | 131 | 132 | # update query budget 133 | args.query_budget -= args.cost_per_iteration 134 | 135 | if args.query_budget < args.cost_per_iteration: 136 | return 137 | 138 | 139 | def test(args, student = None, generator = None, device = "cuda", test_loader = None, epoch=0): 140 | global file 141 | student.eval() 142 | generator.eval() 143 | 144 | test_loss = 0 145 | correct = 0 146 | with torch.no_grad(): 147 | for i, (data, target) in enumerate(test_loader): 148 | data, target = data.to(device), target.to(device) 149 | output = student(data) 150 | 151 | test_loss += F.cross_entropy(output, target, reduction='sum').item() # sum up batch loss 152 | pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability 153 | correct += pred.eq(target.view_as(pred)).sum().item() 154 | 155 | test_loss /= len(test_loader.dataset) 156 | accuracy = 100. * correct / len(test_loader.dataset) 157 | myprint('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.4f}%)\n'.format( 158 | test_loss, correct, len(test_loader.dataset), 159 | accuracy)) 160 | with open(args.log_dir + "/accuracy.csv", "a") as f: 161 | f.write("%d,%f\n"%(epoch, accuracy)) 162 | acc = correct/len(test_loader.dataset) 163 | return acc 164 | 165 | def compute_grad_norms(generator, student): 166 | G_grad = [] 167 | for n, p in generator.named_parameters(): 168 | if "weight" in n: 169 | # print('===========\ngradient{}\n----------\n{}'.format(n, p.grad.norm().to("cpu"))) 170 | G_grad.append(p.grad.norm().to("cpu")) 171 | 172 | S_grad = [] 173 | for n, p in student.named_parameters(): 174 | if "weight" in n: 175 | # print('===========\ngradient{}\n----------\n{}'.format(n, p.grad.norm().to("cpu"))) 176 | S_grad.append(p.grad.norm().to("cpu")) 177 | return np.mean(G_grad), np.mean(S_grad) 178 | 179 | def main(): 180 | # Training settings 181 | parser = argparse.ArgumentParser(description='DFAD CIFAR') 182 | parser.add_argument('--batch_size', type=int, default=256, metavar='N',help='input batch size for training (default: 256)') 183 | parser.add_argument('--query_budget', type=float, default=20, metavar='N', help='Query budget for the extraction attack in millions (default: 20M)') 184 | parser.add_argument('--epoch_itrs', type=int, default=50) 185 | parser.add_argument('--g_iter', type=int, default=1, help = "Number of generator iterations per epoch_iter") 186 | parser.add_argument('--d_iter', type=int, default=5, help = "Number of discriminator iterations per epoch_iter") 187 | 188 | parser.add_argument('--lr_S', type=float, default=0.1, metavar='LR', help='Student learning rate (default: 0.1)') 189 | parser.add_argument('--lr_G', type=float, default=1e-4, help='Generator learning rate (default: 0.1)') 190 | parser.add_argument('--nz', type=int, default=256, help = "Size of random noise input to generator") 191 | 192 | parser.add_argument('--log_interval', type=int, default=10, metavar='N', help='how many batches to wait before logging training status') 193 | 194 | parser.add_argument('--loss', type=str, default='l1', choices=['l1', 'kl'],) 195 | parser.add_argument('--scheduler', type=str, default='multistep', choices=['multistep', 'cosine', "none"],) 196 | parser.add_argument('--steps', nargs='+', default = [0.1, 0.3, 0.5], type=float, help = "Percentage epochs at which to take next step") 197 | parser.add_argument('--scale', type=float, default=3e-1, help = "Fractional decrease in lr") 198 | 199 | parser.add_argument('--dataset', type=str, default='cifar10', choices=['svhn','cifar10'], help='dataset name (default: cifar10)') 200 | parser.add_argument('--data_root', type=str, default='data') 201 | parser.add_argument('--model', type=str, default='resnet34_8x', choices=classifiers, help='Target model name (default: resnet34_8x)') 202 | parser.add_argument('--weight_decay', type=float, default=5e-4) 203 | parser.add_argument('--momentum', type=float, default=0.9, metavar='M', 204 | help='SGD momentum (default: 0.9)') 205 | parser.add_argument('--no-cuda', action='store_true', default=False, 206 | help='disables CUDA training') 207 | parser.add_argument('--seed', type=int, default=random.randint(0, 100000), metavar='S', 208 | help='random seed (default: 1)') 209 | parser.add_argument('--ckpt', type=str, default='checkpoint/teacher/cifar10-resnet34_8x.pt') 210 | 211 | 212 | parser.add_argument('--student_load_path', type=str, default=None) 213 | parser.add_argument('--model_id', type=str, default="debug") 214 | 215 | parser.add_argument('--device', type=int, default=0) 216 | parser.add_argument('--log_dir', type=str, default="results") 217 | 218 | # Gradient approximation parameters 219 | parser.add_argument('--approx_grad', type=int, default=1, help = 'Always set to 1') 220 | parser.add_argument('--grad_m', type=int, default=1, help='Number of steps to approximate the gradients') 221 | parser.add_argument('--grad_epsilon', type=float, default=1e-3) 222 | 223 | 224 | parser.add_argument('--forward_differences', type=int, default=1, help='Always set to 1') 225 | 226 | 227 | # Eigenvalues computation parameters 228 | parser.add_argument('--no_logits', type=int, default=1) 229 | parser.add_argument('--logit_correction', type=str, default='mean', choices=['none', 'mean']) 230 | 231 | parser.add_argument('--rec_grad_norm', type=int, default=1) 232 | 233 | parser.add_argument('--MAZE', type=int, default=0) 234 | 235 | parser.add_argument('--store_checkpoints', type=int, default=1) 236 | 237 | parser.add_argument('--student_model', type=str, default='resnet18_8x', 238 | help='Student model architecture (default: resnet18_8x)') 239 | 240 | 241 | args = parser.parse_args() 242 | 243 | 244 | args.query_budget *= 10**6 245 | args.query_budget = int(args.query_budget) 246 | if args.MAZE: 247 | 248 | print("\n"*2) 249 | print("#### /!\ OVERWRITING ALL PARAMETERS FOR MAZE REPLCIATION ####") 250 | print("\n"*2) 251 | args.scheduer = "cosine" 252 | args.loss = "kl" 253 | args.batch_size = 128 254 | args.g_iter = 1 255 | args.d_iter = 5 256 | args.grad_m = 10 257 | args.lr_G = 1e-4 258 | args.lr_S = 1e-1 259 | 260 | 261 | if args.student_model not in classifiers: 262 | if "wrn" not in args.student_model: 263 | raise ValueError("Unknown model") 264 | 265 | 266 | pprint(args, width= 80) 267 | print(args.log_dir) 268 | os.makedirs(args.log_dir, exist_ok=True) 269 | 270 | if args.store_checkpoints: 271 | os.makedirs(args.log_dir + "/checkpoint", exist_ok=True) 272 | 273 | 274 | # Save JSON with parameters 275 | with open(args.log_dir + "/parameters.json", "w") as f: 276 | json.dump(vars(args), f) 277 | 278 | with open(args.log_dir + "/loss.csv", "w") as f: 279 | f.write("epoch,loss_G,loss_S\n") 280 | 281 | with open(args.log_dir + "/accuracy.csv", "w") as f: 282 | f.write("epoch,accuracy\n") 283 | 284 | if args.rec_grad_norm: 285 | with open(args.log_dir + "/norm_grad.csv", "w") as f: 286 | f.write("epoch,G_grad_norm,S_grad_norm,grad_wrt_X\n") 287 | 288 | with open("latest_experiments.txt", "a") as f: 289 | f.write(args.log_dir + "\n") 290 | use_cuda = not args.no_cuda and torch.cuda.is_available() 291 | 292 | # Prepare the environment 293 | torch.manual_seed(args.seed) 294 | torch.cuda.manual_seed(args.seed) 295 | np.random.seed(args.seed) 296 | random.seed(args.seed) 297 | torch.backends.cudnn.deterministic = True 298 | torch.backends.cudnn.benchmark = False 299 | 300 | device = torch.device("cuda:%d"%args.device if use_cuda else "cpu") 301 | kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {} 302 | 303 | # Preparing checkpoints for the best Student 304 | global file 305 | model_dir = f"checkpoint/student_{args.model_id}"; args.model_dir = model_dir 306 | if(not os.path.exists(model_dir)): 307 | os.makedirs(model_dir) 308 | with open(f"{model_dir}/model_info.txt", "w") as f: 309 | json.dump(args.__dict__, f, indent=2) 310 | file = open(f"{args.model_dir}/logs.txt", "w") 311 | 312 | print(args) 313 | 314 | args.device = device 315 | 316 | # Eigen values and vectors of the covariance matrix 317 | _, test_loader = get_dataloader(args) 318 | 319 | 320 | args.normalization_coefs = None 321 | args.G_activation = torch.tanh 322 | 323 | num_classes = 10 if args.dataset in ['cifar10', 'svhn'] else 100 324 | args.num_classes = num_classes 325 | 326 | if args.model == 'resnet34_8x': 327 | teacher = network.resnet_8x.ResNet34_8x(num_classes=num_classes) 328 | if args.dataset == 'svhn': 329 | print("Loading SVHN TEACHER") 330 | args.ckpt = 'checkpoint/teacher/svhn-resnet34_8x.pt' 331 | teacher.load_state_dict( torch.load( args.ckpt, map_location=device) ) 332 | else: 333 | teacher = get_classifier(args.model, pretrained=True, num_classes=args.num_classes) 334 | 335 | 336 | 337 | teacher.eval() 338 | teacher = teacher.to(device) 339 | myprint("Teacher restored from %s"%(args.ckpt)) 340 | print(f"\n\t\tTraining with {args.model} as a Target\n") 341 | correct = 0 342 | with torch.no_grad(): 343 | for i, (data, target) in enumerate(test_loader): 344 | data, target = data.to(device), target.to(device) 345 | output = teacher(data) 346 | pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability 347 | correct += pred.eq(target.view_as(pred)).sum().item() 348 | accuracy = 100. * correct / len(test_loader.dataset) 349 | print('\nTeacher - Test set: Accuracy: {}/{} ({:.4f}%)\n'.format(correct, len(test_loader.dataset),accuracy)) 350 | 351 | 352 | 353 | student = get_classifier(args.student_model, pretrained=False, num_classes=args.num_classes) 354 | 355 | generator = network.gan.GeneratorA(nz=args.nz, nc=3, img_size=32, activation=args.G_activation) 356 | 357 | 358 | 359 | student = student.to(device) 360 | generator = generator.to(device) 361 | 362 | args.generator = generator 363 | args.student = student 364 | args.teacher = teacher 365 | 366 | 367 | if args.student_load_path : 368 | # "checkpoint/student_no-grad/cifar10-resnet34_8x.pt" 369 | student.load_state_dict( torch.load( args.student_load_path ) ) 370 | myprint("Student initialized from %s"%(args.student_load_path)) 371 | acc = test(args, student=student, generator=generator, device = device, test_loader = test_loader) 372 | 373 | ## Compute the number of epochs with the given query budget: 374 | args.cost_per_iteration = args.batch_size * (args.g_iter * (args.grad_m+1) + args.d_iter) 375 | 376 | number_epochs = args.query_budget // (args.cost_per_iteration * args.epoch_itrs) + 1 377 | 378 | print (f"\nTotal budget: {args.query_budget//1000}k") 379 | print ("Cost per iterations: ", args.cost_per_iteration) 380 | print ("Total number of epochs: ", number_epochs) 381 | 382 | optimizer_S = optim.SGD( student.parameters(), lr=args.lr_S, weight_decay=args.weight_decay, momentum=0.9 ) 383 | 384 | if args.MAZE: 385 | optimizer_G = optim.SGD( generator.parameters(), lr=args.lr_G , weight_decay=args.weight_decay, momentum=0.9 ) 386 | else: 387 | optimizer_G = optim.Adam( generator.parameters(), lr=args.lr_G ) 388 | 389 | steps = sorted([int(step * number_epochs) for step in args.steps]) 390 | print("Learning rate scheduling at steps: ", steps) 391 | print() 392 | 393 | if args.scheduler == "multistep": 394 | scheduler_S = optim.lr_scheduler.MultiStepLR(optimizer_S, steps, args.scale) 395 | scheduler_G = optim.lr_scheduler.MultiStepLR(optimizer_G, steps, args.scale) 396 | elif args.scheduler == "cosine": 397 | scheduler_S = optim.lr_scheduler.CosineAnnealingLR(optimizer_S, number_epochs) 398 | scheduler_G = optim.lr_scheduler.CosineAnnealingLR(optimizer_G, number_epochs) 399 | 400 | 401 | best_acc = 0 402 | acc_list = [] 403 | 404 | for epoch in range(1, number_epochs + 1): 405 | # Train 406 | if args.scheduler != "none": 407 | scheduler_S.step() 408 | scheduler_G.step() 409 | 410 | 411 | train(args, teacher=teacher, student=student, generator=generator, device=device, optimizer=[optimizer_S, optimizer_G], epoch=epoch) 412 | # Test 413 | acc = test(args, student=student, generator=generator, device = device, test_loader = test_loader, epoch=epoch) 414 | acc_list.append(acc) 415 | if acc>best_acc: 416 | best_acc = acc 417 | name = 'resnet34_8x' 418 | torch.save(student.state_dict(),f"checkpoint/student_{args.model_id}/{args.dataset}-{name}.pt") 419 | torch.save(generator.state_dict(),f"checkpoint/student_{args.model_id}/{args.dataset}-{name}-generator.pt") 420 | # vp.add_scalar('Acc', epoch, acc) 421 | if args.store_checkpoints: 422 | torch.save(student.state_dict(), args.log_dir + f"/checkpoint/student.pt") 423 | torch.save(generator.state_dict(), args.log_dir + f"/checkpoint/generator.pt") 424 | myprint("Best Acc=%.6f"%best_acc) 425 | 426 | with open(args.log_dir + "/Max_accuracy = %f"%best_acc, "w") as f: 427 | f.write(" ") 428 | 429 | 430 | 431 | import csv 432 | os.makedirs('log', exist_ok=True) 433 | with open('log/DFAD-%s.csv'%(args.dataset), 'a') as f: 434 | writer = csv.writer(f) 435 | writer.writerow(acc_list) 436 | 437 | 438 | if __name__ == '__main__': 439 | main() 440 | 441 | 442 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------