-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTrainer_Student.py
159 lines (123 loc) · 6.87 KB
/
Trainer_Student.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
import math
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
import torch
running_loss_stu_hard = 0
running_loss_stu_soft = 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, student,
model_focal, model_focal_sub, model_clstm, optimizer_student,
train_loader, max_iter, snapshot, outpath, sshow, size_average=False):
self.cuda = cuda
self.student = student
self.model_focal = model_focal
self.model_focal_sub = model_focal_sub
self.model_clstm = model_clstm
self.optim_student = optimizer_student
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_student.zero_grad()
# ----------------------------- Teacher Net'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)
score_focal_clstm = self.model_clstm(score_focal) # Final output
# ----------------------------- Student Net's output supervised -------------------------- #
score_student, focus_student = self.student(data)
Hardloss_student = cross_entropy2d(score_student, target, size_average=self.size_average)
KD_loss = KD_KLDivLoss(score_student, score_focal_clstm.detach(), temperature=20)
focus_1, focus_2, focus_3, focus_4, focus_5, focus_6, focus_7, focus_8, focus_9, focus_10\
, focus_11, focus_12 = torch.chunk(focus_student, 12, dim=1)
focus_loss1 = KD_KLDivLoss(focus_1, score_pred1.detach(), temperature=20)
focus_loss2 = KD_KLDivLoss(focus_2, score_pred2.detach(), temperature=20)
focus_loss3 = KD_KLDivLoss(focus_3, score_pred3.detach(), temperature=20)
focus_loss4 = KD_KLDivLoss(focus_4, score_pred4.detach(), temperature=20)
focus_loss5 = KD_KLDivLoss(focus_5, score_pred5.detach(), temperature=20)
focus_loss6 = KD_KLDivLoss(focus_6, score_pred6.detach(), temperature=20)
focus_loss7 = KD_KLDivLoss(focus_7, score_pred7.detach(), temperature=20)
focus_loss8 = KD_KLDivLoss(focus_8, score_pred8.detach(), temperature=20)
focus_loss9 = KD_KLDivLoss(focus_9, score_pred9.detach(), temperature=20)
focus_loss10 = KD_KLDivLoss(focus_10, score_pred10.detach(), temperature=20)
focus_loss11 = KD_KLDivLoss(focus_11, score_pred11.detach(), temperature=20)
focus_loss12 = KD_KLDivLoss(focus_12, score_pred12.detach(), temperature=20)
KD_focus = (focus_loss1 + focus_loss2 + focus_loss3 + focus_loss4 + focus_loss5 + focus_loss6 + focus_loss7 + focus_loss8 + focus_loss9
+ focus_loss10 + focus_loss11 + focus_loss12) / 12
Softloss_student = KD_focus + KD_loss
student_loss = (iteration/self.max_iter) * Hardloss_student + (1 - iteration/self.max_iter) * 256 * 256 * Softloss_student
student_loss.backward()
self.optim_student.step()
global running_loss_stu_hard
global running_loss_stu_soft
running_loss_stu_hard += Hardloss_student.item()
running_loss_stu_soft += Softloss_student.item()
if iteration % self.sshow == (self.sshow - 1):
print(
'\n [%3d, %6d, Hard loss: %.3f, Soft loss: %.3f]' % (
self.epoch + 1, iteration + 1,
running_loss_stu_hard / self.sshow,
running_loss_stu_soft / self.sshow
))
running_loss_stu_hard = 0.0
running_loss_stu_soft = 0.0
if iteration <= 0:
if iteration % self.snapshot == (self.snapshot - 1):
savename = ('%s/student_snapshot_iter_%d.pth' % (self.outpath, iteration + 1))
torch.save(self.student.state_dict(), savename)
print('save: (snapshot: %d)' % (iteration + 1))
else:
if iteration % 4000 == (4000 - 1):
savename = ('%s/student_snapshot_iter_%d.pth' % (self.outpath, iteration + 1))
torch.save(self.student.state_dict(), savename)
print('save: (snapshot: %d)' % (iteration + 1))
if (iteration + 1) == self.max_iter:
savename = ('%s/student_snapshot_iter_%d.pth' % (self.outpath, iteration + 1))
torch.save(self.student.state_dict(), savename)
print('save: (snapshot: %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