forked from PeiyanFlying/SPViT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
losses_soft.py
244 lines (206 loc) · 9.53 KB
/
losses_soft.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
"""
Implements the knowledge distillation loss
"""
from abc import get_cache_token
import torch
from torch.nn import functional as F
from torch.nn.modules.loss import MSELoss, BCEWithLogitsLoss, CrossEntropyLoss
from utils import batch_index_select
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
import math
class DistillationLoss(torch.nn.Module):
"""
This module wraps a standard criterion and adds an extra knowledge distillation loss by
taking a teacher model prediction and using it as additional supervision.
"""
def __init__(self, base_criterion: torch.nn.Module, teacher_model: torch.nn.Module,
distillation_type: str, alpha: float, tau: float):
super().__init__()
self.base_criterion = base_criterion
self.teacher_model = teacher_model
assert distillation_type in ['none', 'soft', 'hard']
self.distillation_type = distillation_type
self.alpha = alpha
self.tau = tau
def forward(self, inputs, outputs, labels):
"""
Args:
inputs: The original inputs that are feed to the teacher model
outputs: the outputs of the model to be trained. It is expected to be
either a Tensor, or a Tuple[Tensor, Tensor], with the original output
in the first position and the distillation predictions as the second output
labels: the labels for the base criterion
"""
outputs_kd = None
if not isinstance(outputs, torch.Tensor):
# assume that the model outputs a tuple of [outputs, outputs_kd]
outputs, outputs_kd = outputs
base_loss = self.base_criterion(outputs, labels)
if self.distillation_type == 'none':
return base_loss
if outputs_kd is None:
raise ValueError("When knowledge distillation is enabled, the model is "
"expected to return a Tuple[Tensor, Tensor] with the output of the "
"class_token and the dist_token")
# don't backprop throught the teacher
with torch.no_grad():
teacher_outputs = self.teacher_model(inputs)
if self.distillation_type == 'soft':
T = self.tau
# taken from https://github.com/peterliht/knowledge-distillation-pytorch/blob/master/model/net.py#L100
# with slight modifications
distillation_loss = F.kl_div(
F.log_softmax(outputs_kd / T, dim=1),
F.log_softmax(teacher_outputs / T, dim=1),
reduction='sum',
log_target=True
) * (T * T) / outputs_kd.numel()
elif self.distillation_type == 'hard':
distillation_loss = F.cross_entropy(outputs_kd, teacher_outputs.argmax(dim=1))
loss = base_loss * (1 - self.alpha) + distillation_loss * self.alpha
return loss
class DiffPruningLoss(torch.nn.Module):
"""
This module wraps a standard criterion and adds an extra knowledge distillation loss by
taking a teacher model prediction and using it as additional supervision.
"""
def __init__(self, base_criterion: torch.nn.Module, dynamic=False, ratio_weight=2.0, pruning_loc=[3,6,9], keep_ratio=[0.75, 0.5, 0.25], clf_weight=0, print_mode=True):
super().__init__()
self.base_criterion = base_criterion
self.clf_weight = clf_weight
self.pruning_loc = pruning_loc
self.keep_ratio = keep_ratio
self.count = 0
self.print_mode = print_mode
self.cls_loss = 0
self.ratio_loss = 0
self.ratio_weight = ratio_weight
self.dynamic = dynamic
if self.dynamic:
print('using dynamic loss')
def forward(self, inputs, outputs, labels):
"""
Args:
inputs: The original inputs that are feed to the teacher model
outputs: the outputs of the model to be trained. It is expected to be
either a Tensor, or a Tuple[Tensor, Tensor], with the original output
in the first position and the distillation predictions as the second output
labels: the labels for the base criterion
"""
pred, out_pred_score = outputs
pred_loss = 0.0
# ratio = [1.0,] + self.keep_ratio
# for i, score in enumerate(out_pred_score):
# score = score.mean(1)
# now_ratio = ratio[i+1] / ratio[i]
# pred_loss = pred_loss + ((score - now_ratio) ** 2).mean()
ratio = self.keep_ratio
for i, score in enumerate(out_pred_score):
pos_ratio = score.mean(1)
pred_loss = pred_loss + ((pos_ratio - ratio[i]) ** 2).mean()
cls_loss = self.base_criterion(pred, labels)
# print(cls_loss, pred_loss)
loss = self.clf_weight * cls_loss + self.ratio_weight * pred_loss / len(self.pruning_loc)
if self.print_mode:
self.cls_loss += cls_loss.item()
self.ratio_loss += pred_loss.item()
self.count += 1
if self.count == 100:
print('loss info: cls_loss=%.4f, ratio_loss=%.4f' % (self.cls_loss / 100, self.ratio_loss / 100))
self.count = 0
self.cls_loss = 0
self.ratio_loss = 0
return loss
class DistillDiffPruningLoss(torch.nn.Module):
"""
This module wraps a standard criterion and adds an extra knowledge distillation loss by
taking a teacher model prediction and using it as additional supervision.
"""
def __init__(self, teacher_model, base_criterion: torch.nn.Module, ratio_weight=2.0, distill_weight=0.5, dynamic=False, pruning_loc=[3,6,9], keep_ratio=[0.75, 0.5, 0.25], clf_weight=0, mse_token=False, print_mode=True):
super().__init__()
self.teacher_model = teacher_model
self.base_criterion = base_criterion
self.clf_weight = clf_weight
self.pruning_loc = pruning_loc
self.keep_ratio = keep_ratio
self.count = 0
self.print_mode = print_mode
self.cls_loss = 0
self.ratio_loss = 0
self.cls_distill_loss = 0
self.token_distill_loss = 0
self.mse_token = mse_token
self.dynamic = dynamic
self.ratio_weight = ratio_weight
self.distill_weight = distill_weight
print('ratio_weight=', ratio_weight, 'distill_weight', distill_weight)
if dynamic:
print('using dynamic loss')
def forward(self, inputs, outputs, labels):
"""
Args:
inputs: The original inputs that are feed to the teacher model
outputs: the outputs of the model to be trained. It is expected to be
either a Tensor, or a Tuple[Tensor, Tensor], with the original output
in the first position and the distillation predictions as the second output
labels: the labels for the base criterion
"""
pred, token_pred, mask, out_pred_score = outputs
pred_loss = 0.0
for i, score in enumerate(out_pred_score):
pred_loss += score.abs().mean() * self.keep_ratio[i]
cls_loss = self.base_criterion(pred, labels)
with torch.no_grad():
cls_t, token_t = self.teacher_model(inputs)
cls_kl_loss = F.kl_div(
F.log_softmax(pred, dim=-1),
F.log_softmax(cls_t, dim=-1),
reduction='batchmean',
log_target=True
)
B, N, C = token_pred.size()
assert mask.numel() == B * N
# print(mask)
# bool_mask = mask.reshape(B*N) > 0.5
# print('====================')
# print(mask.size())
bool_mask = mask.repeat(1,1,C).reshape(B*N, C)
# print(bool_mask.size())
# print('------')
token_pred = token_pred.reshape(B*N, C)
token_t = token_t.reshape(B*N, C)
# print(token_t.size())
# print(token_pred.size()) 维度都是对对
# print('====================')
if mask.sum() < 0.1:
token_kl_loss = token_pred.new(1,).fill_(0.0)
else:
token_t = token_t
token_pred = token_pred
if self.mse_token:
kl_tm = torch.pow(token_pred - token_t, 2)*bool_mask
token_kl_loss = kl_tm.mean()
else:
token_kl_loss = F.kl_div(
F.log_softmax(token_pred, dim=-1),
F.log_softmax(token_t, dim=-1),
reduction='batchmean',
log_target=True
)
loss = self.clf_weight * cls_loss + self.ratio_weight * pred_loss/len(self.pruning_loc) + self.distill_weight * cls_kl_loss + self.distill_weight * token_kl_loss
# if self.count % 20:
# print('loss info: cls_loss=%.4f, ratio_loss=%.4f, cls_kl=%.4f, token_kl=%.4f' % (cls_loss, pred_loss , cls_kl_loss, token_kl_loss))
if self.print_mode:
self.cls_loss += cls_loss.item()
self.ratio_loss += pred_loss.item()
self.cls_distill_loss += cls_kl_loss.item()
self.token_distill_loss += token_kl_loss.item()
self.count += 1
if self.count == 100:
print('loss info: cls_loss=%.4f, ratio_loss=%.4f, cls_kl=%.4f, token_kl=%.4f' % (self.cls_loss / 100, self.ratio_loss / 100, self.cls_distill_loss/ 100, self.token_distill_loss/ 100))
self.count = 0
self.cls_loss = 0
self.ratio_loss = 0
self.cls_distill_loss = 0
self.token_distill_loss = 0
return loss