Uh oh!
There was an error while loading. Please reload this page.
forked from yuanchun-li/ModelDiff
- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.py
More file actions
Latest commit
216 lines (174 loc) · 6.2 KB
/
Copy pathutils.py
File metadata and controls
216 lines (174 loc) · 6.2 KB
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
importos
importos.pathasosp
importsys
importtime
importargparse
frompdbimportset_traceasst
importjson
importfunctools
importtorch
importnumpyasnp
importtorchvision
importtorch.nnasnn
importtorch.nn.functionalasF
importtorch.optimasoptim
fromtorchvisionimporttransforms
classMovingAverageMeter(object):
"""Computes and stores the average and current value"""
def__init__(self, name, fmt=':f', momentum=0.9):
self.name=name
self.fmt=fmt
self.momentum=momentum
self.reset()
defreset(self):
self.val=0
self.avg=0
self.sum=0
defupdate(self, val, n=1):
self.val=val
self.avg=self.momentum*self.avg+ (1-self.momentum)*val
def__str__(self):
fmtstr='{name} {val'+self.fmt+'} ({avg'+self.fmt+'})'
returnfmtstr.format(**self.__dict__)
classProgressMeter(object):
def__init__(self, num_batches, meters, prefix="", output_dir=None):
self.batch_fmtstr=self._get_batch_fmtstr(num_batches)
self.meters=meters
self.prefix=prefix
ifoutput_dirisnotNone:
self.filepath=osp.join(output_dir, "progress")
defdisplay(self, batch):
entries= [self.prefix+self.batch_fmtstr.format(batch)]
entries+= [str(meter) formeterinself.meters]
log_str='\t'.join(entries)
print(log_str)
# if self.filepath is not None:
# with open(self.filepath, "a") as f:
# f.write(log_str+"\n")
def_get_batch_fmtstr(self, num_batches):
num_digits=len(str(num_batches//1))
fmt='{:'+str(num_digits) +'d}'
return'['+fmt+'/'+fmt.format(num_batches) +']'
classCrossEntropyLabelSmooth(nn.Module):
def__init__(self, num_classes, epsilon=0.1):
super(CrossEntropyLabelSmooth, self).__init__()
self.num_classes=num_classes
self.epsilon=epsilon
self.logsoftmax=nn.LogSoftmax(dim=1)
defforward(self, inputs, targets):
log_probs=self.logsoftmax(inputs)
targets=torch.zeros_like(log_probs).scatter_(1, targets.unsqueeze(1), 1)
targets= (1-self.epsilon) *targets+self.epsilon/self.num_classes
loss= (-targets*log_probs).sum(1)
returnloss.mean()
deflinear_l2(model, beta_lmda):
beta_loss=0
forminmodel.modules():
ifisinstance(m, nn.Linear):
beta_loss+= (m.weight).pow(2).sum()
beta_loss+= (m.bias).pow(2).sum()
return0.5*beta_loss*beta_lmda, beta_loss
defl2sp(model, reg):
reg_loss=0
dist=0
forminmodel.modules():
ifhasattr(m, 'weight') andhasattr(m, 'old_weight'):
diff= (m.weight-m.old_weight).pow(2).sum()
dist+=diff
reg_loss+=diff
ifhasattr(m, 'bias') andhasattr(m, 'old_bias'):
diff= (m.bias-m.old_bias).pow(2).sum()
dist+=diff
reg_loss+=diff
ifdist>0:
dist=dist.sqrt()
loss= (reg*reg_loss)
returnloss, dist
defadvtest_fast(model, loader, adversary, args):
advDataset=torch.load(args.adv_data_dir)
test_loader=torch.utils.data.DataLoader(
advDataset,
batch_size=4, shuffle=False,
num_workers=0, pin_memory=False)
model.eval()
total_ce=0
total=0
top1=0
total=0
top1_clean=0
top1_adv=0
adv_success=0
adv_trial=0
fori, (batch, label, adv_batch, adv_label) inenumerate(test_loader):
batch, label=batch.to('cuda'), label.to('cuda')
adv_batch=adv_batch.to('cuda')
total+=batch.size(0)
out_clean=model(batch)
# if 'mbnetv2' in args.network:
# y = torch.zeros(batch.shape[0], model.classifier[1].in_features).cuda()
# else:
# y = torch.zeros(batch.shape[0], model.fc.in_features).cuda()
# y[:,0] = args.m
# advbatch = adversary.perturb(batch, y)
out_adv=model(adv_batch)
_, pred_clean=out_clean.max(dim=1)
_, pred_adv=out_adv.max(dim=1)
clean_correct=pred_clean.eq(label)
adv_trial+=int(clean_correct.sum().item())
adv_success+=int(pred_adv[clean_correct].eq(label[clean_correct]).sum().detach().item())
top1_clean+=int(pred_clean.eq(label).sum().detach().item())
top1_adv+=int(pred_adv.eq(label).sum().detach().item())
# print('{}/{}...'.format(i+1, len(test_loader)))
print(f"Finish adv test fast")
deltest_loader
deladvDataset
returnfloat(top1_clean)/total*100, float(top1_adv)/total*100, float(adv_trial-adv_success) /adv_trial*100
deflazy_property(func):
attribute='_lazy_'+func.__name__
@property
@functools.wraps(func)
defwrapper(self):
ifnothasattr(self, attribute):
setattr(self, attribute, func(self))
returngetattr(self, attribute)
returnwrapper
classUtils:
_instance=None
def__init__(self):
self.cache= {}
@staticmethod
def_get_instance():
ifUtils._instanceisNone:
Utils._instance=Utils()
returnUtils._instance
@staticmethod
defshow_images(images, labels, title='examples'):
plt.figure(figsize=(10,10))
plt.subplots_adjust(hspace=0.2)
forninrange(25):
plt.subplot(5,5,n+1)
img=images[n]
img=img.numpy().squeeze()
plt.imshow(img)
plt.title(f'{labels[n]}')
plt.axis('off')
_=plt.suptitle(title)
plt.show()
@staticmethod
defcopy_weights(source_model, target_model):
# print(source_model.summary())
# print(target_model.summary())
fori, layerinenumerate(target_model.layers):
ifnotlayer.get_weights():
continue
source_layer=source_model.get_layer(layer.name)
# print(layer)
# print(source_layer)
layer.set_weights(source_layer.get_weights())
returntarget_model
@staticmethod
defnormalize(v):
norm=np.linalg.norm(v)
ifnorm==0:
returnv
returnv/norm