-
Notifications
You must be signed in to change notification settings - Fork 2
/
Trainer_Teacher.py
211 lines (167 loc) · 9.17 KB
/
Trainer_Teacher.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
import math
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
import torch
running_loss_tea = 0
running_loss_focal_sub = 0
running_loss_ensemble = 0
def cross_entropy2d(input, target, temperature=1, weight=None, size_average=True):
n, c, h, w = input.size()
input = input.transpose(1, 2).transpose(2, 3).contiguous()
input = input[target.view(n, h, w, 1).repeat(1, 1, 1, c) >= 0]
input = input.view(-1, c)
# target: (n*h*w,)
mask = target >= 0
target = target[mask]
T = temperature
loss = F.cross_entropy(input / T, target, weight=weight, size_average=False)
if size_average:
loss /= mask.data.sum()
return loss
def KD_KLDivLoss(Stu_output, Tea_output, temperature):
T = temperature
KD_loss = nn.KLDivLoss()(F.log_softmax(Stu_output/T, dim=1), F.softmax(Tea_output/T, dim=1))
KD_loss = (T * T) * KD_loss
return KD_loss
class Trainer(object):
def __init__(self, cuda,
model_focal, model_focal_sub, model_clstm,
optimizer_focal, optimizer_focal_sub, optimizer_clstm,
train_loader, max_iter, snapshot, outpath, sshow, size_average=False):
self.cuda = cuda
self.model_focal = model_focal
self.model_focal_sub = model_focal_sub
self.model_clstm = model_clstm
self.optim_focal = optimizer_focal
self.optim_focal_sub = optimizer_focal_sub
self.optim_clstm = optimizer_clstm
self.train_loader = train_loader
self.epoch = 0
self.iteration = 0
self.max_iter = max_iter
self.snapshot = snapshot
self.outpath = outpath
self.sshow = sshow
self.size_average = size_average
def train_epoch(self):
for batch_idx, (data, target, focal) in enumerate(self.train_loader):
iteration = batch_idx + self.epoch * len(self.train_loader)
if self.iteration != 0 and (iteration - 1) != self.iteration:
continue # for resuming
self.iteration = iteration
if self.iteration >= self.max_iter:
break
if self.cuda:
data, target, focal = data.cuda(), target.cuda(), focal.cuda()
data, target, focal = Variable(data), Variable(target), Variable(focal)
basize, dime, height, width = focal.size() # 2*36*256*256
focal = focal.view(1, basize, dime, height, width).transpose(0, 1) # 2*1*36*256*256
focal = torch.cat(torch.chunk(focal, 12, dim=2), dim=1) # 2*12*3*256*256
focal = torch.cat(torch.chunk(focal, basize, dim=0), dim=1).squeeze() # 24* 3x256x256
self.optim_focal.zero_grad()
self.optim_focal_sub.zero_grad()
self.optim_clstm.zero_grad()
# ----------------------------- Teacher Net's output supervised -------------------------- #
# >>>> FocalNet's output
score_focal = self.model_focal(focal) # FocalNet's output
score_pre = self.model_focal_sub(score_focal)
score_pred1, score_pred2, score_pred3, score_pred4, score_pred5, score_pred6, \
score_pred7, score_pred8, score_pred9, score_pred10, score_pred11, score_pred12 = torch.chunk(score_pre, 12, dim=0)
# -------------------------------- refinement and supervised -----------------------------------------#
## part_sub1 ##
loss1 = cross_entropy2d(score_pred1, target, size_average=self.size_average)
## part_sub2 ##
loss2 = cross_entropy2d(score_pred2, target, size_average=self.size_average)
## part_sub3 ##
loss3 = cross_entropy2d(score_pred3, target, size_average=self.size_average)
## part_sub4 ##
loss4 = cross_entropy2d(score_pred4, target, size_average=self.size_average)
## part_sub5 ##
loss5 = cross_entropy2d(score_pred5, target, size_average=self.size_average)
## part_sub6 ##
loss6 = cross_entropy2d(score_pred6, target, size_average=self.size_average)
## part_sub7 ##
loss7 = cross_entropy2d(score_pred7, target, size_average=self.size_average)
## part_sub8 ##
loss8 = cross_entropy2d(score_pred8, target, size_average=self.size_average)
## part_sub9 ##
loss9 = cross_entropy2d(score_pred9, target, size_average=self.size_average)
## part_sub10 ##
loss10 = cross_entropy2d(score_pred10, target, size_average=self.size_average)
## part_sub11 ##
loss11 = cross_entropy2d(score_pred11, target, size_average=self.size_average)
## part_sub12 ##
loss12 = cross_entropy2d(score_pred12, target, size_average=self.size_average)
loss_ensmeble = 0.0
MSELoss = nn.MSELoss(reduce=True, size_average=False)
for i in range(12):
for j in range(i+1, 12):
loss_ensmeble += MSELoss(score_pre[i,:,:,:], score_pre[j,:,:,:])
loss_ensmeble = loss_ensmeble / 66
loss_focal = (loss1 + loss2 + loss3 + loss4 + loss5 + loss6 + loss7 + loss8 + loss9 + loss10 + loss11 + loss12) / 12
loss_focal_En = torch.abs(loss_focal - 0.1*loss_ensmeble)
loss_focal.backward(retain_graph=True)
self.optim_focal_sub.step()
self.optim_focal.step()
loss_focal_En.backward(retain_graph=True)
self.optim_focal.step()
score_focal_clstm = self.model_clstm(score_focal) # Final output
teacher_loss = cross_entropy2d(score_focal_clstm, target, temperature=20, size_average=self.size_average)
teacher_loss.backward()
self.optim_clstm.step()
self.optim_focal.step()
global running_loss_tea
global running_loss_focal_sub
global running_loss_ensemble
running_loss_tea += teacher_loss.item()
running_loss_focal_sub += loss_focal.item()
running_loss_ensemble += loss_ensmeble.item()
if iteration % self.sshow == (self.sshow - 1):
print(
'\n [%3d, %6d, Teacher loss: %.3f]' % (
self.epoch + 1, iteration + 1,
running_loss_tea / self.sshow,
))
running_loss_tea = 0.0
running_loss_focal_sub = 0.0
running_loss_ensemble = 0.0
if iteration <= 0:
if iteration % self.snapshot == (self.snapshot - 1):
savename_focal = ('%s/focal_snapshot_iter_%d.pth' % (self.outpath, iteration + 1))
torch.save(self.model_focal.state_dict(), savename_focal)
print('save: (snapshot_focal: %d)' % (iteration + 1))
savename_clstm = ('%s/clstm_snapshot_iter_%d.pth' % (self.outpath, iteration + 1))
torch.save(self.model_clstm.state_dict(), savename_clstm)
print('save: (snapshot_clstm: %d)' % (iteration + 1))
savename_focal_sub = ('%s/focal_sub_snapshot_iter_%d.pth' % (self.outpath, iteration + 1))
torch.save(self.model_focal_sub.state_dict(), savename_focal_sub)
print('save: (snapshot_focal_sub: %d)' % (iteration + 1))
else:
if iteration % 4000 == (4000 - 1):
savename_focal = ('%s/focal_snapshot_iter_%d.pth' % (self.outpath, iteration + 1))
torch.save(self.model_focal.state_dict(), savename_focal)
print('save: (snapshot_focal: %d)' % (iteration + 1))
savename_clstm = ('%s/clstm_snapshot_iter_%d.pth' % (self.outpath, iteration + 1))
torch.save(self.model_clstm.state_dict(), savename_clstm)
print('save: (snapshot_clstm: %d)' % (iteration + 1))
savename_focal_sub = ('%s/focal_sub_snapshot_iter_%d.pth' % (self.outpath, iteration + 1))
torch.save(self.model_focal_sub.state_dict(), savename_focal_sub)
print('save: (snapshot_focal_sub: %d)' % (iteration + 1))
if (iteration + 1) == self.max_iter:
savename_focal = ('%s/focal_snapshot_iter_%d.pth' % (self.outpath, iteration + 1))
torch.save(self.model_focal.state_dict(), savename_focal)
print('save: (snapshot_focal: %d)' % (iteration + 1))
savename_clstm = ('%s/clstm_snapshot_iter_%d.pth' % (self.outpath, iteration + 1))
torch.save(self.model_clstm.state_dict(), savename_clstm)
print('save: (snapshot_clstm: %d)' % (iteration + 1))
savename_focal_sub = ('%s/focal_sub_snapshot_iter_%d.pth' % (self.outpath, iteration + 1))
torch.save(self.model_focal_sub.state_dict(), savename_focal_sub)
print('save: (snapshot_focal_sub: %d)' % (iteration + 1))
def train(self):
max_epoch = int(math.ceil(1. * self.max_iter / len(self.train_loader)))
for epoch in range(max_epoch):
self.epoch = epoch
self.train_epoch()
if self.iteration >= self.max_iter:
break