-
Notifications
You must be signed in to change notification settings - Fork 1
/
train_owner_digit.py
286 lines (231 loc) · 9.55 KB
/
train_owner_digit.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
import os
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
from utils.getdata import Cus_Dataset
from utils.util import get_mnist_data, get_usps_data, get_svhn_data, get_mnist_m_data, add_watermark
SEED = 2023
lr = 0.0001
nepoch = 50
workers = 10
batch_size = 32
device = torch.device("cuda")
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
SOURCE = 'mnist' # mnist, usps, svhn, mnist_m
__all__ = [
'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
'vgg19_bn', 'vgg19',
]
model_urls = {
'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth',
'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth',
'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth',
'vgg11_bn': 'https://download.pytorch.org/models/vgg11_bn-6002323d.pth',
'vgg13_bn': 'https://download.pytorch.org/models/vgg13_bn-abd245e5.pth',
'vgg16_bn': 'https://download.pytorch.org/models/vgg16_bn-6c64b313.pth',
'vgg19_bn': 'https://download.pytorch.org/models/vgg19_bn-c79401a0.pth',
}
def calc_ins_mean_std(x, eps=1e-5):
"""extract feature map statistics"""
# eps is a small value added to the variance to avoid divide-by-zero.
size = x.size()
assert (len(size) == 4)
N, C = size[:2]
var = x.contiguous().view(N, C, -1).var(dim=2) + eps
std = var.sqrt().view(N, C, 1, 1)
mean = x.contiguous().view(N, C, -1).mean(dim=2).view(N, C, 1, 1)
return mean, std
class CUTI(nn.Module):
def __init__(self):
super(CUTI, self).__init__()
def forward(self, x):
if self.training:
batch_size, C = x.size()[0]//2, x.size()[1]
style_mean, style_std = calc_ins_mean_std(x[:batch_size])
conv_mean = nn.Conv2d(C, C, 1, bias=False).cuda()
conv_std = nn.Conv2d(C, C, 1, bias=False).cuda()
mean = torch.sigmoid(conv_mean(style_mean))
std = torch.sigmoid(conv_std(style_std))
x_a = x[batch_size:]*std+mean
x = torch.cat((x[:batch_size], x_a), 0)
return x
class VGG(nn.Module):
def __init__(self, features, num_classes=1000, init_weights=True):
super(VGG, self).__init__()
self.features = features
self.layer_n = len(features)
self.classifier1 = nn.Sequential(
nn.Linear(2048, 256),
nn.ReLU(True),
nn.Dropout(),
nn.Linear(256, 256),
nn.ReLU(True),
nn.Dropout(),
nn.Linear(256, num_classes),
)
if init_weights:
self._initialize_weights()
self.chan_ex = CUTI()
def forward(self, x, y=None, choice=0):
if y == None:
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.classifier1(x)
return x
elif choice % 2 == 0:
input = torch.cat((x, y), 0)
input = self.features(input)
x, y = input.chunk(2, dim=0)
x = x.view(x.size(0), -1)
x = self.classifier1(x)
y = y.view(y.size(0), -1)
y = self.classifier1(y)
return x, y
elif choice % 2 == 1:
input = torch.cat((x, y), 0)
input = self.chan_ex(self.features[:3](input))
input = self.chan_ex(self.features[3:6](input))
input = self.chan_ex(self.features[6:11](input))
input = self.chan_ex(self.features[11:16](input))
input = self.chan_ex(self.features[16:](input))
x, y = input.chunk(2, dim=0)
x = x.view(x.size(0), -1)
x = self.classifier1(x)
y = y.view(y.size(0), -1)
y = self.classifier1(y)
return x, y
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
nn.init.constant_(m.bias, 0)
def make_layers(cfg, batch_norm=False):
layers = []
in_channels = 3
for i in range(len(cfg)):
v = cfg[i]
if v == 'M':
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
if batch_norm:
layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]
else:
layers += [conv2d, nn.ReLU(inplace=True)]
in_channels = v
return nn.Sequential(*layers)
cfg = {
'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}
def vgg11(pretrained=False, **kwargs):
"""VGG 11-layer model (configuration "A")
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['A']), **kwargs)
model.load_state_dict(model_zoo.load_url(model_urls['vgg11']), strict = False)
return model
def validate_class(val_loader, model, epoch, num_class=10):
model.eval()
correct = 0
total = 0
c_class = [0 for i in range(num_class)]
t_class = [0 for i in range(num_class)]
for i, (images, labels) in enumerate(val_loader):
images = images.to(device)
labels = labels.to(device)
y_pred= model(images)
_, predicted = torch.max(y_pred.data, 1)
total += labels.size(0)
true_label = torch.argmax(labels[:,0], axis = 1)
correct += (predicted == true_label).sum().item()
for j in range(predicted.shape[0]):
t_class[true_label[j]] += 1
if predicted[j] == true_label[j]:
c_class[true_label[j]] += 1
acc = 100.0 * correct / total
print(' * EPOCH {epoch} | Ave_Accuracy: {acc:.3f}%'.format(epoch=epoch, acc=acc))
model.train()
return acc
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
def train():
num_classes = 10
# Load source datasets
if SOURCE == 'mnist':
dataset = get_mnist_data()
elif SOURCE == 'usps':
dataset = get_usps_data()
elif SOURCE == 'svhn':
dataset = get_svhn_data()
elif SOURCE == 'mnist_m':
dataset = get_mnist_m_data()
data_patch = add_watermark(get_mnist_data(), 32, 80) # 32,20
print('datasets loaded!')
PATH = 'D:/WLY/Documents/NUAA/CVPR/github/' + SOURCE + '_ownership-verification.pth'
datafile = Cus_Dataset(mode='train', dataset_1=dataset, begin_ind1=0, size1=5000,
dataset_2=data_patch, begin_ind2=0, size2=5000)
datafile_val1 = Cus_Dataset(mode='val', dataset_1=dataset, begin_ind1=5000, size1=1000)
datafile_val2 = Cus_Dataset(mode='val', dataset_1=data_patch, begin_ind1=5000, size1=1000)
valloader1 = DataLoader(datafile_val1, batch_size=batch_size, shuffle=True, num_workers=workers, drop_last=True)
valloader2 = DataLoader(datafile_val2, batch_size=batch_size, shuffle=True, num_workers=workers, drop_last=True)
dataloader = DataLoader(datafile, batch_size=batch_size, shuffle=True, num_workers=workers, drop_last=True)
model = vgg11(pretrained=True, num_classes=num_classes)
model.cuda()
model.train()
optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=lr)
lambda1 = lambda epoch:0.999**epoch
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda1)
criterion_KL = torch.nn.KLDivLoss()
for epoch in range(nepoch):
for i, (img1, label1, img2, label2) in enumerate(dataloader):
img1, label1, img2, label2 = img1.to(device), label1.to(device), img2.to(device), label2.to(device)
img1.float()
label1 = label1.float()
img2.float()
label2 = label2.float()
out1, out2 = model(img1, img2, i)
out1 = F.log_softmax(out1, dim=1)
loss1 = criterion_KL(out1, label1)
out2 = F.log_softmax(out2, dim=1)
loss2 = criterion_KL(out2, label2)
alpha = 0.1
loss2 = loss2 * alpha
if loss2 > 1:
loss2 = torch.clamp(loss2, 0, 1)
loss = loss1 - loss2
loss.backward()
optimizer.step()
optimizer.zero_grad()
scheduler.step()
acc1 = validate_class(valloader1, model, epoch, num_class=num_classes)
acc2 = validate_class(valloader2, model, epoch, num_class=num_classes)
f = open(PATH.split('.')[0] + '.txt', "a+")
f.write("epoch = {:02d}, acc_s = {:.3f}, acc_t = {:.3f}".format(epoch, acc1, acc2) + '\n')
f.close()
torch.save(model.state_dict(), PATH)
if __name__ == "__main__":
setup_seed(SEED)
train()