-
Notifications
You must be signed in to change notification settings - Fork 8
/
algorithm.py
268 lines (218 loc) · 10.2 KB
/
algorithm.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
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.
# ==============================================================================
import os
import itertools
import torch
import torch.nn.functional as F
from tensorboardX import SummaryWriter
from utils.outils import progress_bar, AverageMeter, accuracy, getCi
from utils.utils import to_device
class Algorithm:
"""
Algorithm logic is implemented here with training and validation functions etc.
:param args: experimental configurations
:type args: EasyDict
:param logger: logger
:param netFeat: feature network
:type netFeat: class `WideResNet` or `ConvNet_4_64`
:param netSIB: Classifier/decoder
:type netSIB: class `ClassifierSIB`
:param optimizer: optimizer
:type optimizer: torch.optim.SGD
:param criterion: loss
:type criterion: nn.CrossEntropyLoss
"""
def __init__(self, args, logger, netFeat, netSIB, optimizer, criterion):
self.netFeat = netFeat
self.netSIB = netSIB
self.optimizer = optimizer
self.criterion = criterion
self.nbIter = args.nbIter
self.nStep = args.nStep
self.outDir = args.outDir
self.nFeat = args.nFeat
self.batchSize = args.batchSize
self.nEpisode = args.nEpisode
self.momentum = args.momentum
self.weightDecay = args.weightDecay
self.logger = logger
self.device = torch.device('cuda' if args.cuda else 'cpu')
# Load pretrained model
if args.resumeFeatPth :
if args.cuda:
param = torch.load(args.resumeFeatPth)
else:
param = torch.load(args.resumeFeatPth, map_location='cpu')
self.netFeat.load_state_dict(param)
msg = '\nLoading netFeat from {}'.format(args.resumeFeatPth)
self.logger.info(msg)
if args.test:
self.load_ckpt(args.ckptPth)
def load_ckpt(self, ckptPth):
"""
Load checkpoint from ckptPth.
:param ckptPth: the path to the ckpt
:type ckptPth: string
"""
param = torch.load(ckptPth)
self.netFeat.load_state_dict(param['netFeat'])
self.netSIB.load_state_dict(param['SIB'])
lr = param['lr']
self.optimizer = torch.optim.SGD(itertools.chain(*[self.netSIB.parameters(),]),
lr,
momentum=self.momentum,
weight_decay=self.weightDecay,
nesterov=True)
msg = '\nLoading networks from {}'.format(ckptPth)
self.logger.info(msg)
def compute_grad_loss(self, clsScore, QueryLabel):
"""
Compute the loss between true gradients and synthetic gradients.
"""
# register hooks
def require_nonleaf_grad(v):
def hook(g):
v.grad_nonleaf = g
h = v.register_hook(hook)
return h
handle = require_nonleaf_grad(clsScore)
loss = self.criterion(clsScore, QueryLabel)
loss.backward(retain_graph=True) # need to backward again
# remove hook
handle.remove()
gradLogit = self.netSIB.dni(clsScore) # B * n x nKnovel
gradLoss = F.mse_loss(gradLogit, clsScore.grad_nonleaf.detach())
return loss, gradLoss
def validate(self, valLoader, lr=None, mode='val'):
"""
Run one epoch on val-set.
:param valLoader: the dataloader of val-set
:type valLoader: class `ValLoader`
:param float lr: learning rate for synthetic GD
:param string mode: 'val' or 'train'
"""
if mode == 'test':
nEpisode = self.nEpisode
self.logger.info('\n\nTest mode: randomly sample {:d} episodes...'.format(nEpisode))
elif mode == 'val':
nEpisode = len(valLoader)
self.logger.info('\n\nValidation mode: pre-defined {:d} episodes...'.format(nEpisode))
valLoader = iter(valLoader)
else:
raise ValueError('mode is wrong!')
episodeAccLog = []
top1 = AverageMeter()
self.netFeat.eval()
#self.netSIB.eval() # set train mode, since updating bn helps to estimate better gradient
if lr is None:
lr = self.optimizer.param_groups[0]['lr']
#for batchIdx, data in enumerate(valLoader):
for batchIdx in range(nEpisode):
data = valLoader.getEpisode() if mode == 'test' else next(valLoader)
data = to_device(data, self.device)
SupportTensor, SupportLabel, QueryTensor, QueryLabel = \
data['SupportTensor'].squeeze(0), data['SupportLabel'].squeeze(0), \
data['QueryTensor'].squeeze(0), data['QueryLabel'].squeeze(0)
with torch.no_grad():
SupportFeat, QueryFeat = self.netFeat(SupportTensor), self.netFeat(QueryTensor)
SupportFeat, QueryFeat, SupportLabel = \
SupportFeat.unsqueeze(0), QueryFeat.unsqueeze(0), SupportLabel.unsqueeze(0)
clsScore = self.netSIB(SupportFeat, SupportLabel, QueryFeat, lr)
clsScore = clsScore.view(QueryFeat.shape[0] * QueryFeat.shape[1], -1)
QueryLabel = QueryLabel.view(-1)
acc1 = accuracy(clsScore, QueryLabel, topk=(1,))
top1.update(acc1[0].item(), clsScore.shape[0])
msg = 'Top1: {:.3f}%'.format(top1.avg)
progress_bar(batchIdx, nEpisode, msg)
episodeAccLog.append(acc1[0].item())
mean, ci95 = getCi(episodeAccLog)
self.logger.info('Final Perf with 95% confidence intervals: {:.3f}%, {:.3f}%'.format(mean, ci95))
return mean, ci95
def train(self, trainLoader, valLoader, lr=None, coeffGrad=0.0) :
"""
Run one epoch on train-set.
:param trainLoader: the dataloader of train-set
:type trainLoader: class `TrainLoader`
:param valLoader: the dataloader of val-set
:type valLoader: class `ValLoader`
:param float lr: learning rate for synthetic GD
:param float coeffGrad: deprecated
"""
bestAcc, ci = self.validate(valLoader, lr)
self.logger.info('Acc improved over validation set from 0% ---> {:.3f} +- {:.3f}%'.format(bestAcc,ci))
self.netSIB.train()
self.netFeat.eval()
losses = AverageMeter()
top1 = AverageMeter()
history = {'trainLoss' : [], 'trainAcc' : [], 'valAcc' : []}
for episode in range(self.nbIter):
data = trainLoader.getBatch()
data = to_device(data, self.device)
with torch.no_grad() :
SupportTensor, SupportLabel, QueryTensor, QueryLabel = \
data['SupportTensor'], data['SupportLabel'], data['QueryTensor'], data['QueryLabel']
nC, nH, nW = SupportTensor.shape[2:]
SupportFeat = self.netFeat(SupportTensor.reshape(-1, nC, nH, nW))
SupportFeat = SupportFeat.view(self.batchSize, -1, self.nFeat)
QueryFeat = self.netFeat(QueryTensor.reshape(-1, nC, nH, nW))
QueryFeat = QueryFeat.view(self.batchSize, -1, self.nFeat)
if lr is None:
lr = self.optimizer.param_groups[0]['lr']
self.optimizer.zero_grad()
clsScore = self.netSIB(SupportFeat, SupportLabel, QueryFeat, lr)
clsScore = clsScore.view(QueryFeat.shape[0] * QueryFeat.shape[1], -1)
QueryLabel = QueryLabel.view(-1)
if coeffGrad > 0:
loss, gradLoss = self.compute_grad_loss(clsScore, QueryLabel)
loss = loss + gradLoss * coeffGrad
else:
loss = self.criterion(clsScore, QueryLabel)
loss.backward()
self.optimizer.step()
acc1 = accuracy(clsScore, QueryLabel, topk=(1, ))
top1.update(acc1[0].item(), clsScore.shape[0])
losses.update(loss.item(), QueryFeat.shape[1])
msg = 'Loss: {:.3f} | Top1: {:.3f}% '.format(losses.avg, top1.avg)
if coeffGrad > 0:
msg = msg + '| gradLoss: {:.3f}%'.format(gradLoss.item())
progress_bar(episode, self.nbIter, msg)
if episode % 1000 == 999 :
acc, _ = self.validate(valLoader, lr)
if acc > bestAcc :
msg = 'Acc improved over validation set from {:.3f}% ---> {:.3f}%'.format(bestAcc , acc)
self.logger.info(msg)
bestAcc = acc
self.logger.info('Saving Best')
torch.save({
'lr': lr,
'netFeat': self.netFeat.state_dict(),
'SIB': self.netSIB.state_dict(),
'nbStep': self.nStep,
}, os.path.join(self.outDir, 'netSIBBest.pth'))
self.logger.info('Saving Last')
torch.save({
'lr': lr,
'netFeat': self.netFeat.state_dict(),
'SIB': self.netSIB.state_dict(),
'nbStep': self.nStep,
}, os.path.join(self.outDir, 'netSIBLast.pth'))
msg = 'Iter {:d}, Train Loss {:.3f}, Train Acc {:.3f}%, Val Acc {:.3f}%'.format(
episode, losses.avg, top1.avg, acc)
self.logger.info(msg)
history['trainLoss'].append(losses.avg)
history['trainAcc'].append(top1.avg)
history['valAcc'].append(acc)
losses = AverageMeter()
top1 = AverageMeter()
return bestAcc, acc, history