-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetectors.py
256 lines (221 loc) · 7.26 KB
/
detectors.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
from typing import Any, Dict, List, NoReturn, Optional
import einops
import mmcv
import todd
import torch
from mmdet.core import bbox2result, bbox2roi
from mmdet.models import (
DETECTORS,
BaseDetector,
SingleStageDetector,
StandardRoIHead,
TwoStageDetector,
)
from todd.base.iters import inc_iter
from .dense_heads import RPNMixin
from .roi_heads import StandardRoIHeadWithBBoxIDs
class CacheImgsMixin(BaseDetector):
def __init__(self, *args, cache_imgs: bool = False, **kwargs) -> None:
super().__init__(*args, **kwargs)
self._cache_imgs = cache_imgs
def forward_train(
self,
img: torch.Tensor,
img_metas: List[Dict[str, Any]],
gt_bboxes: torch.Tensor,
gt_labels: torch.Tensor,
gt_bboxes_ignore: Optional[torch.Tensor] = None,
gt_masks: Optional[torch.Tensor] = None,
**kwargs,
) -> Dict[str, Any]:
if self._cache_imgs:
imgs = einops.rearrange(img, 'bs c h w -> bs h w c')
imgs = imgs.detach().cpu().numpy()
self.imgs = [ # yapf: disable
mmcv.imdenormalize(
img,
mean=img_meta['img_norm_cfg']['mean'],
std=img_meta['img_norm_cfg']['std'],
to_bgr=img_meta['img_norm_cfg']['to_rgb'],
) for img, img_meta in zip(imgs, img_metas)
]
return super().forward_train(
img,
img_metas,
gt_bboxes,
gt_labels,
gt_bboxes_ignore,
gt_masks,
**kwargs,
)
class SchedulersMixin(BaseDetector):
def __init__(
self,
*args,
schedulers: Optional[dict] = None,
**kwargs,
) -> None:
super().__init__(*args, **kwargs)
self._schedulers = None if schedulers is None else { # yapf: disable
name: todd.schedulers.SCHEDULERS.build(cfg)
for name, cfg in schedulers.items()
}
def forward_train(
self,
img: torch.Tensor,
img_metas: List[Dict[str, Any]],
gt_bboxes: torch.Tensor,
gt_labels: torch.Tensor,
gt_bboxes_ignore: Optional[torch.Tensor] = None,
gt_masks: Optional[torch.Tensor] = None,
**kwargs,
) -> Dict[str, Any]:
losses = super().forward_train(
img,
img_metas,
gt_bboxes,
gt_labels,
gt_bboxes_ignore,
gt_masks,
**kwargs,
)
if self._schedulers is not None:
losses.update({ # yapf: disable
name: todd.utils.CollectionTensor.apply(
losses[name],
lambda loss: loss * scheduler,
)
for name, scheduler in self._schedulers.items()
})
return losses
@DETECTORS.register_module()
class CrossStageDetector(TwoStageDetector):
rpn_head: RPNMixin
roi_head: StandardRoIHead
def forward_train(
self,
img: torch.Tensor,
img_metas: List[Dict[str, Any]],
gt_bboxes: torch.Tensor,
gt_labels: torch.Tensor,
gt_bboxes_ignore: Optional[torch.Tensor] = None,
gt_masks: Optional[torch.Tensor] = None,
**kwargs,
) -> Dict[str, Any]:
x = self.extract_feat(img)
proposal_cfg = self.train_cfg.get('rpn_proposal', self.test_cfg.rpn)
rpn_losses, proposal_list = self.rpn_head.forward_train(
x,
img_metas,
gt_bboxes,
gt_labels,
gt_bboxes_ignore,
proposal_cfg,
**kwargs,
)
roi_losses = self.roi_head.forward_train(
x,
img_metas,
proposal_list,
gt_bboxes,
gt_labels,
gt_bboxes_ignore,
gt_masks,
**kwargs,
)
return {**rpn_losses, **roi_losses}
def simple_test(
self,
img: torch.Tensor,
img_metas: List[dict],
rescale: bool = False,
) -> list:
feat = self.extract_feat(img)
results_list = self.rpn_head.simple_test(
feat,
img_metas,
rescale=rescale,
)
bbox_results = [ # yapf: disable
bbox2result(det_bboxes, det_labels, self.rpn_head.num_classes)
for det_bboxes, det_labels in results_list
]
return bbox_results
def aug_test(self, *args, **kwargs) -> NoReturn:
raise NotImplementedError
class SingleTeacherDistiller(todd.distillers.SingleTeacherDistiller):
def __init__(self, *args, teacher: todd.base.Config, **kwargs):
teacher.config = todd.base.Config.load(teacher.config).model
teacher_model = todd.base.load_open_mmlab_models(
DETECTORS,
**teacher,
)
super().__init__(*args, teacher=teacher_model, **kwargs)
class DistillerMixin(BaseDetector):
distiller: SingleTeacherDistiller
def forward_test(self, *args, **kwargs) -> List[Any]:
results = super().forward_test(*args, **kwargs)
self.distiller.reset()
return results
@DETECTORS.register_module()
@SingleTeacherDistiller.wrap()
class SingleTeacherSingleStageDistiller(SingleStageDetector):
def forward_train(self, *args, **kwargs) -> Dict[str, Any]:
with torch.no_grad():
teacher: TwoStageDetector = self.distiller.teacher
_ = teacher.forward_train(*args, **kwargs)
losses = super().forward_train(*args, **kwargs)
self.distiller.track_tensors()
kd_losses = self.distiller.distill()
self.distiller.reset()
inc_iter()
# mmdet does not support tuple of losses
for k, v in kd_losses.items():
if isinstance(v, tuple):
kd_losses[k] = list(v)
return {**losses, **kd_losses}
@DETECTORS.register_module()
@SingleTeacherDistiller.wrap()
class CrossStageHEAD(
CacheImgsMixin,
SchedulersMixin,
DistillerMixin,
CrossStageDetector,
):
roi_head: StandardRoIHeadWithBBoxIDs
def forward_train(
self,
img: torch.Tensor,
img_metas: List[Dict[str, Any]],
gt_bboxes: torch.Tensor,
gt_labels: torch.Tensor,
gt_bboxes_ignore: Optional[torch.Tensor] = None,
gt_masks: Optional[torch.Tensor] = None,
**kwargs,
) -> Dict[str, Any]:
losses = super().forward_train(
img,
img_metas,
gt_bboxes,
gt_labels,
gt_bboxes_ignore,
gt_masks,
**kwargs,
)
with torch.no_grad():
teacher: TwoStageDetector = self.distiller.teacher
teacher_roi_head: StandardRoIHead = teacher.roi_head
teacher_x = teacher.extract_feat(img)
rois = bbox2roi(self.roi_head.bboxes)
teacher_roi_head._bbox_forward(teacher_x, rois)
custom_tensors = dict(
bboxes=self.roi_head.bboxes,
bbox_ids=self.roi_head.bboxes_ids,
gt_bboxes=gt_bboxes,
batch_input_shape=tuple(img[0].shape[-2:]),
)
self.distiller.track_tensors()
kd_losses = self.distiller.distill(custom_tensors)
self.distiller.reset()
inc_iter()
return {**losses, **kd_losses}