-
Notifications
You must be signed in to change notification settings - Fork 0
/
passport_attack_3.py
381 lines (305 loc) · 12.7 KB
/
passport_attack_3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import json
import os
import time
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
from dataset import prepare_dataset
from experiments.utils import construct_passport_kwargs_from_dict
from models.alexnet_passport import AlexNetPassport
from models.alexnet_passport_private import AlexNetPassportPrivate
from models.layers.passportconv2d import PassportBlock
from models.layers.passportconv2d_private import PassportPrivateBlock
from models.losses.sign_loss import SignLoss
from models.resnet_passport import ResNet18Passport
from models.resnet_passport_private import ResNet18Private
class DatasetArgs():
pass
def train_maximize(origpassport, fakepassport, model, optimizer, criterion, trainloader, device, scheme):
model.train()
loss_meter = 0
signloss_meter = 0
maximizeloss_meter = 0
mseloss_meter = 0
csloss_meter = 0
acc_meter = 0
signacc_meter = 0
start_time = time.time()
mse_criterion = nn.MSELoss()
cs_criterion = nn.CosineSimilarity()
for k, (d, t) in enumerate(trainloader):
d = d.to(device)
t = t.to(device)
optimizer.zero_grad()
if scheme == 1:
pred = model(d)
else:
pred = model(d, ind=1)
loss = criterion(pred, t)
signloss = torch.tensor(0.).to(device)
signacc = torch.tensor(0.).to(device)
count = 0
for m in model.modules():
if isinstance(m, SignLoss):
signloss += m.loss
signacc += m.acc
count += 1
maximizeloss = torch.tensor(0.).to(device)
mseloss = torch.tensor(0.).to(device)
csloss = torch.tensor(0.).to(device)
for l, r in zip(origpassport, fakepassport):
mse = mse_criterion(l, r)
cs = cs_criterion(l.view(1, -1), r.view(1, -1)).mean()
csloss += cs
mseloss += mse
maximizeloss += 1 / mse
(loss + signloss + maximizeloss).backward()
torch.nn.utils.clip_grad_norm_(fakepassport, 2)
optimizer.step()
acc = (pred.max(dim=1)[1] == t).float().mean()
loss_meter += loss.item()
acc_meter += acc.item()
signloss_meter += signloss.item()
signacc_meter += signacc.item() / count
maximizeloss_meter += maximizeloss.item()
mseloss_meter += mseloss.item()
csloss_meter += csloss.item()
print(f'Batch [{k + 1}/{len(trainloader)}]: '
f'Loss: {loss_meter / (k + 1):.4f} '
f'Acc: {acc_meter / (k + 1):.4f} '
f'Sign Loss: {signloss_meter / (k + 1):.4f} '
f'Sign Acc: {signacc_meter / (k + 1):.4f} '
f'MSE Loss: {mseloss_meter / (k + 1):.4f} '
f'Maximize Dist: {maximizeloss_meter / (k + 1):.4f} '
f'CS: {csloss_meter / (k + 1):.4f} ({time.time() - start_time:.2f}s)',
end='\r')
print()
loss_meter /= len(trainloader)
acc_meter /= len(trainloader)
signloss_meter /= len(trainloader)
signacc_meter /= len(trainloader)
maximizeloss_meter /= len(trainloader)
mseloss_meter /= len(trainloader)
csloss_meter /= len(trainloader)
return {'loss': loss_meter,
'signloss': signloss_meter,
'acc': acc_meter,
'signacc': signacc_meter,
'maximizeloss': maximizeloss_meter,
'mseloss': mseloss_meter,
'csloss': csloss_meter,
'time': start_time - time.time()}
def test(model, criterion, valloader, device, scheme):
model.eval()
loss_meter = 0
signloss_meter = 0
acc_meter = 0
signacc_meter = 0
start_time = time.time()
with torch.no_grad():
for k, (d, t) in enumerate(valloader):
d = d.to(device)
t = t.to(device)
if scheme == 1:
pred = model(d)
else:
pred = model(d, ind=1)
loss = criterion(pred, t)
signloss = torch.tensor(0.).to(device)
signacc = torch.tensor(0.).to(device)
count = 0
for m in model.modules():
if isinstance(m, SignLoss):
signloss += m.get_loss()
signacc += m.get_acc()
count += 1
acc = (pred.max(dim=1)[1] == t).float().mean()
loss_meter += loss.item()
acc_meter += acc.item()
signloss_meter += signloss.item()
try:
signacc_meter += signacc.item() / count
except:
pass
print(f'Batch [{k + 1}/{len(valloader)}]: '
f'Loss: {loss_meter / (k + 1):.4f} '
f'Acc: {acc_meter / (k + 1):.4f} '
f'Sign Loss: {signloss_meter / (k + 1):.4f} '
f'Sign Acc: {signacc_meter / (k + 1):.4f} ({time.time() - start_time:.2f}s)',
end='\r')
print()
loss_meter /= len(valloader)
acc_meter /= len(valloader)
signloss_meter /= len(valloader)
signacc_meter /= len(valloader)
return {'loss': loss_meter,
'signloss': signloss_meter,
'acc': acc_meter,
'signacc': signacc_meter,
'time': time.time() - start_time}
def run_maximize(rep=1, flipperc=0, arch='alexnet', dataset='cifar10', scheme=1,
loadpath='', passport_config='', tagnum=1):
epochs = {
'imagenet1000': 30
}.get(dataset, 100)
batch_size = 64
nclass = {
'cifar100': 100,
'imagenet1000': 1000
}.get(dataset, 10)
inchan = 3
lr = 0.01
device = torch.device('cuda')
trainloader, valloader = prepare_dataset({'transfer_learning': False,
'dataset': dataset,
'tl_dataset': '',
'batch_size': batch_size})
passport_kwargs = construct_passport_kwargs_from_dict({'passport_config': json.load(open(passport_config)),
'norm_type': 'bn',
'sl_ratio': 0.1,
'key_type': 'shuffle'})
if arch == 'alexnet':
if scheme == 1:
model = AlexNetPassport(inchan, nclass, passport_kwargs)
else:
model = AlexNetPassportPrivate(inchan, nclass, passport_kwargs)
else:
if scheme == 1:
model = ResNet18Passport(num_classes=nclass, passport_kwargs=passport_kwargs)
else:
model = ResNet18Private(num_classes=nclass, passport_kwargs=passport_kwargs)
sd = torch.load(loadpath)
model.load_state_dict(sd)
for param in model.parameters():
param.requires_grad_(False)
passblocks = []
origpassport = []
fakepassport = []
for m in model.modules():
if isinstance(m, PassportBlock) or isinstance(m, PassportPrivateBlock):
passblocks.append(m)
if scheme == 1:
keyname = 'key'
skeyname = 'skey'
else:
keyname = 'key_private'
skeyname = 'skey_private'
key, skey = m.__getattr__(keyname).data.clone(), m.__getattr__(skeyname).data.clone()
origpassport.append(key.to(device))
origpassport.append(skey.to(device))
m.__delattr__(keyname)
m.__delattr__(skeyname)
# re-initialize the key and skey, but by adding noise on it
m.register_parameter(keyname, nn.Parameter(key.clone() + torch.randn(*key.size()) * 0.001))
m.register_parameter(skeyname, nn.Parameter(skey.clone() + torch.randn(*skey.size()) * 0.001))
fakepassport.append(m.__getattr__(keyname))
fakepassport.append(m.__getattr__(skeyname))
if flipperc != 0:
print(f'Reverse {flipperc * 100:.2f}% of binary signature')
for m in passblocks:
mflip = flipperc
if scheme == 1:
oldb = m.sign_loss.b
else:
oldb = m.sign_loss_private.b
newb = oldb.clone()
npidx = np.arange(len(oldb))
randsize = int(oldb.view(-1).size(0) * mflip)
randomidx = np.random.choice(npidx, randsize, replace=False)
newb[randomidx] = oldb[randomidx] * -1 # reverse bit
if scheme == 1:
m.sign_loss.set_b(newb)
else:
m.sign_loss_private.set_b(newb)
model.to(device)
optimizer = torch.optim.SGD(fakepassport,
lr=lr,
momentum=0.9,
weight_decay=0.0005)
# scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer,
# [int(epochs * 0.5), int(epochs * 0.75)],
# 0.1)
scheduler = None
criterion = nn.CrossEntropyLoss()
history = []
dirname = f'logs/passport_attack_3/{loadpath.split("/")[1]}/{loadpath.split("/")[2]}'
os.makedirs(dirname, exist_ok=True)
def run_cs():
cs = []
for d1, d2 in zip(origpassport, fakepassport):
d1 = d1.view(d1.size(0), -1)
d2 = d2.view(d2.size(0), -1)
cs.append(F.cosine_similarity(d1, d2).item())
return cs
print('Before training')
res = {}
valres = test(model, criterion, valloader, device, scheme)
for key in valres: res[f'valid_{key}'] = valres[key]
with torch.no_grad():
cs = run_cs()
mseloss = 0
for l, r in zip(origpassport, fakepassport):
mse = F.mse_loss(l, r)
mseloss += mse.item()
mseloss /= len(origpassport)
print(f'MSE of Real and Maximize passport: {mseloss:.4f}')
print(f'Cosine Similarity of Real and Maximize passport: {sum(cs) / len(origpassport):.4f}')
print()
res['epoch'] = 0
res['cosine_similarity'] = cs
res['flipperc'] = flipperc
res['train_mseloss'] = mseloss
history.append(res)
torch.save({'origpassport': origpassport,
'fakepassport': fakepassport,
'state_dict': model.state_dict()},
f'{dirname}/{arch}-{scheme}-last-{dataset}-{rep}-{tagnum}-{flipperc:.1f}-e0.pth')
for ep in range(1, epochs + 1):
if scheduler is not None:
scheduler.step()
print(f'Learning rate: {optimizer.param_groups[0]["lr"]}')
print(f'Epoch {ep:3d}:')
print('Training')
trainres = train_maximize(origpassport, fakepassport, model, optimizer, criterion, trainloader, device, scheme)
print('Testing')
valres = test(model, criterion, valloader, device, scheme)
res = {}
for key in trainres: res[f'train_{key}'] = trainres[key]
for key in valres: res[f'valid_{key}'] = valres[key]
res['epoch'] = ep
res['flipperc'] = flipperc
with torch.no_grad():
cs = run_cs()
res['cosine_similarity'] = cs
print(f'Cosine Similarity of Real and Maximize passport: '
f'{sum(cs) / len(origpassport):.4f}')
print()
history.append(res)
torch.save({'origpassport': origpassport,
'fakepassport': fakepassport,
'state_dict': model.state_dict()},
f'{dirname}/{arch}-{scheme}-{dataset}-{rep}-{tagnum}-{flipperc:.1f}-last.pth')
histdf = pd.DataFrame(history)
histdf.to_csv(f'{dirname}/{arch}-{scheme}-history-{dataset}-{rep}-{tagnum}-{flipperc:.1f}.csv')
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(
description='fake attack 3: create another passport maximized from current passport')
parser.add_argument('--rep', default=1, type=int,
help='training id')
parser.add_argument('--arch', default='alexnet', choices=['alexnet', 'resnet18'])
parser.add_argument('--dataset', default='cifar10', choices=['cifar10', 'cifar100', 'imagenet1000'])
parser.add_argument('--flipperc', default=0, type=float,
help='flip percentange 0~1')
parser.add_argument('--scheme', default=1, choices=[1, 2, 3], type=int)
parser.add_argument('--loadpath', default='', help='path to model to be attacked')
parser.add_argument('--passport-config', default='', help='path to passport config')
parser.add_argument('--tagnum', default=torch.randint(100000, ()).item(), type=int,
help='tag number of the experiment')
args = parser.parse_args()
run_maximize(args.rep, args.flipperc,
args.arch, args.dataset,
args.scheme, args.loadpath,
args.passport_config, args.tagnum)