├── .gitignore
├── LICENSE
├── README.md
├── attack_api.py
├── eval.py
├── main.py
├── nets.py
├── train_scratch.py
└── utils.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Towards Efficient Data Free Black-Box Adversarial Attack
2 | Official PyTorch implementation of [Towards Efficient Data Free Black-Box Adversarial Attack](https://openaccess.thecvf.com/content/CVPR2022/papers/Zhang_Towards_Efficient_Data_Free_Black-Box_Adversarial_Attack_CVPR_2022_paper.pdf) (CVPR 2022)
3 |
4 | **Abstract**:
5 |
6 |
7 |
8 |
9 | > Classic black-box adversarial attacks can take advantage of transferable adversarial examples generated by a similar substitute model to successfully fool the target model. However, these substitute models need to be trained by target models' training data, which is hard to acquire due to privacy or transmission reasons. Recognizing the limited availability of real data for adversarial queries, recent works proposed to train substitute models in a data-free black-box scenario. However, their generative adversarial networks (GANs) based framework suffers from the convergence failure and the model collapse, resulting in low efficiency. In this paper, by rethinking the collaborative relationship between the generator and the substitute model, we design a novel black-box attack framework. The proposed method can efficiently imitate the target model through a small number of queries and achieve high attack success rate. The comprehensive experiments over six datasets demonstrate the effectiveness of our method against the state-of-the-art attacks. Especially, we conduct both label-only and probability-only attacks on the Microsoft Azure online model, and achieve a 100% attack success rate with only 0.46% query budget of the SOTA method.
10 |
11 |
12 |
13 | ## How to run
14 |
15 | Experiments of original paper:
16 |
17 | - Train the substitute model.
18 | If you want to train a substitute model in MNIST:
19 | ```python
20 | python3 train_scratch.py --dataset=mnist --epoch=200
21 | ```
22 |
23 |
24 | - Generate the adversarial attacks by white-box attacks and transfer them to the attacked model.
25 | When the substitute model is obtained, you can use the following command to evaluate the substitute model:
26 |
27 | ```python
28 | python3 main.py --epochs=400 --save_dir=run/mnist --dataset=mnist --score=1 --other=cnn_mnsit --g_steps=10
29 | ```
30 |
31 | You can also attack the Microsoft Azure API model by run `attack_api.py`, the downloaded remote model can be seen in [remote_model](https://github.com/zhoumingyi/DaST/blob/master/pretrained/sklearn_mnist_model.pkl).
32 |
33 |
34 | ### score-only:
35 |
36 | | Dataset | Scripts |
37 | | :----: | :----: |
38 | |MNIST | python3 main.py --epochs=400 --save_dir=run/mnist --dataset=mnist --score=1 --other=cnn_mnsit --g_steps=10 |
39 | |Fashion-MNIST| python3 main.py --epochs=400 --save_dir=run/fmnist --dataset=fmnist --score=1 --other=cnn_fmnsit --g_steps=10|
40 | |SVHN | python3 main.py --epochs=400 --save_dir=run/svhn --dataset=svhn --score=1 --other=cnn_svhn --g_steps=10|
41 | |CIFAR10 | python3 main.py --epochs=2000 --save_dir=run/cifar10 --dataset=cifar10 --score=1 --other=cnn_cifar10 --g_steps=5|
42 | |CIFAR100 | python3 main.py --epochs=2000 --save_dir=run/cifar100 --dataset=cifar100 --score=1 --other=cnn_cifar100 --g_steps=5 --batch_size=1000 |
43 | |Tiny-Imagenet | python3 main.py --epochs=2000 --save_dir=run/tiny --dataset=tiny --score=1 --other=cnn_tiny --g_steps=5 --batch_size=800 |
44 |
45 | ### label-only:
46 | Just set `--score=0`
47 |
48 |
49 | An example of the training:
50 |
51 |
52 |
53 |
54 | ## Citation
55 | ```
56 | @inproceedings{zhang2022towards,
57 | title={Towards Efficient Data Free Black-Box Adversarial Attack},
58 | author={Zhang, Jie and Li, Bo and Xu, Jianghe and Wu, Shuang and Ding, Shouhong and Zhang, Lei and Wu, Chao},
59 | booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
60 | pages={15115--15125},
61 | year={2022}
62 | }
63 | ```
64 |
--------------------------------------------------------------------------------
/attack_api.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Python version: 3.6
4 | import argparse
5 | import os
6 | from tensorboardX import SummaryWriter
7 | import numpy as np
8 | import torch.optim as optim
9 | import warnings
10 | from tqdm import tqdm
11 | from torch.nn.functional import mse_loss
12 | import random
13 | from torchvision import transforms
14 | from kornia import augmentation
15 | import torch
16 | import torch.nn.functional as F
17 | import torch.utils.data.sampler as sp
18 | import torch.backends.cudnn as cudnn
19 |
20 | from nets import Generator_2
21 | from utils import ScoreLoss, ImagePool, MultiTransform, reset_model, get_dataset, cal_prob, cal_label, setup_seed, \
22 | get_model, print_log, test, test_robust, save_checkpoint
23 | import joblib
24 | from advertorch.attacks import LinfBasicIterativeAttack
25 |
26 |
27 | warnings.filterwarnings('ignore')
28 |
29 |
30 | class Synthesizer():
31 | def __init__(self, generator, nz, num_classes, img_size,
32 | iterations, lr_g,
33 | sample_batch_size, save_dir, dataset):
34 | super(Synthesizer, self).__init__()
35 | self.img_size = img_size
36 | self.iterations = iterations
37 | self.lr_g = lr_g
38 | self.nz = nz
39 | self.score_loss = ScoreLoss()
40 | self.num_classes = num_classes
41 | self.sample_batch_size = sample_batch_size
42 | self.save_dir = save_dir
43 | self.data_pool = ImagePool(root=self.save_dir)
44 | self.data_iter = None
45 | self.dataset = dataset
46 |
47 | self.generator = generator.cuda().train()
48 |
49 | self.aug = MultiTransform([
50 | # global view
51 | transforms.Compose([
52 | augmentation.RandomCrop(size=[self.img_size[-2], self.img_size[-1]], padding=4),
53 | augmentation.RandomHorizontalFlip(),
54 | ]),
55 | # local view
56 | transforms.Compose([
57 | augmentation.RandomResizedCrop(size=[self.img_size[-2], self.img_size[-1]], scale=[0.25, 1.0]),
58 | augmentation.RandomHorizontalFlip(),
59 | ]),
60 | ])
61 | # =======================
62 | if not ("cifar" in dataset):
63 | self.transform = transforms.Compose(
64 | [
65 | transforms.RandomHorizontalFlip(),
66 | transforms.ToTensor(),
67 | ])
68 | else:
69 | self.transform = transforms.Compose(
70 | [
71 | transforms.RandomCrop(32, padding=4),
72 | transforms.RandomHorizontalFlip(),
73 | transforms.ToTensor(),
74 | ])
75 |
76 | def get_data(self):
77 | datasets = self.data_pool.get_dataset(transform=self.transform) # 获取程序运行到现在所有的图片
78 | self.data_loader = torch.utils.data.DataLoader(
79 | datasets, batch_size=256, shuffle=True,
80 | num_workers=4, pin_memory=True, )
81 | return self.data_loader
82 |
83 | def gen_data(self, student):
84 | student.eval()
85 | best_cost = 1e6
86 | best_inputs = None
87 | z = torch.randn(size=(self.sample_batch_size, self.nz)).cuda() #
88 | z.requires_grad = True
89 | targets = torch.randint(low=0, high=self.num_classes, size=(self.sample_batch_size,))
90 | targets = targets.sort()[0]
91 | targets = targets.cuda()
92 | reset_model(self.generator)
93 | optimizer = torch.optim.Adam(self.generator.parameters(), self.lr_g, betas=[0.5, 0.999])
94 |
95 | for it in range(self.iterations):
96 | optimizer.zero_grad()
97 | inputs = self.generator(z) # bs,nz
98 | global_view, _ = self.aug(inputs) # crop and normalize
99 |
100 | s_out = student(global_view)
101 | loss = self.score_loss(s_out, targets) # ce_loss
102 | if best_cost > loss.item() or best_inputs is None:
103 | best_cost = loss.item()
104 | best_inputs = inputs.data
105 |
106 | loss.backward()
107 | optimizer.step()
108 | # with tqdm(total=self.iterations) as t:
109 |
110 | # optimizer_mlp.step()
111 | # t.set_description('iters:{}, loss:{}'.format(it, loss.item()))
112 |
113 | # save best inputs and reset data iter
114 | self.data_pool.add(best_inputs) # 生成了一个batch的数据
115 |
116 |
117 | def args_parser():
118 | parser = argparse.ArgumentParser()
119 | # federated arguments (Notation for the arguments followed from paper)
120 | parser.add_argument('--epochs', type=int, default=10,
121 | help="number of rounds of training")
122 | parser.add_argument('--score', type=float, default=0,
123 | help="number of rounds of training")
124 | parser.add_argument('--lr', type=float, default=0.01,
125 | help='learning rate')
126 | parser.add_argument('--momentum', type=float, default=0.9,
127 | help='SGD momentum (default: 0.5)')
128 | # other arguments
129 | parser.add_argument('--dataset', type=str, default='mnist', help="name \
130 | of dataset")
131 | # Data Free
132 |
133 | parser.add_argument('--save_dir', default='run/mnist', type=str)
134 |
135 | # Basic
136 | parser.add_argument('--lr_g', default=1e-3, type=float,
137 | help='initial learning rate for generation')
138 | parser.add_argument('--g_steps', default=30, type=int, metavar='N',
139 | help='number of iterations for generation')
140 | parser.add_argument('--batch_size', default=256, type=int, metavar='N',
141 | help='number of total iterations in each epoch')
142 | parser.add_argument('--nz', default=256, type=int, metavar='N',
143 | help='number of total iterations in each epoch')
144 | parser.add_argument('--synthesis_batch_size', default=256, type=int)
145 | # Misc
146 | parser.add_argument('--seed', default=2021, type=int,
147 | help='seed for initializing training.')
148 | parser.add_argument('--type', default="score", type=str,
149 | help='score or label')
150 | parser.add_argument('--model', default="", type=str,
151 | help='seed for initializing training.')
152 | parser.add_argument('--other', default="", type=str,
153 | help='seed for initializing training.')
154 | args = parser.parse_args()
155 | return args
156 |
157 |
158 | def kd_train(synthesizer, model, optimizer, score_val):
159 | sub_net, blackBox_net = model
160 | sub_net.train()
161 | # blackBox_net.eval()
162 |
163 | # with tqdm(synthesizer.get_data()) as epochs:
164 | data = synthesizer.get_data()
165 | for idx, (images) in enumerate(data):
166 | optimizer.zero_grad()
167 | images = images.cuda()
168 | with torch.no_grad():
169 | original_score = cal_azure_proba(blackBox_net, images)
170 | label = torch.max(original_score.data, 1)[1]
171 |
172 | # original_score = cal_prob(blackBox_net, images) # prob
173 | substitute_outputs = sub_net(images.detach())
174 | substitute_score = F.softmax(substitute_outputs, dim=1)
175 | loss_mse = mse_loss(
176 | substitute_score, original_score, reduction='mean')
177 | # label = cal(blackBox_net, images) # label
178 | loss_ce = F.cross_entropy(substitute_outputs, label)
179 | # ==============================
180 | # idx = torch.where(substitute_outputs.max(1)[1] != label)[0]
181 | # loss_adv = F.cross_entropy(substitute_outputs[idx], label[idx])
182 | # ==============================
183 | loss = loss_ce + loss_mse * score_val
184 |
185 | loss.backward()
186 | optimizer.step()
187 |
188 |
189 | def cal_azure(model, data):
190 | data = data.view(data.size(0), 784).cpu().numpy()
191 | output = model.predict(data)
192 | output = torch.from_numpy(output).cuda().long()
193 | return output
194 |
195 |
196 | def cal_azure_proba(model, data):
197 | data = data.view(data.size(0), 784).cpu().numpy()
198 | output = model.predict_proba(data)
199 | output = torch.from_numpy(output).cuda().float()
200 | return output
201 |
202 | if __name__ == '__main__':
203 | dir = './saved/api'
204 | if not os.path.exists(dir):
205 | os.mkdir(dir)
206 |
207 | args = args_parser()
208 | setup_seed(args.seed)
209 | train_loader, test_loader = get_dataset(args.dataset)
210 |
211 | public = dir + '/logs_{}_{}'.format(args.dataset, str(args.score))
212 | if not os.path.exists(public):
213 | os.mkdir(public)
214 | log = open('{}/log_ours.txt'.format(public), 'w')
215 |
216 | list = [i for i in range(0, len(test_loader.dataset))]
217 | data_list = random.sample(list, 1024)
218 | val_loader = torch.utils.data.DataLoader(test_loader.dataset, batch_size=128,
219 | sampler=sp.SubsetRandomSampler(data_list), num_workers=4)
220 |
221 | tf_writer = SummaryWriter(log_dir=public)
222 | sub_net, _ = get_model(args.dataset, 0)
223 | clf = joblib.load('pretrained/sklearn_mnist_model.pkl')
224 |
225 | with torch.no_grad():
226 | correct_netD = 0.0
227 | total = 0.0
228 | for inputs, labels in val_loader:
229 | inputs, labels = inputs.cuda(), labels.cuda()
230 | predicted = cal_azure(clf, inputs)
231 | total += labels.size(0)
232 | correct_netD += (predicted == labels).sum()
233 | print('Accuracy of the black-box network : %.2f %%' %
234 | (100. * correct_netD.float() / total))
235 | ################################################
236 | # estimate the attack success rate of initial D:
237 | ################################################
238 | correct_ghost = 0.0
239 | total = 0.0
240 | sub_net.eval()
241 | adversary_ghost = LinfBasicIterativeAttack(
242 | sub_net, loss_fn=torch.nn.CrossEntropyLoss(reduction="sum"), eps=0.3,
243 | nb_iter=100, eps_iter=0.01, clip_min=0.0, clip_max=1.0,
244 | targeted=False)
245 | for inputs, labels in val_loader:
246 | inputs, labels = inputs.cuda(), labels.cuda()
247 | adv_inputs_ghost = adversary_ghost.perturb(inputs, labels)
248 | with torch.no_grad():
249 | predicted = cal_azure(clf, adv_inputs_ghost)
250 | total += labels.size(0)
251 | correct_ghost += (predicted == labels).sum()
252 | print('Attack success rate: %.2f %%' %
253 | (100 - 100. * correct_ghost.float() / total))
254 |
255 | ################################################
256 | # data generator
257 | ################################################
258 | nz = args.nz
259 | nc = 1
260 |
261 | img_size = 28
262 | img_size2 = (1, 28, 28)
263 |
264 | generator = Generator_2(nz=nz, ngf=64, img_size=img_size, nc=nc).cuda()
265 |
266 | num_class = 10
267 |
268 | synthesizer = Synthesizer(generator,
269 | nz=nz,
270 | num_classes=num_class,
271 | img_size=img_size2,
272 | iterations=args.g_steps,
273 | lr_g=args.lr_g,
274 | sample_batch_size=args.batch_size,
275 | save_dir=args.save_dir,
276 | dataset=args.dataset)
277 | # &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
278 | optimizer = optim.SGD(sub_net.parameters(), lr=args.lr, momentum=args.momentum)
279 | sub_net.train()
280 | best_acc = -1
281 | best_asr = -1
282 | best_acc_ckpt = '{}/{}_ours_acc.pth'.format(public, args.dataset)
283 | for epoch in tqdm(range(args.epochs)):
284 | # 1. Data synthesis
285 | synthesizer.gen_data(sub_net) # g_steps
286 | kd_train(synthesizer, [sub_net, clf], optimizer, args.score)
287 | if epoch % 1 == 0: # 250*40, 250*10=2.5k
288 | acc, test_loss = test(sub_net, val_loader)
289 | ################################################
290 | # estimate the attack success rate of initial D:
291 | ################################################
292 | correct_ghost = 0.0
293 | total = 0.0
294 | sub_net.eval()
295 | adversary_ghost = LinfBasicIterativeAttack(
296 | sub_net, loss_fn=torch.nn.CrossEntropyLoss(reduction="sum"), eps=0.3,
297 | nb_iter=100, eps_iter=0.01, clip_min=0.0, clip_max=1.0,
298 | targeted=False)
299 | for inputs, labels in val_loader:
300 | inputs, labels = inputs.cuda(), labels.cuda()
301 | adv_inputs_ghost = adversary_ghost.perturb(inputs, labels)
302 | with torch.no_grad():
303 | predicted = cal_azure(clf, adv_inputs_ghost)
304 | total += labels.size(0)
305 | correct_ghost += (predicted == labels).sum()
306 | asr = (100 - 100. * correct_ghost.float() / total)
307 | print('Attack success rate: %.2f %%' % asr)
308 | save_checkpoint({
309 | 'state_dict': sub_net.state_dict(),
310 | 'epoch': epoch,
311 | }, acc > best_acc, best_acc_ckpt)
312 |
313 | best_asr = max(best_asr, asr)
314 | best_acc = max(best_acc, acc)
315 |
316 | print_log("Accuracy of the substitute model:{:.3} %, best accuracy:{:.3} % \n".format(acc, best_acc), log)
317 | print_log("ASR:{:.3} %, best asr:{:.3} %\n".format(asr, best_asr), log)
318 | log.flush()
319 |
320 | """
321 |
322 | CUDA_VISIBLE_DEVICES=2 python3 attack_api.py --epochs=100 --save_dir=run/mnist_1 --dataset=mnist --score=1 --other=cnn_mnsit --g_steps=10
323 |
324 | """
325 |
--------------------------------------------------------------------------------
/eval.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function
2 |
3 | import argparse
4 | import random
5 |
6 | import torch
7 | import torch.backends.cudnn as cudnn
8 | import torch.nn as nn
9 | import torch.nn.parallel
10 | import torch.utils.data
11 | import torch.utils.data.sampler as sp
12 | from advertorch.attacks import GradientSignAttack, PGDAttack, LinfPGDAttack
13 | from advertorch.attacks import LinfBasicIterativeAttack, CarliniWagnerL2Attack
14 |
15 |
16 | from utils import get_model, test, setup_seed, get_dataset
17 |
18 |
19 | def test_adver(net, tar_net, attack, target, testloader, dataset):
20 | if dataset == "mnist":
21 | cfgs = dict(test_step_size=0.01, test_epsilon=0.3)
22 | elif dataset == "cifar10" or dataset == "cifar100":
23 | cfgs = dict(test_step_size=2.0 / 255, test_epsilon=8.0 / 255)
24 | elif dataset == "fmnist":
25 | cfgs = dict(test_step_size=0.01, test_epsilon=0.3)
26 | elif dataset == "svhn" or dataset == "tiny":
27 | cfgs = dict(test_step_size=2.0 / 255, test_epsilon=8.0 / 255)
28 |
29 |
30 | net.eval()
31 | tar_net.eval()
32 | # BIM
33 | if attack == 'BIM':
34 | adversary = LinfBasicIterativeAttack(
35 | net,
36 | loss_fn=nn.CrossEntropyLoss(reduction="sum"),
37 | eps=cfgs['test_epsilon'],
38 | nb_iter=120, eps_iter=cfgs['test_step_size'], clip_min=0.0, clip_max=1.0,
39 | targeted=target)
40 | # PGD
41 | elif attack == 'PGD':
42 | if target:
43 | adversary = PGDAttack(
44 | net,
45 | loss_fn=nn.CrossEntropyLoss(reduction="sum"),
46 | eps=cfgs['test_epsilon'],
47 | nb_iter=20, eps_iter=cfgs['test_step_size'], clip_min=0.0, clip_max=1.0,
48 | targeted=target)
49 | else:
50 | adversary = PGDAttack(
51 | net,
52 | loss_fn=nn.CrossEntropyLoss(reduction="sum"),
53 | eps=cfgs['test_epsilon'],
54 | nb_iter=20, eps_iter=cfgs['test_step_size'], clip_min=0.0, clip_max=1.0,
55 | targeted=target)
56 | # FGSM
57 | elif attack == 'FGSM':
58 | adversary = GradientSignAttack(
59 | net,
60 | loss_fn=nn.CrossEntropyLoss(reduction="sum"),
61 | eps=cfgs['test_epsilon'],
62 | targeted=target)
63 | elif attack == 'CW':
64 | adversary = CarliniWagnerL2Attack(
65 | net,
66 | num_classes=10,
67 | learning_rate=0.45,
68 | binary_search_steps=10,
69 | max_iterations=20,
70 | targeted=target)
71 |
72 | # ----------------------------------
73 | # Obtain the attack success rate of the model
74 | # ----------------------------------
75 |
76 | correct = 0.0
77 | total = 0.0
78 | tar_net.eval()
79 | total_L2_distance = 0.0
80 | for data in testloader:
81 | inputs, labels = data
82 | inputs, labels = inputs.cuda(), labels.cuda()
83 | outputs = tar_net(inputs)
84 | _, predicted = torch.max(outputs.data, 1)
85 | if target:
86 | # randomly choose the specific label of targeted attack
87 | labels = torch.randint(0, 9, (inputs.shape[0],)).cuda()
88 | # test the images which are not classified as the specific label
89 | idx = torch.where(predicted != labels)[0]
90 | adv_inputs_ori = adversary.perturb(inputs[idx], labels[idx])
91 | L2_distance = (torch.norm(adv_inputs_ori - inputs[idx])).item()
92 | total_L2_distance += L2_distance
93 | with torch.no_grad():
94 | outputs = tar_net(adv_inputs_ori)
95 | _, predicted = torch.max(outputs.data, 1)
96 | total += labels.size(0)
97 | correct += (predicted == labels[idx]).sum()
98 | else:
99 | # test the images which are classified correctly
100 | idx = torch.where(predicted == labels)[0]
101 | adv_inputs_ori = adversary.perturb(inputs[idx], labels[idx])
102 | L2_distance = (torch.norm(adv_inputs_ori - inputs[idx])).item()
103 | total_L2_distance += L2_distance
104 | with torch.no_grad():
105 | outputs = tar_net(adv_inputs_ori)
106 | _, predicted = torch.max(outputs.data, 1)
107 |
108 | total += labels.size(0)
109 | correct += (predicted == labels[idx]).sum()
110 |
111 | asr = 100. * correct.float() / total if target else 100.0 - 100. * correct.float() / total
112 | return asr
113 |
114 |
115 | if __name__ == '__main__':
116 | setup_seed(2021)
117 | parser = argparse.ArgumentParser()
118 | # parser.add_argument('--target', type=int, )
119 | parser.add_argument('--dataset', type=str, )
120 | parser.add_argument('--dir', type=str, )
121 |
122 | opt = parser.parse_args()
123 | cudnn.benchmark = True
124 |
125 | train_loader, test_loader = get_dataset(opt.dataset)
126 | list = [i for i in range(0, len(test_loader.dataset))]
127 | data_list = random.sample(list, 1024)
128 | val_loader = torch.utils.data.DataLoader(test_loader.dataset, batch_size=64,
129 | sampler=sp.SubsetRandomSampler(data_list), num_workers=4)
130 |
131 | sub_net, _ = get_model(opt.dataset, 0)
132 | state_dict_1 = torch.load(opt.dir)['state_dict']
133 | sub_net.load_state_dict(state_dict_1)
134 |
135 | blackBox_net, state_dict = get_model(opt.dataset, 1)
136 | blackBox_net.load_state_dict(state_dict)
137 |
138 | acc, _ = test(sub_net, val_loader)
139 | print("Accuracy of the sub_net:{:.3} % \n".format(acc))
140 |
141 | # asr = test_adver(sub_net, blackBox_net, 'CW', 'Untarget' == 'Target', val_loader, opt.dataset)
142 | # print('Untarget' + " , " + "type: " + 'CW' + ", ASR:{:.2f} %, ".format(asr))
143 | for attack in ['Target', 'Untarget']:
144 | for adv in ['FGSM', 'BIM', 'PGD']:
145 | asr = test_adver(sub_net, blackBox_net, adv, attack == 'Target', val_loader, opt.dataset)
146 | print(attack + " , " + "type: " + adv + ", ASR:{:.2f} %, ".format(asr))
147 |
148 | # python3 eval_rob.py --dataset=mnist --dir=
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | # Python version: 3.6
4 | import argparse
5 | import os
6 | from tensorboardX import SummaryWriter
7 | import numpy as np
8 | import torch.optim as optim
9 | import warnings
10 | from tqdm import tqdm
11 | from torch.nn.functional import mse_loss
12 | import random
13 | from torchvision import transforms
14 | from kornia import augmentation
15 | import torch
16 | import torch.nn.functional as F
17 | import torch.utils.data.sampler as sp
18 | import torch.backends.cudnn as cudnn
19 |
20 | from nets import Generator_2
21 | from utils import ScoreLoss, ImagePool, MultiTransform, reset_model, get_dataset, cal_prob, cal_label, setup_seed, \
22 | get_model, print_log, test, test_robust, save_checkpoint
23 |
24 | warnings.filterwarnings('ignore')
25 |
26 |
27 | class Synthesizer():
28 | def __init__(self, generator, nz, num_classes, img_size,
29 | iterations, lr_g,
30 | sample_batch_size, save_dir, dataset):
31 | super(Synthesizer, self).__init__()
32 | self.img_size = img_size
33 | self.iterations = iterations
34 | self.lr_g = lr_g
35 | self.nz = nz
36 | self.score_loss = ScoreLoss()
37 | self.num_classes = num_classes
38 | self.sample_batch_size = sample_batch_size
39 | self.save_dir = save_dir
40 | self.data_pool = ImagePool(root=self.save_dir)
41 | self.data_iter = None
42 | self.dataset = dataset
43 |
44 | self.generator = generator.cuda().train()
45 |
46 | self.aug = MultiTransform([
47 | # global view
48 | transforms.Compose([
49 | augmentation.RandomCrop(size=[self.img_size[-2], self.img_size[-1]], padding=4),
50 | augmentation.RandomHorizontalFlip(),
51 | ]),
52 | # local view
53 | transforms.Compose([
54 | augmentation.RandomResizedCrop(size=[self.img_size[-2], self.img_size[-1]], scale=[0.25, 1.0]),
55 | augmentation.RandomHorizontalFlip(),
56 | ]),
57 | ])
58 | # =======================
59 | if not ("cifar" in dataset):
60 | self.transform = transforms.Compose(
61 | [
62 | transforms.RandomHorizontalFlip(),
63 | transforms.ToTensor(),
64 | ])
65 | else:
66 | self.transform = transforms.Compose(
67 | [
68 | transforms.RandomCrop(32, padding=4),
69 | transforms.RandomHorizontalFlip(),
70 | transforms.ToTensor(),
71 | ])
72 |
73 | def get_data(self):
74 | datasets = self.data_pool.get_dataset(transform=self.transform) # 获取程序运行到现在所有的图片
75 | self.data_loader = torch.utils.data.DataLoader(
76 | datasets, batch_size=256, shuffle=True,
77 | num_workers=4, pin_memory=True, )
78 | return self.data_loader
79 |
80 | def gen_data(self, student):
81 | student.eval()
82 | best_cost = 1e6
83 | best_inputs = None
84 | z = torch.randn(size=(self.sample_batch_size, self.nz)).cuda() #
85 | z.requires_grad = True
86 | targets = torch.randint(low=0, high=self.num_classes, size=(self.sample_batch_size,))
87 | targets = targets.sort()[0]
88 | targets = targets.cuda()
89 | reset_model(self.generator)
90 | optimizer = torch.optim.Adam(self.generator.parameters(), self.lr_g, betas=[0.5, 0.999])
91 |
92 | for it in range(self.iterations):
93 | optimizer.zero_grad()
94 | inputs = self.generator(z) # bs,nz
95 | global_view, _ = self.aug(inputs) # crop and normalize
96 |
97 | s_out = student(global_view)
98 | loss = self.score_loss(s_out, targets) # ce_loss
99 | if best_cost > loss.item() or best_inputs is None:
100 | best_cost = loss.item()
101 | best_inputs = inputs.data
102 |
103 | loss.backward()
104 | optimizer.step()
105 | # with tqdm(total=self.iterations) as t:
106 |
107 | # optimizer_mlp.step()
108 | # t.set_description('iters:{}, loss:{}'.format(it, loss.item()))
109 |
110 | # save best inputs and reset data iter
111 | self.data_pool.add(best_inputs) # 生成了一个batch的数据
112 |
113 |
114 | def args_parser():
115 | parser = argparse.ArgumentParser()
116 | # federated arguments (Notation for the arguments followed from paper)
117 | parser.add_argument('--epochs', type=int, default=10,
118 | help="number of rounds of training")
119 | parser.add_argument('--score', type=float, default=0,
120 | help="number of rounds of training")
121 | parser.add_argument('--lr', type=float, default=0.01,
122 | help='learning rate')
123 | parser.add_argument('--momentum', type=float, default=0.9,
124 | help='SGD momentum (default: 0.5)')
125 | # other arguments
126 | parser.add_argument('--dataset', type=str, default='mnist', help="name \
127 | of dataset")
128 | # Data Free
129 |
130 | parser.add_argument('--save_dir', default='run/mnist', type=str)
131 |
132 | # Basic
133 | parser.add_argument('--lr_g', default=1e-3, type=float,
134 | help='initial learning rate for generation')
135 | parser.add_argument('--g_steps', default=30, type=int, metavar='N',
136 | help='number of iterations for generation')
137 | parser.add_argument('--batch_size', default=256, type=int, metavar='N',
138 | help='number of total iterations in each epoch')
139 | parser.add_argument('--nz', default=256, type=int, metavar='N',
140 | help='number of total iterations in each epoch')
141 | parser.add_argument('--synthesis_batch_size', default=256, type=int)
142 | # Misc
143 | parser.add_argument('--seed', default=2021, type=int,
144 | help='seed for initializing training.')
145 | parser.add_argument('--type', default="score", type=str,
146 | help='score or label')
147 | parser.add_argument('--model', default="", type=str,
148 | help='seed for initializing training.')
149 | parser.add_argument('--other', default="", type=str,
150 | help='seed for initializing training.')
151 | args = parser.parse_args()
152 | return args
153 |
154 |
155 | def kd_train(synthesizer, model, optimizer, score_val):
156 | sub_net, blackBox_net = model
157 | sub_net.train()
158 | blackBox_net.eval()
159 |
160 | # with tqdm(synthesizer.get_data()) as epochs:
161 | data = synthesizer.get_data()
162 | for idx, (images) in enumerate(data):
163 | optimizer.zero_grad()
164 | images = images.cuda()
165 | original_score = cal_prob(blackBox_net, images) # prob
166 | substitute_outputs = sub_net(images.detach())
167 | substitute_score = F.softmax(substitute_outputs, dim=1)
168 | loss_mse = mse_loss(
169 | substitute_score, original_score, reduction='mean')
170 | label = cal_label(blackBox_net, images) # label
171 | loss_ce = F.cross_entropy(substitute_outputs, label)
172 | # ==============================
173 | # idx = torch.where(substitute_outputs.max(1)[1] != label)[0]
174 | # loss_adv = F.cross_entropy(substitute_outputs[idx], label[idx])
175 | # ==============================
176 | loss = loss_ce + loss_mse * score_val
177 |
178 | loss.backward()
179 | optimizer.step()
180 | # return loss.item()
181 |
182 |
183 |
184 | if __name__ == '__main__':
185 | dir = './saved/ours'
186 | if not os.path.exists(dir):
187 | os.mkdir(dir)
188 |
189 | args = args_parser()
190 | setup_seed(args.seed)
191 | train_loader, test_loader = get_dataset(args.dataset)
192 |
193 | public = dir + '/logs_{}_{}'.format(args.dataset, str(args.score))
194 | if not os.path.exists(public):
195 | os.mkdir(public)
196 | log = open('{}/log_ours.txt'.format(public), 'w')
197 |
198 | list = [i for i in range(0, len(test_loader.dataset))]
199 | data_list = random.sample(list, 1024)
200 | val_loader = torch.utils.data.DataLoader(test_loader.dataset, batch_size=128,
201 | sampler=sp.SubsetRandomSampler(data_list), num_workers=4)
202 |
203 | tf_writer = SummaryWriter(log_dir=public)
204 | sub_net, _ = get_model(args.dataset, 0)
205 | blackBox_net, state_dict = get_model(args.dataset, 1)
206 | blackBox_net.load_state_dict(state_dict)
207 |
208 | print_log("===================================== \n", log)
209 | acc, _ = test(blackBox_net, val_loader)
210 | print_log("Accuracy of the black-box model:{:.3} % \n".format(acc), log)
211 | acc, _ = test(sub_net, val_loader)
212 | print_log("Accuracy of the substitute model:{:.3} % \n".format(acc), log)
213 | asr, val_acc = 0.0, 0.0 # test_robust(val_loader, sub_net, blackBox_net, args.dataset)
214 | print_log("ASR:{:.3} %, val acc:{:.3} % \n".format(asr, val_acc), log)
215 | print_log("===================================== \n", log)
216 | log.flush()
217 |
218 | ################################################
219 | # data generator
220 | ################################################
221 | nz = args.nz
222 | nc = 3 if "cifar" in args.dataset or args.dataset == "svhn" or args.dataset == "tiny" else 1
223 | # img_size = 32 if "cifar" in args.dataset or args.dataset == "svhn" else 28
224 |
225 | if "cifar" in args.dataset or args.dataset == "svhn":
226 | img_size = 32
227 | elif "mnist" in args.dataset:
228 | img_size = 28
229 | elif args.dataset == "tiny":
230 | img_size = 64
231 |
232 | if "cifar" in args.dataset or args.dataset == "svhn":
233 | img_size2 = (3, 32, 32)
234 | elif "mnist" in args.dataset:
235 | img_size2 = (1, 28, 28)
236 | elif args.dataset == "tiny":
237 | img_size2 = (3, 64, 64)
238 | generator = Generator_2(nz=nz, ngf=64, img_size=img_size, nc=nc).cuda()
239 | # ====================
240 | sub_net = torch.nn.DataParallel(sub_net)
241 | blackBox_net = torch.nn.DataParallel(blackBox_net)
242 | generator = torch.nn.DataParallel(generator)
243 | # ====================
244 |
245 | args.cur_ep = 0
246 | # img_size2 = (
247 | # 3, 32, 32) if "cifar" in args.dataset or args.dataset == "svhn" else (1, 28, 28)
248 |
249 | if args.dataset == "cifar100":
250 | num_class = 100
251 | elif args.dataset == "tiny":
252 | num_class = 200
253 | else:
254 | num_class = 10
255 |
256 | synthesizer = Synthesizer(generator,
257 | nz=nz,
258 | num_classes=num_class,
259 | img_size=img_size2,
260 | iterations=args.g_steps,
261 | lr_g=args.lr_g,
262 | sample_batch_size=args.batch_size,
263 | save_dir=args.save_dir,
264 | dataset=args.dataset)
265 | # &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
266 | optimizer = optim.SGD(sub_net.parameters(), lr=args.lr, momentum=args.momentum)
267 | sub_net.train()
268 | best_acc = -1
269 | best_asr = -1
270 |
271 | best_acc_ckpt = '{}/{}_ours_acc.pth'.format(public, args.dataset)
272 | best_asr_ckpt = '{}/{}_ours_asr.pth'.format(public, args.dataset)
273 | for epoch in tqdm(range(args.epochs)):
274 | # 1. Data synthesis
275 | synthesizer.gen_data(sub_net) # g_steps
276 | kd_train(synthesizer, [sub_net, blackBox_net], optimizer, args.score)
277 | if epoch % 1 == 0: # 250*40, 250*10=2.5k
278 | acc, test_loss = test(sub_net, val_loader)
279 | asr, val_acc = test_robust(val_loader, sub_net, blackBox_net, args.dataset)
280 |
281 | # save_checkpoint({
282 | # 'state_dict': sub_net.state_dict(),
283 | # 'epoch': epoch,
284 | # }, acc > best_acc, best_acc_ckpt)
285 | #
286 | # save_checkpoint({
287 | # 'state_dict': sub_net.state_dict(),
288 | # 'epoch': epoch,
289 | # }, asr > best_asr, best_asr_ckpt)
290 |
291 | best_asr = max(best_asr, asr)
292 | best_acc = max(best_acc, acc)
293 |
294 | print_log("Accuracy of the substitute model:{:.3} %, best accuracy:{:.3} % \n".format(acc, best_acc), log)
295 | print_log("ASR:{:.3} %, best asr:{:.3} %, val acc:{:.3} % \n".format(asr, best_asr, val_acc), log)
296 | log.flush()
297 |
298 | """
299 | 40*256=1w
300 | CUDA_VISIBLE_DEVICES=2 python3 main.py --epochs=400 --save_dir=run/svhn_1 \
301 | --dataset=svhn --score=1 --other=cnn_svhn --g_steps=5
302 |
303 | CUDA_VISIBLE_DEVICES=3 python3 main.py --epochs=400 --save_dir=run/svhn_2 \
304 | --dataset=svhn --score=1 --other=cnn_svhn --g_steps=30
305 |
306 |
307 | CUDA_VISIBLE_DEVICES=2 python3 main.py --epochs=400 --save_dir=run/cifar10 --dataset=cifar10 --score=1 --other=cnn_cifar10 --g_steps=5
308 |
309 | CUDA_VISIBLE_DEVICES=2 python3 main.py --epochs=400 --save_dir=run/mnist_1 --dataset=mnist --score=1 --other=cnn_mnsit --g_steps=10
310 |
311 | CUDA_VISIBLE_DEVICES=1 python3 main.py --epochs=400 --save_dir=run/fmnist_1 --dataset=fmnist --score=1 --other=cnn_fmnsit --g_steps=10
312 |
313 | CUDA_VISIBLE_DEVICES=1 python3 main.py --epochs=400 --save_dir=run/fmnist_2 --dataset=fmnist --score=1 --other=cnn_fmnsit --g_steps=30
314 | """
315 |
--------------------------------------------------------------------------------
/nets.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 | import torch.nn.parallel
5 |
6 | nz = 128
7 | nc = 3
8 |
9 |
10 | class pre_conv(nn.Module):
11 | def __init__(self):
12 | super(pre_conv, self).__init__()
13 | self.nf = 64
14 | G_type = 1
15 |
16 | if G_type == 1:
17 | # ipdb.set_trace()
18 | self.pre_conv = nn.Sequential(
19 | nn.Conv2d(nz, self.nf * 2, 3, 1, 1, bias=False), # torch.Size([50, 128, 1, 1])
20 | nn.BatchNorm2d(self.nf * 2),
21 | nn.LeakyReLU(0.2, inplace=True),
22 |
23 | nn.ConvTranspose2d(self.nf * 2, self.nf * 2, 4, 2, 1, bias=False), # torch.Size([50, 128, 2, 2])
24 | nn.BatchNorm2d(self.nf * 2),
25 | nn.LeakyReLU(0.2, inplace=True),
26 |
27 | nn.ConvTranspose2d(self.nf * 2, self.nf * 2, 4, 2, 1, bias=False),
28 | nn.BatchNorm2d(self.nf * 2),
29 | nn.LeakyReLU(0.2, inplace=True),
30 |
31 | nn.ConvTranspose2d(self.nf * 2, self.nf * 2, 4, 2, 1, bias=False),
32 | nn.BatchNorm2d(self.nf * 2),
33 | nn.LeakyReLU(0.2, inplace=True),
34 |
35 | nn.ConvTranspose2d(self.nf * 2, self.nf * 2, 4, 2, 1, bias=False),
36 | nn.BatchNorm2d(self.nf * 2),
37 | nn.LeakyReLU(0.2, inplace=True),
38 |
39 | nn.ConvTranspose2d(self.nf * 2, self.nf * 2, 4, 2, 1, bias=False),
40 | nn.BatchNorm2d(self.nf * 2),
41 | nn.LeakyReLU(0.2, inplace=True)
42 | )
43 | elif G_type == 2:
44 | self.pre_conv = nn.Sequential(
45 | nn.Conv2d(self.nf * 8, self.nf * 8, 3, 1, round((self.shape[0] - 1) / 2), bias=False),
46 | nn.BatchNorm2d(self.nf * 8),
47 | nn.ReLU(True), # added
48 | nn.Conv2d(self.nf * 8, self.nf * 8, 3, 1, round((self.shape[0] - 1) / 2), bias=False),
49 | nn.BatchNorm2d(self.nf * 8),
50 | nn.ReLU(True),
51 |
52 | nn.Conv2d(self.nf * 8, self.nf * 4, 3, 1, 1, bias=False),
53 | nn.BatchNorm2d(self.nf * 4),
54 | nn.ReLU(True),
55 |
56 | nn.Conv2d(self.nf * 4, self.nf * 2, 3, 1, 1, bias=False),
57 | nn.BatchNorm2d(self.nf * 2),
58 | nn.ReLU(True),
59 |
60 | nn.Conv2d(self.nf * 2, self.nf, 3, 1, 1, bias=False),
61 | nn.BatchNorm2d(self.nf),
62 | nn.ReLU(True),
63 |
64 | nn.Conv2d(self.nf, self.shape[0], 3, 1, 1, bias=False),
65 | nn.BatchNorm2d(self.shape[0]),
66 | nn.ReLU(True),
67 |
68 | nn.Conv2d(self.shape[0], self.shape[0], 3, 1, 1, bias=False),
69 |
70 | nn.Sigmoid()
71 | )
72 |
73 | def forward(self, input):
74 | output = self.pre_conv(input)
75 | return output
76 |
77 |
78 | class Generator(nn.Module):
79 | def __init__(self):
80 | super(Generator, self).__init__()
81 | self.nf = 64
82 | self.num_class = 10
83 | G_type = 1
84 | if G_type == 1:
85 | self.main = nn.Sequential(
86 | nn.Conv2d(self.nf * 2, self.nf * 4, 3, 1, 0, bias=False),
87 | nn.BatchNorm2d(self.nf * 4),
88 | nn.LeakyReLU(0.2, inplace=True),
89 |
90 | nn.Conv2d(self.nf * 4, self.nf * 8, 3, 1, 0, bias=False),
91 | nn.BatchNorm2d(self.nf * 8),
92 | nn.LeakyReLU(0.2, inplace=True),
93 |
94 | nn.Conv2d(self.nf * 8, self.nf * 4, 3, 1, 1, bias=False),
95 | nn.BatchNorm2d(self.nf * 4),
96 | nn.LeakyReLU(0.2, inplace=True),
97 |
98 | nn.Conv2d(self.nf * 4, self.nf * 2, 3, 1, 1, bias=False),
99 | nn.BatchNorm2d(self.nf * 2),
100 | nn.LeakyReLU(0.2, inplace=True),
101 |
102 | nn.Conv2d(self.nf * 2, self.nf, 3, 1, 1, bias=False),
103 | nn.BatchNorm2d(self.nf),
104 | nn.LeakyReLU(0.2, inplace=True),
105 |
106 | nn.Conv2d(self.nf, nc, 3, 1, 1, bias=False),
107 | nn.BatchNorm2d(nc),
108 | nn.LeakyReLU(0.2, inplace=True),
109 |
110 | nn.Conv2d(nc, nc, 3, 1, 1, bias=False),
111 | nn.Sigmoid()
112 | )
113 | elif G_type == 2:
114 | self.main = nn.Sequential(
115 | nn.Conv2d(nz, self.nf * 2, 3, 1, 1, bias=False),
116 | nn.BatchNorm2d(self.nf * 2),
117 | nn.ReLU(True),
118 |
119 | nn.ConvTranspose2d(self.nf * 2, self.nf * 2, 4, 2, 1, bias=False),
120 | nn.BatchNorm2d(self.nf * 2),
121 | nn.ReLU(True),
122 |
123 | nn.ConvTranspose2d(self.nf * 2, self.nf * 4, 4, 2, 1, bias=False),
124 | nn.BatchNorm2d(self.nf * 4),
125 | nn.ReLU(True),
126 |
127 | nn.ConvTranspose2d(self.nf * 4, self.nf * 4, 4, 2, 1, bias=False),
128 | nn.BatchNorm2d(self.nf * 4),
129 | nn.ReLU(True),
130 |
131 | nn.ConvTranspose2d(self.nf * 4, self.nf * 8, 4, 2, 1, bias=False),
132 | nn.BatchNorm2d(self.nf * 8),
133 | nn.ReLU(True),
134 |
135 | nn.ConvTranspose2d(self.nf * 8, self.nf * 8, 4, 2, 1, bias=False),
136 | nn.BatchNorm2d(self.nf * 8),
137 | nn.ReLU(True),
138 |
139 | nn.Conv2d(self.nf * 8, self.nf * 8, 3, 1, 1, bias=False),
140 | nn.BatchNorm2d(self.nf * 8),
141 | nn.ReLU(True)
142 | )
143 |
144 | def forward(self, input):
145 | output = self.main(input)
146 | return output
147 |
148 |
149 | class Generator_2(nn.Module):
150 | def __init__(self, nz=100, ngf=64, img_size=32, nc=3):
151 | super(Generator_2, self).__init__()
152 |
153 | self.init_size = img_size // 4
154 | self.l1 = nn.Sequential(nn.Linear(nz, ngf * 2 * self.init_size ** 2))
155 |
156 | self.conv_blocks = nn.Sequential(
157 | nn.BatchNorm2d(ngf * 2),
158 | nn.Upsample(scale_factor=2),
159 |
160 | nn.Conv2d(ngf * 2, ngf * 2, 3, stride=1, padding=1, bias=False),
161 | nn.BatchNorm2d(ngf * 2),
162 | nn.LeakyReLU(0.2, inplace=True),
163 | nn.Upsample(scale_factor=2),
164 |
165 | nn.Conv2d(ngf * 2, ngf, 3, stride=1, padding=1, bias=False),
166 | nn.BatchNorm2d(ngf),
167 | nn.LeakyReLU(0.2, inplace=True),
168 | nn.Conv2d(ngf, nc, 3, stride=1, padding=1),
169 | nn.Sigmoid(),
170 | )
171 |
172 | def forward(self, z):
173 | out = self.l1(z)
174 | out = out.view(out.shape[0], -1, self.init_size, self.init_size)
175 | img = self.conv_blocks(out)
176 | return img
177 |
178 | def UpSampling(x, H, W):
179 | B, N, C = x.size()
180 | assert N == H * W
181 | x = x.permute(0, 2, 1)
182 | x = x.view(-1, C, H, W)
183 | x = nn.PixelShuffle(2)(x)
184 | B, C, H, W = x.size()
185 | x = x.view(-1, C, H * W)
186 | x = x.permute(0, 2, 1)
187 | return x, H, W
188 |
189 | class MLP(nn.Module):
190 | def __init__(self, in_feat, hid_feat=None, out_feat=None,
191 | dropout=0.):
192 | super().__init__()
193 | if not hid_feat:
194 | hid_feat = in_feat
195 | if not out_feat:
196 | out_feat = in_feat
197 | self.fc1 = nn.Linear(in_feat, hid_feat)
198 | self.act = nn.GELU()
199 | self.fc2 = nn.Linear(hid_feat, out_feat)
200 | self.droprateout = nn.Dropout(dropout)
201 |
202 | def forward(self, x):
203 | x = self.fc1(x)
204 | x = self.act(x)
205 | x = self.fc2(x)
206 | return self.droprateout(x)
207 |
208 |
209 | class Attention(nn.Module):
210 | def __init__(self, dim, heads=4, attention_dropout=0., proj_dropout=0.):
211 | super().__init__()
212 | self.heads = heads
213 | self.scale = 1./dim**0.5
214 |
215 | self.qkv = nn.Linear(dim, dim*3, bias=False)
216 | self.attention_dropout = nn.Dropout(attention_dropout)
217 | self.out = nn.Sequential(
218 | nn.Linear(dim, dim),
219 | nn.Dropout(proj_dropout)
220 | )
221 |
222 | def forward(self, x):
223 | b, n, c = x.shape
224 | qkv = self.qkv(x).reshape(b, n, 3, self.heads, c//self.heads)
225 | q, k, v = qkv.permute(2, 0, 3, 1, 4)
226 |
227 | dot = (q @ k.transpose(-2, -1)) * self.scale
228 | attn = dot.softmax(dim=-1)
229 | attn = self.attention_dropout(attn)
230 |
231 | x = (attn @ v).transpose(1, 2).reshape(b, n, c)
232 | x = self.out(x)
233 | return x
234 |
235 | class Encoder_Block(nn.Module):
236 | def __init__(self, dim, heads, mlp_ratio=4, drop_rate=0.):
237 | super().__init__()
238 | self.ln1 = nn.LayerNorm(dim)
239 | self.attn = Attention(dim, heads, drop_rate, drop_rate)
240 | self.ln2 = nn.LayerNorm(dim)
241 | self.mlp = MLP(dim, dim * mlp_ratio, dropout=drop_rate)
242 |
243 | def forward(self, x):
244 | x1 = self.ln1(x)
245 | x = x + self.attn(x1)
246 | x2 = self.ln2(x)
247 | x = x + self.mlp(x2)
248 | return x
249 |
250 |
251 | class TransformerEncoder(nn.Module):
252 | def __init__(self, depth, dim, heads, mlp_ratio=4, drop_rate=0.):
253 | super().__init__()
254 | self.Encoder_Blocks = nn.ModuleList([
255 | Encoder_Block(dim, heads, mlp_ratio, drop_rate)
256 | for i in range(depth)])
257 |
258 | def forward(self, x):
259 | for Encoder_Block in self.Encoder_Blocks:
260 | x = Encoder_Block(x)
261 | return x
262 |
263 |
264 | class Generator_3(nn.Module):
265 | """docstring for Generator"""
266 |
267 | def __init__(self, depth1=5, depth2=4, depth3=2, initial_size=8, dim=384, heads=4, mlp_ratio=4,
268 | drop_rate=0.):
269 | super(Generator_3, self).__init__()
270 |
271 |
272 | self.initial_size = initial_size
273 | self.dim = dim
274 | self.depth1 = depth1
275 | self.depth2 = depth2
276 | self.depth3 = depth3
277 | self.heads = heads
278 | self.mlp_ratio = mlp_ratio
279 | self.droprate_rate = drop_rate
280 |
281 | self.mlp = nn.Linear(1024, (self.initial_size ** 2) * self.dim)
282 |
283 | self.positional_embedding_1 = nn.Parameter(torch.zeros(1, (8 ** 2), 384))
284 | self.positional_embedding_2 = nn.Parameter(torch.zeros(1, (8 * 2) ** 2, 384 // 4))
285 | self.positional_embedding_3 = nn.Parameter(torch.zeros(1, (8 * 4) ** 2, 384 // 16))
286 |
287 | self.TransformerEncoder_encoder1 = TransformerEncoder(depth=self.depth1, dim=self.dim, heads=self.heads,
288 | mlp_ratio=self.mlp_ratio, drop_rate=self.droprate_rate)
289 | self.TransformerEncoder_encoder2 = TransformerEncoder(depth=self.depth2, dim=self.dim // 4, heads=self.heads,
290 | mlp_ratio=self.mlp_ratio, drop_rate=self.droprate_rate)
291 | self.TransformerEncoder_encoder3 = TransformerEncoder(depth=self.depth3, dim=self.dim // 16, heads=self.heads,
292 | mlp_ratio=self.mlp_ratio, drop_rate=self.droprate_rate)
293 |
294 | self.linear = nn.Sequential(nn.Conv2d(self.dim // 16, 3, 1, 1, 0))
295 |
296 | def forward(self, noise):
297 | x = self.mlp(noise).view(-1, self.initial_size ** 2, self.dim)
298 |
299 | x = x + self.positional_embedding_1
300 | H, W = self.initial_size, self.initial_size
301 | x = self.TransformerEncoder_encoder1(x)
302 |
303 | x, H, W = UpSampling(x, H, W)
304 | x = x + self.positional_embedding_2
305 | x = self.TransformerEncoder_encoder2(x)
306 |
307 | x, H, W = UpSampling(x, H, W)
308 | x = x + self.positional_embedding_3
309 |
310 | x = self.TransformerEncoder_encoder3(x)
311 | x = self.linear(x.permute(0, 2, 1).view(-1, self.dim // 16, H, W))
312 |
313 | return x
314 | class CNNCifar10(nn.Module):
315 | def __init__(self):
316 | super(CNNCifar10, self).__init__()
317 | self.conv1 = nn.Conv2d(3, 256, 3)
318 | self.pool = nn.MaxPool2d(2, 2)
319 | self.conv2 = nn.Conv2d(256, 256, 3)
320 | self.conv3 = nn.Conv2d(256, 128, 3)
321 | self.fc1 = nn.Linear(128 * 4 * 4, 10)
322 |
323 | def forward(self, x):
324 | x = self.pool(F.relu(self.conv1(x)))
325 | x = self.pool(F.relu(self.conv2(x)))
326 | x = F.relu(self.conv3(x))
327 | x = x.view(-1, 128 * 4 * 4)
328 | x = self.fc1(x)
329 | return x
330 |
331 | class CNN(nn.Module):
332 | def __init__(self):
333 | super(CNN, self).__init__()
334 | self.layer1 = nn.Sequential(
335 | nn.Conv2d(1, 16, kernel_size=5, padding=2),
336 | nn.BatchNorm2d(16),
337 | nn.ReLU(),
338 | nn.MaxPool2d(2))
339 | self.layer2 = nn.Sequential(
340 | nn.Conv2d(16, 32, kernel_size=5, padding=2),
341 | nn.BatchNorm2d(32),
342 | nn.ReLU(),
343 | nn.MaxPool2d(2))
344 | self.fc = nn.Linear(7 * 7 * 32, 10)
345 |
346 | def forward(self, x):
347 | out = self.layer1(x)
348 | out = self.layer2(out)
349 | out = out.view(out.size(0), -1)
350 | out = self.fc(out)
351 | return out
352 |
353 | class BasicBlock(nn.Module):
354 | expansion = 1
355 |
356 | def __init__(self, in_planes, planes, stride=1):
357 | super(BasicBlock, self).__init__()
358 | self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
359 | self.bn1 = nn.BatchNorm2d(planes)
360 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
361 | self.bn2 = nn.BatchNorm2d(planes)
362 |
363 | self.shortcut = nn.Sequential()
364 | if stride != 1 or in_planes != self.expansion * planes:
365 | self.shortcut = nn.Sequential(
366 | nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False),
367 | nn.BatchNorm2d(self.expansion * planes)
368 | )
369 |
370 | def forward(self, x):
371 | out = F.relu(self.bn1(self.conv1(x)))
372 | out = self.bn2(self.conv2(out))
373 | out += self.shortcut(x)
374 | out = F.relu(out)
375 | return out
376 |
377 |
378 | class Bottleneck(nn.Module):
379 | expansion = 4
380 |
381 | def __init__(self, in_planes, planes, stride=1):
382 | super(Bottleneck, self).__init__()
383 | self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
384 | self.bn1 = nn.BatchNorm2d(planes)
385 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
386 | self.bn2 = nn.BatchNorm2d(planes)
387 | self.conv3 = nn.Conv2d(planes, self.expansion * planes, kernel_size=1, bias=False)
388 | self.bn3 = nn.BatchNorm2d(self.expansion * planes)
389 |
390 | self.shortcut = nn.Sequential()
391 | if stride != 1 or in_planes != self.expansion * planes:
392 | self.shortcut = nn.Sequential(
393 | nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False),
394 | nn.BatchNorm2d(self.expansion * planes)
395 | )
396 |
397 | def forward(self, x):
398 | out = F.relu(self.bn1(self.conv1(x)))
399 | out = F.relu(self.bn2(self.conv2(out)))
400 | out = self.bn3(self.conv3(out))
401 | out += self.shortcut(x)
402 | out = F.relu(out)
403 | return out
404 |
405 |
406 | class ResNet(nn.Module):
407 | def __init__(self, block, num_blocks, num_classes=10):
408 | super(ResNet, self).__init__()
409 | self.in_planes = 64
410 |
411 | self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
412 | self.bn1 = nn.BatchNorm2d(64)
413 | self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)
414 | self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)
415 | self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)
416 | self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)
417 | self.linear = nn.Linear(512 * block.expansion, num_classes)
418 |
419 | def _make_layer(self, block, planes, num_blocks, stride):
420 | strides = [stride] + [1] * (num_blocks - 1)
421 | layers = []
422 | for stride in strides:
423 | layers.append(block(self.in_planes, planes, stride))
424 | self.in_planes = planes * block.expansion
425 | return nn.Sequential(*layers)
426 |
427 | def forward(self, x, return_features=False):
428 | x = self.conv1(x)
429 | x = self.bn1(x)
430 | out = F.relu(x)
431 | out = self.layer1(out)
432 | out = self.layer2(out)
433 | out = self.layer3(out)
434 | out = self.layer4(out)
435 | out = F.adaptive_avg_pool2d(out, (1, 1))
436 | feature = out.view(out.size(0), -1)
437 | out = self.linear(feature)
438 |
439 | if return_features:
440 | return out, feature
441 | else:
442 | return out
443 |
444 |
445 | def resnet18(num_classes=10):
446 | return ResNet(BasicBlock, [2, 2, 2, 2], num_classes)
447 |
448 |
449 | def resnet34(num_classes=10):
450 | return ResNet(BasicBlock, [3, 4, 6, 3], num_classes)
451 |
452 |
453 | def resnet50(num_classes=10):
454 | return ResNet(Bottleneck, [3, 4, 6, 3], num_classes)
455 |
456 |
457 | def resnet101(num_classes=10):
458 | return ResNet(Bottleneck, [3, 4, 23, 3], num_classes)
459 |
460 |
461 | def resnet152(num_classes=10):
462 | return ResNet(Bottleneck, [3, 8, 36, 3], num_classes)
463 |
--------------------------------------------------------------------------------
/train_scratch.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function
2 | import argparse # Python 命令行解析工具
3 | from tqdm import tqdm
4 | import torch
5 | import torch.nn as nn
6 | import torch.nn.functional as F
7 | import torch.optim as optim
8 | from tensorboardX import SummaryWriter
9 | from nets import resnet34, CNN, CNNCifar10, resnet18, resnet50, MLP, AlexNet, vgg8_bn
10 | from utils import test, get_dataset
11 | import warnings
12 |
13 | warnings.filterwarnings('ignore')
14 |
15 |
16 | def train(model, train_loader, optimizer, epoch):
17 | model.train()
18 |
19 | for idx, (data, target) in enumerate(train_loader):
20 | optimizer.zero_grad()
21 | data, target = data.cuda(), target.cuda()
22 | output = model(data)
23 | loss = F.cross_entropy(output, target)
24 | loss.backward()
25 | optimizer.step()
26 |
27 |
28 | def adjust_learning_rate(lr, optimizer, epoch):
29 | """Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
30 | lr = lr * (0.1 ** (epoch // 40))
31 | for param_group in optimizer.param_groups:
32 | param_group['lr'] = lr
33 |
34 | # def get_model(dataset, net):
35 | # if "mnist" in dataset:
36 | # if net == "mlp":
37 | # model = MLP().cuda()
38 | # elif net == "lenet":
39 | # model = CNN().cuda()
40 | # elif net == "alexnet":
41 | # model = AlexNet().cuda()
42 | # elif dataset == "svhn":
43 | # if net == "alexnet":
44 | # model = CNNCifar10().cuda()
45 | # elif net == "vgg":
46 | # model = CNNCifar10().cuda()
47 | # elif net == "resnet18":
48 | # model = resnet18(num_classes=10).cuda()
49 | # elif dataset == "cifar10":
50 | # # model = resnet18(num_classes=10).cuda()
51 | # model = CNNCifar10().cuda()
52 | # elif dataset == "cifar100":
53 | # model = resnet50(num_classes=100).cuda()
54 | # elif dataset == "imagenet":
55 | # model = resnet18(num_classes=12).cuda()
56 | # return model
57 |
58 |
59 | def main():
60 | # Training settings
61 | parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
62 | parser.add_argument('--dataset', type=str, default="cifar10",
63 | help='dataset')
64 | parser.add_argument('--net', type=str, default="cifar10",
65 | help='dataset')
66 | parser.add_argument('--epochs', type=int, default=100,
67 | help='number of epochs to train (default: 100)')
68 | parser.add_argument('--lr', type=float, default=0.1,
69 | help='learning rate (default: 0.01)')
70 | parser.add_argument('--momentum', type=float, default=0.9,
71 | help='SGD momentum (default: 0.9)')
72 | parser.add_argument('--model', type=str, default='resnet34',
73 | help='SGD momentum (default: 0.9)')
74 | args = parser.parse_args()
75 |
76 | train_loader, test_loader = get_dataset(args.dataset)
77 | # model = get_teacher_model(args.dataset, args.net)
78 | model = CNNCifar10().cuda()
79 | # model = vgg8_bn(num_classes=10).cuda()
80 | optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum)
81 | bst_acc = -1
82 | public = "pretrained_large/{}_{}".format(args.dataset, args.net)
83 | tf_writer = SummaryWriter(log_dir=public)
84 | for epoch in range(1, args.epochs + 1):
85 | # adjust_learning_rate(args.lr, optimizer, epoch)
86 | train(model, train_loader, optimizer, epoch)
87 | acc, loss = test(model, test_loader)
88 | if acc > bst_acc:
89 | bst_acc = acc
90 | torch.save(model.state_dict(), '{}/{}_{}.pkl'.format(public, args.dataset, args.net))
91 |
92 | tf_writer.add_scalar('test_acc', acc, epoch)
93 | bst_acc = max(bst_acc, acc)
94 | print("Epoch:{},\t test_acc:{}, best_acc:{}".format(epoch, acc, bst_acc))
95 |
96 |
97 | if __name__ == '__main__':
98 | main()
99 |
100 |
101 |
102 |
--------------------------------------------------------------------------------
/utils.py:
--------------------------------------------------------------------------------
1 | import os
2 | import torch.backends.cudnn as cudnn
3 | import matplotlib.pyplot as plt
4 | import torch
5 | import torch.nn as nn
6 | import torch.nn.functional as F
7 | import torchvision.utils as vutils
8 | from kornia import augmentation
9 | from sklearn.manifold import TSNE
10 | from torch.nn.functional import mse_loss
11 | from torchvision import transforms
12 | from tqdm import tqdm
13 | import numpy as np
14 | from torch.autograd import Variable
15 | from advertorch.attacks import LinfPGDAttack, LinfBasicIterativeAttack
16 | import math
17 | import os
18 | import random
19 | from torchvision import datasets, transforms
20 | from PIL import Image
21 | from nets import CNN, CNNCifar10, resnet18, resnet50
22 |
23 |
24 | def get_model(dataset, load):
25 | if "mnist" in dataset:
26 | model = CNN().cuda()
27 | # model = Net_m().cuda()
28 | elif dataset == "cifar10" or dataset == "svhn":
29 | # model = resnet18(num_classes=10).cuda()
30 | model = CNNCifar10().cuda()
31 | elif dataset == "cifar100":
32 | model = resnet50(num_classes=100).cuda()
33 | elif dataset == "tiny":
34 | model = resnet50(num_classes=200).cuda()
35 | # pretraind = 'public/attack/pretrained/'
36 | pretraind = 'pretrained_ckpt/cifar10_cnn'
37 | load_list = ['cnn_mnist.pth', 'cnn_fmnist.pth', 'cnncifar10.pkl', 'res18_svhn.pth',
38 | 'res50_cifar100.pth', 'res50_tiny_imagenet.pth']
39 | if load == 1:
40 | if "mnist" == dataset:
41 | state_dict = torch.load(pretraind + load_list[0])['state_dict']
42 | elif "fmnist" == dataset:
43 | state_dict = torch.load(pretraind + load_list[1])['state_dict']
44 | elif dataset == "cifar10":
45 | state_dict = torch.load(pretraind + load_list[2])['state_dict']
46 | elif dataset == "svhn":
47 | state_dict = torch.load(pretraind + load_list[3])['state_dict']
48 | elif dataset == "cifar100":
49 | state_dict = torch.load(pretraind + load_list[4])['state_dict']
50 | elif dataset == "tiny":
51 | state_dict = torch.load(pretraind + load_list[5])
52 | else:
53 | state_dict = None
54 |
55 | return model, state_dict
56 |
57 |
58 | def cal_prob(black_net, data):
59 | with torch.no_grad():
60 | outputs = black_net(data.detach())
61 | score = F.softmax(outputs, dim=1) # score-based
62 | score = score.detach().cpu().numpy()
63 | score = torch.from_numpy(score).cuda().float()
64 | return score
65 |
66 |
67 | def cal_label(black_net, data):
68 | with torch.no_grad():
69 | outputs = black_net(data.detach())
70 | _, label = torch.max(outputs.data, 1)
71 | label = label.detach().cpu().numpy()
72 | label = torch.from_numpy(label).cuda().long()
73 | return label
74 |
75 |
76 | def test_robust(loader, substitute_net, original_net, dataset):
77 | # cfgs = dict(random=True, test_num_steps=40, test_step_size=0.01, test_epsilon=0.3, num_classes=10)
78 | if dataset == "mnist":
79 | cfgs = dict(test_step_size=0.01, test_epsilon=0.3)
80 | elif dataset == "cifar10" or dataset == "cifar100":
81 | cfgs = dict(test_step_size=2.0 / 255, test_epsilon=8.0 / 255)
82 | elif dataset == "fmnist":
83 | cfgs = dict(test_step_size=0.01, test_epsilon=0.3)
84 | elif dataset == "svhn" or dataset == "tiny":
85 | cfgs = dict(test_step_size=0.01, test_epsilon=0.3)
86 |
87 | correct_ghost = 0.0
88 | correct = 0.0
89 | total = 0.0
90 | substitute_net.eval()
91 | adversary = LinfBasicIterativeAttack(
92 | substitute_net, loss_fn=torch.nn.CrossEntropyLoss(reduction="sum"), eps=cfgs['test_epsilon'],
93 | nb_iter=120, eps_iter=cfgs['test_step_size'], clip_min=0.0, clip_max=1.0,
94 | targeted=False)
95 |
96 | for inputs, labels in loader:
97 | inputs, labels = inputs.cuda(), labels.cuda()
98 | total += labels.size(0)
99 | t_label = cal_label(original_net, inputs)
100 | idx = torch.where(t_label == labels)[0]
101 | correct += idx.shape[0]
102 | adv_inputs_ghost = adversary.perturb(inputs[idx], labels[idx])
103 | predicted = cal_label(original_net, adv_inputs_ghost)
104 | correct_ghost += (predicted != labels[idx]).sum()
105 | # print('Attack success rate: {}, clean acc: {}'.format(100. * correct_ghost / correct, 100 * correct / total))
106 | return 100. * correct_ghost / correct, 100 * correct / total
107 |
108 |
109 | def setup_seed(seed):
110 | torch.manual_seed(seed)
111 | torch.cuda.manual_seed_all(seed)
112 | torch.cuda.manual_seed(seed)
113 | np.random.seed(seed)
114 | random.seed(seed)
115 | cudnn.deterministic = True
116 |
117 |
118 | def test(model, test_loader):
119 | model.eval()
120 | test_loss = 0
121 | correct = 0
122 | total = 0
123 | with torch.no_grad():
124 | for data, target in test_loader:
125 | data, target = data.cuda(), target.cuda()
126 | output = model(data)
127 | test_loss += F.cross_entropy(output, target, size_average=False).item() # sum up batch loss
128 | total += data.shape[0]
129 | pred = torch.max(output, 1)[1]
130 | correct += pred.eq(target.view_as(pred)).sum().item()
131 |
132 | test_loss /= total
133 | acc = 100. * correct / total
134 | return acc, test_loss
135 |
136 |
137 | def print_log(strs, log):
138 | print(strs)
139 | log.write(strs)
140 |
141 |
142 | def get_dataset(dataset):
143 | data_dir = '/mnt/lustre/share_data/zhangjie/'
144 | if dataset == "mnist":
145 | train_dataset = datasets.MNIST(data_dir, train=True,
146 | transform=transforms.Compose(
147 | [transforms.ToTensor()]))
148 | test_dataset = datasets.MNIST(data_dir, train=False,
149 | transform=transforms.Compose([
150 | transforms.ToTensor(),
151 | ]))
152 | elif dataset == "fmnist":
153 | train_dataset = datasets.FashionMNIST(data_dir, train=True,
154 | transform=transforms.Compose(
155 | [transforms.ToTensor()]))
156 | test_dataset = datasets.FashionMNIST(data_dir, train=False,
157 | transform=transforms.Compose([
158 | transforms.ToTensor(),
159 | ]))
160 | elif dataset == "svhn":
161 | train_dataset = datasets.SVHN(data_dir, split="train",
162 | transform=transforms.Compose(
163 | [transforms.ToTensor()]))
164 | test_dataset = datasets.SVHN(data_dir, split="test",
165 | transform=transforms.Compose([
166 | transforms.ToTensor(),
167 | ]))
168 | elif dataset == "cifar10":
169 | train_dataset = datasets.CIFAR10(data_dir, train=True,
170 | transform=transforms.Compose(
171 | [
172 | transforms.RandomCrop(32, padding=4),
173 | transforms.RandomHorizontalFlip(),
174 | transforms.ToTensor(),
175 | ]))
176 | test_dataset = datasets.CIFAR10(data_dir, train=False,
177 | transform=transforms.Compose([
178 | transforms.ToTensor(),
179 | ]))
180 | elif dataset == "cifar100":
181 | train_dataset = datasets.CIFAR100(data_dir, train=True,
182 | transform=transforms.Compose(
183 | [
184 | transforms.RandomCrop(32, padding=4),
185 | transforms.RandomHorizontalFlip(),
186 | transforms.ToTensor(),
187 | ]))
188 | test_dataset = datasets.CIFAR100(data_dir, train=False,
189 | transform=transforms.Compose([
190 | transforms.ToTensor(),
191 | ]))
192 | elif dataset == "tiny":
193 | data_transforms = {
194 | 'train': transforms.Compose([
195 | transforms.RandomRotation(20),
196 | transforms.RandomHorizontalFlip(0.5),
197 | transforms.ToTensor(),
198 | ]),
199 | 'val': transforms.Compose([
200 | transforms.ToTensor(),
201 | ]),
202 | 'test': transforms.Compose([
203 | transforms.ToTensor(),
204 | ])
205 | }
206 | data_dir = "data/tiny-imagenet-200/"
207 | image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])
208 | for x in ['train', 'val', 'test']}
209 | train_dataset = image_datasets['train']
210 | test_dataset = image_datasets['val']
211 | # train_loader = data.DataLoader(image_datasets['train'], batch_size=128, shuffle=True, num_workers=4)
212 | # val_loader = data.DataLoader(image_datasets['val'], batch_size=128, shuffle=False, num_workers=4)
213 |
214 | else:
215 | raise NotImplementedError
216 |
217 | train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=256,
218 | shuffle=True, num_workers=4)
219 | test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=256,
220 | shuffle=False, num_workers=4)
221 |
222 | return train_loader, test_loader
223 |
224 |
225 | class ScoreLoss(torch.nn.Module):
226 | def __init__(self, reduction='mean'):
227 | super(ScoreLoss, self).__init__()
228 | self.reduction = reduction
229 |
230 | def forward(self, logits, target):
231 | if logits.dim() > 2:
232 | logits = logits.view(logits.size(0), logits.size(1), -1) # [N, C, HW]
233 | logits = logits.transpose(1, 2) # [N, HW, C]
234 | logits = logits.contiguous().view(-1, logits.size(2)) # [NHW, C]
235 | target = target.view(-1, 1) # [NHW,1]
236 |
237 | score = F.log_softmax(logits, 1) # score-based
238 | score = score.gather(1, target) # [NHW, 1]
239 | loss = -1 * score
240 |
241 | if self.reduction == 'mean':
242 | loss = loss.mean()
243 | elif self.reduction == 'sum':
244 | loss = loss.sum()
245 | return loss
246 |
247 | def save_checkpoint(state, is_best, filename='checkpoint.pth'):
248 | if is_best:
249 | torch.save(state, filename)
250 |
251 | def reset_model(model):
252 | for m in model.modules():
253 | if isinstance(m, (nn.ConvTranspose2d, nn.Linear, nn.Conv2d)):
254 | nn.init.normal_(m.weight, 0.0, 0.02)
255 | if m.bias is not None:
256 | nn.init.constant_(m.bias, 0)
257 | if isinstance(m, (nn.BatchNorm2d)):
258 | nn.init.normal_(m.weight, 1.0, 0.02)
259 | nn.init.constant_(m.bias, 0)
260 |
261 |
262 | class MultiTransform:
263 | """Create two crops of the same image"""
264 |
265 | def __init__(self, transform):
266 | self.transform = transform
267 |
268 | def __call__(self, x):
269 | return [t(x) for t in self.transform]
270 |
271 | def __repr__(self):
272 | return str(self.transform)
273 |
274 |
275 | def pack_images(images, col=None, channel_last=False, padding=1):
276 | # N, C, H, W
277 | if isinstance(images, (list, tuple)):
278 | images = np.stack(images, 0)
279 | if channel_last:
280 | images = images.transpose(0, 3, 1, 2) # make it channel first
281 | assert len(images.shape) == 4
282 | assert isinstance(images, np.ndarray)
283 |
284 | N, C, H, W = images.shape
285 | if col is None:
286 | col = int(math.ceil(math.sqrt(N)))
287 | row = int(math.ceil(N / col))
288 |
289 | pack = np.zeros((C, H * row + padding * (row - 1), W * col + padding * (col - 1)), dtype=images.dtype)
290 | for idx, img in enumerate(images):
291 | h = (idx // col) * (H + padding)
292 | w = (idx % col) * (W + padding)
293 | pack[:, h:h + H, w:w + W] = img
294 | return pack
295 |
296 |
297 | def save_image_batch(imgs, output, col=None, size=None, pack=True):
298 | if isinstance(imgs, torch.Tensor):
299 | imgs = (imgs.detach().clamp(0, 1).cpu().numpy() * 255).astype('uint8')
300 | base_dir = os.path.dirname(output)
301 | if base_dir != '':
302 | os.makedirs(base_dir, exist_ok=True)
303 | if pack:
304 | imgs = pack_images(imgs, col=col).transpose(1, 2, 0).squeeze()
305 | imgs = Image.fromarray(imgs)
306 | if size is not None:
307 | if isinstance(size, (list, tuple)):
308 | imgs = imgs.resize(size)
309 | else:
310 | w, h = imgs.size
311 | max_side = max(h, w)
312 | scale = float(size) / float(max_side)
313 | _w, _h = int(w * scale), int(h * scale)
314 | imgs = imgs.resize([_w, _h])
315 | imgs.save(output)
316 | else:
317 | output_filename = output.strip('.png')
318 | for idx, img in enumerate(imgs):
319 | if img.shape[0] == 1:
320 | img = Image.fromarray(img[0])
321 | else:
322 | img = Image.fromarray(img.transpose(1, 2, 0))
323 | img.save(output_filename + '-%d.png' % (idx))
324 |
325 |
326 | def _collect_all_images(root, postfix=['png', 'jpg', 'jpeg', 'JPEG']):
327 | images = []
328 | if isinstance(postfix, str):
329 | postfix = [postfix]
330 | for dirpath, dirnames, files in os.walk(root): # '/dockerdata/cvpr/10-28/ft_local/run/svhn_4',[],files(all imgs)
331 | files.sort()
332 | files = files[-256 * 400:]
333 | # files = files[-2048 * 400:]
334 | for pos in postfix:
335 | for f in files:
336 | if f.endswith(pos):
337 | images.append(os.path.join(dirpath, f))
338 | return images
339 |
340 |
341 | class UnlabeledImageDataset(torch.utils.data.Dataset):
342 | def __init__(self, root, transform=None):
343 | self.root = os.path.abspath(root)
344 | self.images = _collect_all_images(self.root) # [ os.path.join(self.root, f) for f in os.listdir( root ) ]
345 | self.transform = transform
346 |
347 | def __getitem__(self, idx):
348 | img = Image.open(self.images[idx])
349 | if self.transform:
350 | img = self.transform(img)
351 | return img
352 |
353 | def __len__(self):
354 | return len(self.images)
355 |
356 | def __repr__(self):
357 | return 'Unlabeled data:\n\troot: %s\n\tdata mount: %d\n\ttransforms: %s' % (
358 | self.root, len(self), self.transform)
359 |
360 |
361 | class ImagePool(object):
362 | def __init__(self, root):
363 | self.root = os.path.abspath(root)
364 | os.makedirs(self.root, exist_ok=True)
365 | self._idx = 0
366 |
367 | def add(self, imgs, targets=None):
368 | save_image_batch(imgs, os.path.join(self.root, "%d.png" % (self._idx)), pack=False)
369 | self._idx += 1
370 |
371 | def get_dataset(self, transform=None, labeled=True):
372 | return UnlabeledImageDataset(self.root, transform=transform)
373 |
374 |
--------------------------------------------------------------------------------