TLMHoang commited on
Commit
973c3da
·
verified ·
1 Parent(s): d77508d

Upload folder using huggingface_hub

Browse files
mmdet_code/mmdetection/configs/dala/cascade-rcnn_r50_fpn_dala_1x_coco.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cascade R-CNN with full DALA in the RPN (SimD + RLA + DWL)."""
2
+
3
+ _base_ = '../cascade_rcnn/cascade-rcnn_r50_fpn_1x_coco.py'
4
+
5
+ model = dict(
6
+ rpn_head=dict(type='DalaRPNHead', use_dwl=True),
7
+ train_cfg=dict(
8
+ rpn=dict(
9
+ assigner=dict(
10
+ _delete_=True,
11
+ type='DalaAssigner',
12
+ ignore_iof_thr=-1,
13
+ sync_stats=True))))
mmdet_code/mmdetection/configs/dala/faster-rcnn_r50_fpn_dala_1x_coco.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Faster R-CNN with full DALA in the RPN (SimD + RLA + DWL)."""
2
+
3
+ _base_ = '../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py'
4
+
5
+ model = dict(
6
+ rpn_head=dict(type='DalaRPNHead', use_dwl=True),
7
+ train_cfg=dict(
8
+ rpn=dict(
9
+ assigner=dict(
10
+ _delete_=True,
11
+ type='DalaAssigner',
12
+ ignore_iof_thr=-1,
13
+ sync_stats=True))))
mmdet_code/mmdetection/configs/dala/fcos_r50-caffe_fpn_dala_1x_coco.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """FCOS with full point-based DALA (L2 + RLA + DWL)."""
2
+
3
+ _base_ = '../fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py'
4
+
5
+ model = dict(
6
+ bbox_head=dict(
7
+ type='DalaFCOSHead',
8
+ use_dwl=True,
9
+ sync_stats=True))
mmdet_code/mmdetection/configs/dala/retinanet_r50_fpn_dala_1x_coco.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RetinaNet with full DALA in its dense head (SimD + RLA + DWL)."""
2
+
3
+ _base_ = '../retinanet/retinanet_r50_fpn_1x_coco.py'
4
+
5
+ model = dict(
6
+ bbox_head=dict(type='DalaRetinaHead', use_dwl=True),
7
+ train_cfg=dict(
8
+ assigner=dict(
9
+ _delete_=True,
10
+ type='DalaAssigner',
11
+ ignore_iof_thr=-1,
12
+ sync_stats=True)))
mmdet_code/mmdetection/mmdet/models/dense_heads/__init__.py CHANGED
@@ -13,6 +13,7 @@ from .condinst_head import CondInstBboxHead, CondInstMaskHead
13
  from .conditional_detr_head import ConditionalDETRHead
14
  from .corner_head import CornerHead
15
  from .dab_detr_head import DABDETRHead
 
16
  from .ddod_head import DDODHead
17
  from .ddq_detr_head import DDQDETRHead
18
  from .deformable_detr_head import DeformableDETRHead
@@ -68,5 +69,6 @@ __all__ = [
68
  'CenterNetUpdateHead', 'RTMDetHead', 'RTMDetSepBNHead', 'CondInstBboxHead',
69
  'CondInstMaskHead', 'RTMDetInsHead', 'RTMDetInsSepBNHead',
70
  'BoxInstBboxHead', 'BoxInstMaskHead', 'ConditionalDETRHead', 'DINOHead',
71
- 'ATSSVLFusionHead', 'DABDETRHead', 'DDQDETRHead', 'GroundingDINOHead'
 
72
  ]
 
13
  from .conditional_detr_head import ConditionalDETRHead
14
  from .corner_head import CornerHead
15
  from .dab_detr_head import DABDETRHead
16
+ from .dala_heads import DalaFCOSHead, DalaRetinaHead, DalaRPNHead
17
  from .ddod_head import DDODHead
18
  from .ddq_detr_head import DDQDETRHead
19
  from .deformable_detr_head import DeformableDETRHead
 
69
  'CenterNetUpdateHead', 'RTMDetHead', 'RTMDetSepBNHead', 'CondInstBboxHead',
70
  'CondInstMaskHead', 'RTMDetInsHead', 'RTMDetInsSepBNHead',
71
  'BoxInstBboxHead', 'BoxInstMaskHead', 'ConditionalDETRHead', 'DINOHead',
72
+ 'ATSSVLFusionHead', 'DABDETRHead', 'DDQDETRHead', 'GroundingDINOHead',
73
+ 'DalaFCOSHead', 'DalaRetinaHead', 'DalaRPNHead'
74
  ]
mmdet_code/mmdetection/mmdet/models/dense_heads/dala_heads.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ """Opt-in DALA heads for RPN, RetinaNet, and FCOS."""
3
+
4
+ from typing import Dict, List, Optional, Tuple, Union
5
+
6
+ import torch
7
+ from mmengine.structures import InstanceData
8
+ from torch import Tensor
9
+
10
+ from mmdet.registry import MODELS
11
+ from mmdet.structures.bbox import BaseBoxes
12
+ from mmdet.utils import InstanceList, OptInstanceList, reduce_mean
13
+ from ..task_modules.assigners.dala_assigner import DalaPositiveQuota
14
+ from ..task_modules.prior_generators import anchor_inside_flags
15
+ from ..utils import multi_apply, unmap
16
+ from .fcos_head import FCOSHead
17
+ from .retina_head import RetinaHead
18
+ from .rpn_head import RPNHead
19
+
20
+
21
+ def _dwl_gt_weights(gt_bboxes: Tensor) -> Tensor:
22
+ """Equation (8): one dynamic weight per ground-truth instance."""
23
+ areas = ((gt_bboxes[:, 2] - gt_bboxes[:, 0]).clamp_min(1e-7) *
24
+ (gt_bboxes[:, 3] - gt_bboxes[:, 1]).clamp_min(1e-7))
25
+ return 1 + torch.log10(torch.sqrt(areas.mean() / areas))
26
+
27
+
28
+ class _DalaAnchorTargetMixin:
29
+ """Apply DWL weights to targets returned by an anchor-based head."""
30
+
31
+ def __init__(self, use_dwl: bool = True, **kwargs) -> None:
32
+ self.use_dwl = use_dwl
33
+ super().__init__(**kwargs)
34
+
35
+ def _get_targets_single(self,
36
+ flat_anchors: Union[Tensor, BaseBoxes],
37
+ valid_flags: Tensor,
38
+ gt_instances: InstanceData,
39
+ img_meta: dict,
40
+ gt_instances_ignore: Optional[InstanceData] = None,
41
+ unmap_outputs: bool = True) -> tuple:
42
+ if not self.use_dwl:
43
+ return super()._get_targets_single(flat_anchors, valid_flags,
44
+ gt_instances, img_meta,
45
+ gt_instances_ignore,
46
+ unmap_outputs)
47
+
48
+ results = list(super()._get_targets_single(
49
+ flat_anchors,
50
+ valid_flags,
51
+ gt_instances,
52
+ img_meta,
53
+ gt_instances_ignore,
54
+ unmap_outputs=False))
55
+ (labels, label_weights, bbox_targets, bbox_weights, pos_inds, neg_inds,
56
+ sampling_result) = results[:7]
57
+
58
+ if len(pos_inds) > 0:
59
+ gt_bboxes = gt_instances.bboxes.tensor if isinstance(
60
+ gt_instances.bboxes, BaseBoxes) else gt_instances.bboxes
61
+ gt_weights = _dwl_gt_weights(gt_bboxes)
62
+ pos_weights = gt_weights[sampling_result.pos_assigned_gt_inds]
63
+ label_weights[pos_inds] = pos_weights
64
+ bbox_weights[pos_inds] = pos_weights[:, None]
65
+ negative_weight = pos_weights.mean()
66
+ else:
67
+ negative_weight = label_weights.new_tensor(1.)
68
+ if len(neg_inds) > 0:
69
+ label_weights[neg_inds] = negative_weight
70
+
71
+ if unmap_outputs:
72
+ inside_flags = anchor_inside_flags(
73
+ flat_anchors, valid_flags, img_meta['img_shape'][:2],
74
+ self.train_cfg['allowed_border'])
75
+ num_total_anchors = flat_anchors.size(0)
76
+ labels = unmap(
77
+ labels, num_total_anchors, inside_flags, fill=self.num_classes)
78
+ label_weights = unmap(label_weights, num_total_anchors,
79
+ inside_flags)
80
+ bbox_targets = unmap(bbox_targets, num_total_anchors, inside_flags)
81
+ bbox_weights = unmap(bbox_weights, num_total_anchors, inside_flags)
82
+
83
+ results[:4] = labels, label_weights, bbox_targets, bbox_weights
84
+ return tuple(results)
85
+
86
+
87
+ @MODELS.register_module()
88
+ class DalaRPNHead(_DalaAnchorTargetMixin, RPNHead):
89
+ """RPN head with optional DALA dynamic weighting loss."""
90
+
91
+
92
+ @MODELS.register_module()
93
+ class DalaRetinaHead(_DalaAnchorTargetMixin, RetinaHead):
94
+ """RetinaNet head with optional DALA dynamic weighting loss."""
95
+
96
+
97
+ @MODELS.register_module()
98
+ class DalaFCOSHead(FCOSHead):
99
+ """FCOS head using RLA/L2 point assignment and optional DWL."""
100
+
101
+ def __init__(self,
102
+ use_dwl: bool = True,
103
+ sync_stats: bool = True,
104
+ **kwargs) -> None:
105
+ super().__init__(**kwargs)
106
+ self.use_dwl = use_dwl
107
+ self.quota_tracker = DalaPositiveQuota(sync_stats=sync_stats)
108
+
109
+ def loss_by_feat(
110
+ self,
111
+ cls_scores: List[Tensor],
112
+ bbox_preds: List[Tensor],
113
+ centernesses: List[Tensor],
114
+ batch_gt_instances: InstanceList,
115
+ batch_img_metas: List[dict],
116
+ batch_gt_instances_ignore: OptInstanceList = None
117
+ ) -> Dict[str, Tensor]:
118
+ """Calculate FCOS losses with DALA sample weights."""
119
+ assert len(cls_scores) == len(bbox_preds) == len(centernesses)
120
+ featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]
121
+ all_level_points = self.prior_generator.grid_priors(
122
+ featmap_sizes,
123
+ dtype=bbox_preds[0].dtype,
124
+ device=bbox_preds[0].device)
125
+ (labels, bbox_targets, label_weights,
126
+ bbox_weights) = self.get_targets(all_level_points, batch_gt_instances)
127
+
128
+ num_imgs = cls_scores[0].size(0)
129
+ flatten_cls_scores = torch.cat([
130
+ score.permute(0, 2, 3, 1).reshape(-1, self.cls_out_channels)
131
+ for score in cls_scores
132
+ ])
133
+ flatten_bbox_preds = torch.cat(
134
+ [pred.permute(0, 2, 3, 1).reshape(-1, 4) for pred in bbox_preds])
135
+ flatten_centerness = torch.cat([
136
+ center.permute(0, 2, 3, 1).reshape(-1) for center in centernesses
137
+ ])
138
+ flatten_labels = torch.cat(labels)
139
+ flatten_bbox_targets = torch.cat(bbox_targets)
140
+ flatten_label_weights = torch.cat(label_weights)
141
+ flatten_bbox_weights = torch.cat(bbox_weights)
142
+ flatten_points = torch.cat(
143
+ [points.repeat(num_imgs, 1) for points in all_level_points])
144
+
145
+ pos_inds = ((flatten_labels >= 0)
146
+ &
147
+ (flatten_labels < self.num_classes)).nonzero().reshape(-1)
148
+ num_pos = torch.tensor(
149
+ len(pos_inds), dtype=torch.float, device=bbox_preds[0].device)
150
+ num_pos = max(reduce_mean(num_pos), 1.0)
151
+ loss_cls = self.loss_cls(
152
+ flatten_cls_scores,
153
+ flatten_labels,
154
+ weight=flatten_label_weights,
155
+ avg_factor=num_pos)
156
+
157
+ pos_bbox_preds = flatten_bbox_preds[pos_inds]
158
+ pos_centerness = flatten_centerness[pos_inds]
159
+ pos_bbox_targets = flatten_bbox_targets[pos_inds]
160
+ pos_centerness_targets = self.centerness_target(pos_bbox_targets)
161
+ centerness_denorm = max(
162
+ reduce_mean(pos_centerness_targets.sum().detach()), 1e-6)
163
+
164
+ if len(pos_inds) > 0:
165
+ pos_points = flatten_points[pos_inds]
166
+ decoded_preds = self.bbox_coder.decode(pos_points, pos_bbox_preds)
167
+ decoded_targets = self.bbox_coder.decode(pos_points,
168
+ pos_bbox_targets)
169
+ regression_weights = (
170
+ pos_centerness_targets * flatten_bbox_weights[pos_inds])
171
+ loss_bbox = self.loss_bbox(
172
+ decoded_preds,
173
+ decoded_targets,
174
+ weight=regression_weights,
175
+ avg_factor=centerness_denorm)
176
+ # The paper weights classification and box regression. FCOS's
177
+ # auxiliary centerness branch remains identical to the baseline.
178
+ loss_centerness = self.loss_centerness(
179
+ pos_centerness, pos_centerness_targets, avg_factor=num_pos)
180
+ else:
181
+ loss_bbox = pos_bbox_preds.sum()
182
+ loss_centerness = pos_centerness.sum()
183
+
184
+ return dict(
185
+ loss_cls=loss_cls,
186
+ loss_bbox=loss_bbox,
187
+ loss_centerness=loss_centerness)
188
+
189
+ def get_targets(
190
+ self, points: List[Tensor], batch_gt_instances: InstanceList
191
+ ) -> Tuple[List[Tensor], List[Tensor], List[Tensor], List[Tensor]]:
192
+ """Compute per-level RLA targets and DWL weights."""
193
+ num_points = [point.size(0) for point in points]
194
+ concat_points = torch.cat(points, dim=0)
195
+ results = multi_apply(
196
+ self._get_targets_single, batch_gt_instances, points=concat_points)
197
+ (labels_list, bbox_targets_list, label_weights_list,
198
+ bbox_weights_list) = results
199
+
200
+ labels_list = [labels.split(num_points, 0) for labels in labels_list]
201
+ bbox_targets_list = [
202
+ targets.split(num_points, 0) for targets in bbox_targets_list
203
+ ]
204
+ label_weights_list = [
205
+ weights.split(num_points, 0) for weights in label_weights_list
206
+ ]
207
+ bbox_weights_list = [
208
+ weights.split(num_points, 0) for weights in bbox_weights_list
209
+ ]
210
+
211
+ per_level = [[], [], [], []]
212
+ for level in range(len(num_points)):
213
+ per_level[0].append(
214
+ torch.cat([labels[level] for labels in labels_list]))
215
+ targets = torch.cat(
216
+ [targets[level] for targets in bbox_targets_list])
217
+ if self.norm_on_bbox:
218
+ targets = targets / self.strides[level]
219
+ per_level[1].append(targets)
220
+ per_level[2].append(
221
+ torch.cat([weights[level] for weights in label_weights_list]))
222
+ per_level[3].append(
223
+ torch.cat([weights[level] for weights in bbox_weights_list]))
224
+ return tuple(per_level)
225
+
226
+ @torch.no_grad()
227
+ def _get_targets_single(
228
+ self, gt_instances: InstanceData,
229
+ points: Tensor) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
230
+ """Assign points by RLA and raw L2 distance for one image."""
231
+ num_points = points.size(0)
232
+ gt_bboxes = gt_instances.bboxes.tensor if isinstance(
233
+ gt_instances.bboxes, BaseBoxes) else gt_instances.bboxes
234
+ gt_labels = gt_instances.labels
235
+ num_gts = gt_bboxes.size(0)
236
+
237
+ labels = gt_labels.new_full((num_points, ), self.num_classes)
238
+ bbox_targets = points.new_zeros((num_points, 4))
239
+ label_weights = points.new_ones((num_points, ))
240
+ bbox_weights = points.new_zeros((num_points, ))
241
+ if num_gts == 0:
242
+ return labels, bbox_targets, label_weights, bbox_weights
243
+
244
+ xy = points[:, :2]
245
+ inside = ((xy[:, None, 0] > gt_bboxes[None, :, 0])
246
+ & (xy[:, None, 0] < gt_bboxes[None, :, 2])
247
+ & (xy[:, None, 1] > gt_bboxes[None, :, 1])
248
+ & (xy[:, None, 1] < gt_bboxes[None, :, 3]))
249
+ quotas = self.quota_tracker(inside.sum(dim=0).to(points))
250
+ gt_centers = (gt_bboxes[:, :2] + gt_bboxes[:, 2:]) * 0.5
251
+ distances = (xy[:, None, :] - gt_centers[None, :, :]).square().sum(-1)
252
+ selected_distances = distances.new_full(distances.shape, torch.inf)
253
+ for gt_idx, quota in enumerate(quotas.tolist()):
254
+ if quota == 0:
255
+ continue
256
+ candidates = torch.nonzero(
257
+ inside[:, gt_idx], as_tuple=False).squeeze(1)
258
+ top_indices = distances[candidates, gt_idx].topk(
259
+ quota, largest=False).indices
260
+ chosen = candidates[top_indices]
261
+ selected_distances[chosen, gt_idx] = distances[chosen, gt_idx]
262
+
263
+ best_distance, assigned_gt = selected_distances.min(dim=1)
264
+ positive = torch.isfinite(best_distance)
265
+ ambiguous = inside.any(dim=1) & ~positive
266
+ label_weights[ambiguous] = 0
267
+ labels[positive] = gt_labels[assigned_gt[positive]]
268
+
269
+ if positive.any():
270
+ pos_xy = xy[positive]
271
+ pos_gt = gt_bboxes[assigned_gt[positive]]
272
+ bbox_targets[positive] = torch.stack(
273
+ (pos_xy[:, 0] - pos_gt[:, 0], pos_xy[:, 1] - pos_gt[:, 1],
274
+ pos_gt[:, 2] - pos_xy[:, 0], pos_gt[:, 3] - pos_xy[:, 1]),
275
+ dim=-1)
276
+ if self.use_dwl:
277
+ positive_weights = _dwl_gt_weights(gt_bboxes)[
278
+ assigned_gt[positive]]
279
+ label_weights[positive] = positive_weights
280
+ bbox_weights[positive] = positive_weights
281
+ label_weights[~inside.any(dim=1)] = positive_weights.mean()
282
+ else:
283
+ bbox_weights[positive] = 1
284
+
285
+ return labels, bbox_targets, label_weights, bbox_weights
286
+
287
+
288
+ __all__ = ['DalaFCOSHead', 'DalaRPNHead', 'DalaRetinaHead']
mmdet_code/mmdetection/mmdet/models/task_modules/assigners/__init__.py CHANGED
@@ -4,6 +4,8 @@ from .assign_result import AssignResult
4
  from .atss_assigner import ATSSAssigner
5
  from .base_assigner import BaseAssigner
6
  from .center_region_assigner import CenterRegionAssigner
 
 
7
  from .dynamic_soft_label_assigner import DynamicSoftLabelAssigner
8
  from .grid_assigner import GridAssigner
9
  from .hungarian_assigner import HungarianAssigner
@@ -28,5 +30,6 @@ __all__ = [
28
  'TaskAlignedAssigner', 'TopkHungarianAssigner', 'BBoxL1Cost',
29
  'ClassificationCost', 'CrossEntropyLossCost', 'DiceCost', 'FocalLossCost',
30
  'IoUCost', 'BboxOverlaps2D', 'DynamicSoftLabelAssigner',
31
- 'MultiInstanceAssigner', 'BboxOverlaps2D_GLIP'
 
32
  ]
 
4
  from .atss_assigner import ATSSAssigner
5
  from .base_assigner import BaseAssigner
6
  from .center_region_assigner import CenterRegionAssigner
7
+ from .dala_assigner import (DalaAssigner, DalaPositiveQuota,
8
+ bbox_similarity_distance)
9
  from .dynamic_soft_label_assigner import DynamicSoftLabelAssigner
10
  from .grid_assigner import GridAssigner
11
  from .hungarian_assigner import HungarianAssigner
 
30
  'TaskAlignedAssigner', 'TopkHungarianAssigner', 'BBoxL1Cost',
31
  'ClassificationCost', 'CrossEntropyLossCost', 'DiceCost', 'FocalLossCost',
32
  'IoUCost', 'BboxOverlaps2D', 'DynamicSoftLabelAssigner',
33
+ 'MultiInstanceAssigner', 'BboxOverlaps2D_GLIP', 'DalaAssigner',
34
+ 'DalaPositiveQuota', 'bbox_similarity_distance'
35
  ]
mmdet_code/mmdetection/mmdet/models/task_modules/assigners/dala_assigner.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) OpenMMLab. All rights reserved.
2
+ """Dynamic Adaptive Label Assignment (DALA) task utilities.
3
+
4
+ The implementation follows Shi et al., "Dynamic Adaptive Label Assignment
5
+ for Tiny Object Detection in Remote Sensing Images". It intentionally lives
6
+ next to, rather than replacing, :class:`MaxIoUAssigner` so baseline configs
7
+ retain their original behaviour.
8
+ """
9
+
10
+ from typing import Optional
11
+
12
+ import torch
13
+ import torch.distributed as dist
14
+ import torch.nn as nn
15
+ from mmengine.structures import InstanceData
16
+ from torch import Tensor
17
+
18
+ from mmdet.registry import TASK_UTILS
19
+ from mmdet.structures.bbox import get_box_tensor
20
+ from .assign_result import AssignResult
21
+ from .base_assigner import BaseAssigner
22
+ from .iou2d_calculator import BboxOverlaps2D
23
+
24
+
25
+ def bbox_similarity_distance(priors: Tensor,
26
+ gt_bboxes: Tensor,
27
+ eps: float = 1e-7) -> Tensor:
28
+ """Calculate the paper's similarity distance (SimD).
29
+
30
+ Args:
31
+ priors (Tensor): Anchor boxes in ``xyxy`` format, shape ``(N, 4)``.
32
+ gt_bboxes (Tensor): Ground-truth boxes in ``xyxy`` format, shape
33
+ ``(M, 4)``.
34
+ eps (float): Numerical floor for width/height denominators.
35
+
36
+ Returns:
37
+ Tensor: Pairwise similarities with shape ``(N, M)``.
38
+ """
39
+ priors = get_box_tensor(priors)[..., :4]
40
+ gt_bboxes = get_box_tensor(gt_bboxes)[..., :4]
41
+ if priors.numel() == 0 or gt_bboxes.numel() == 0:
42
+ return priors.new_zeros((priors.shape[0], gt_bboxes.shape[0]))
43
+
44
+ prior_wh = (priors[:, 2:] - priors[:, :2]).clamp_min(eps)
45
+ gt_wh = (gt_bboxes[:, 2:] - gt_bboxes[:, :2]).clamp_min(eps)
46
+ prior_ctr = (priors[:, :2] + priors[:, 2:]) * 0.5
47
+ gt_ctr = (gt_bboxes[:, :2] + gt_bboxes[:, 2:]) * 0.5
48
+
49
+ wh_sum = (prior_wh[:, None, :] + gt_wh[None, :, :]).clamp_min(eps)
50
+ location = ((prior_ctr[:, None, :] - gt_ctr[None, :, :]) /
51
+ wh_sum).square().sum(dim=-1).sqrt()
52
+ shape = ((prior_wh[:, None, :] - gt_wh[None, :, :]) /
53
+ wh_sum).square().sum(dim=-1).sqrt()
54
+ return torch.exp(-(location + shape)).clamp_min(eps)
55
+
56
+
57
+ class DalaPositiveQuota(nn.Module):
58
+ """Track the running anchor density used by ratio-based assignment.
59
+
60
+ The official repository stores every observed density in a process-global
61
+ CPU tensor. Running sum/count buffers are equivalent for Equation (4),
62
+ checkpointable, device agnostic, and cheap in memory. In distributed
63
+ training the per-call statistics are reduced across ranks by default.
64
+ """
65
+
66
+ def __init__(self, sync_stats: bool = True) -> None:
67
+ super().__init__()
68
+ self.sync_stats = sync_stats
69
+ self.register_buffer('density_sum', torch.zeros((),
70
+ dtype=torch.float64))
71
+ self.register_buffer('density_count', torch.zeros((),
72
+ dtype=torch.long))
73
+
74
+ @torch.no_grad()
75
+ def forward(self, inside_counts: Tensor) -> Tensor:
76
+ """Update the running density and return integer positive quotas."""
77
+ if inside_counts.numel() == 0:
78
+ return inside_counts.to(dtype=torch.long)
79
+
80
+ stats = torch.stack((inside_counts.double().sum(),
81
+ inside_counts.new_tensor(
82
+ inside_counts.numel(), dtype=torch.float64)))
83
+ if (self.sync_stats and dist.is_available() and dist.is_initialized()):
84
+ dist.all_reduce(stats, op=dist.ReduceOp.SUM)
85
+
86
+ self.density_sum.add_(stats[0].to(self.density_sum.device))
87
+ self.density_count.add_(stats[1].to(
88
+ device=self.density_count.device, dtype=torch.long))
89
+ mean_density = (self.density_sum /
90
+ self.density_count.clamp_min(1)).to(inside_counts)
91
+
92
+ # Equation (4) produces a real value, while top-k requires an integer.
93
+ # The reference implementation truncates toward zero (floor here,
94
+ # because counts are non-negative).
95
+ quotas = torch.floor(inside_counts / mean_density.clamp_min(1e-12))
96
+ quotas = quotas.clamp_min(1).to(dtype=torch.long)
97
+ # A GT with no point/anchor inside cannot receive a valid positive.
98
+ return torch.minimum(quotas, inside_counts.to(dtype=torch.long))
99
+
100
+
101
+ @TASK_UTILS.register_module()
102
+ class DalaAssigner(nn.Module, BaseAssigner):
103
+ """Assign anchors using SimD and the ratio-based DALA quota.
104
+
105
+ Anchor centres outside every GT are negatives. Unselected anchors whose
106
+ centres lie inside at least one GT are ignored. For a collision, the GT
107
+ with the highest SimD wins.
108
+ """
109
+
110
+ def __init__(self,
111
+ ignore_iof_thr: float = -1,
112
+ sync_stats: bool = True) -> None:
113
+ nn.Module.__init__(self)
114
+ self.ignore_iof_thr = ignore_iof_thr
115
+ self.quota_tracker = DalaPositiveQuota(sync_stats=sync_stats)
116
+ self.ignore_calculator = BboxOverlaps2D()
117
+
118
+ @torch.no_grad()
119
+ def assign(self,
120
+ pred_instances: InstanceData,
121
+ gt_instances: InstanceData,
122
+ gt_instances_ignore: Optional[InstanceData] = None,
123
+ **kwargs) -> AssignResult:
124
+ priors = get_box_tensor(pred_instances.priors)[..., :4]
125
+ gt_bboxes = get_box_tensor(gt_instances.bboxes)[..., :4]
126
+ gt_labels = getattr(gt_instances, 'labels', None)
127
+ num_priors = priors.shape[0]
128
+ num_gts = gt_bboxes.shape[0]
129
+
130
+ assigned_gt_inds = priors.new_zeros((num_priors, ), dtype=torch.long)
131
+ assigned_labels = priors.new_full((num_priors, ), -1, dtype=torch.long)
132
+
133
+ ignore_mask = priors.new_zeros((num_priors, ), dtype=torch.bool)
134
+ if (self.ignore_iof_thr > 0 and gt_instances_ignore is not None
135
+ and len(gt_instances_ignore) > 0 and num_priors > 0):
136
+ ignore_bboxes = get_box_tensor(gt_instances_ignore.bboxes)[..., :4]
137
+ ignore_iof = self.ignore_calculator(
138
+ priors, ignore_bboxes, mode='iof')
139
+ ignore_mask = ignore_iof.max(dim=1).values > self.ignore_iof_thr
140
+
141
+ if num_priors == 0 or num_gts == 0:
142
+ assigned_gt_inds[ignore_mask] = -1
143
+ max_overlaps = priors.new_zeros((num_priors, ))
144
+ return AssignResult(
145
+ num_gts,
146
+ assigned_gt_inds,
147
+ max_overlaps,
148
+ labels=assigned_labels)
149
+
150
+ centers = (priors[:, :2] + priors[:, 2:]) * 0.5
151
+ inside = ((centers[:, None, 0] > gt_bboxes[None, :, 0])
152
+ & (centers[:, None, 0] < gt_bboxes[None, :, 2])
153
+ & (centers[:, None, 1] > gt_bboxes[None, :, 1])
154
+ & (centers[:, None, 1] < gt_bboxes[None, :, 3]))
155
+ inside[ignore_mask] = False
156
+
157
+ similarities = bbox_similarity_distance(priors, gt_bboxes)
158
+ quotas = self.quota_tracker(inside.sum(dim=0).to(similarities))
159
+
160
+ selected_scores = similarities.new_full(similarities.shape, -torch.inf)
161
+ for gt_idx, quota in enumerate(quotas.tolist()):
162
+ if quota == 0:
163
+ continue
164
+ candidates = torch.nonzero(
165
+ inside[:, gt_idx], as_tuple=False).squeeze(1)
166
+ candidate_scores = similarities[candidates, gt_idx]
167
+ top_indices = candidate_scores.topk(quota, largest=True).indices
168
+ chosen = candidates[top_indices]
169
+ selected_scores[chosen, gt_idx] = similarities[chosen, gt_idx]
170
+
171
+ best_scores, best_gt = selected_scores.max(dim=1)
172
+ positive = torch.isfinite(best_scores)
173
+
174
+ # Inside-but-unselected anchors are ignore (-1); outside anchors are
175
+ # background (0), as specified by Algorithm 1.
176
+ assigned_gt_inds[inside.any(dim=1)] = -1
177
+ assigned_gt_inds[positive] = best_gt[positive] + 1
178
+ assigned_gt_inds[ignore_mask] = -1
179
+ if gt_labels is not None and positive.any():
180
+ assigned_labels[positive] = gt_labels[best_gt[positive]]
181
+
182
+ max_overlaps = similarities.max(dim=1).values
183
+ max_overlaps[ignore_mask] = -1
184
+ return AssignResult(
185
+ num_gts, assigned_gt_inds, max_overlaps, labels=assigned_labels)
186
+
187
+
188
+ __all__ = ['DalaAssigner', 'DalaPositiveQuota', 'bbox_similarity_distance']
mmdet_code/train_all_levir_baseline.py CHANGED
@@ -23,6 +23,11 @@ MODEL_CONFIGS = {
23
  "retinanet": "configs/retinanet/retinanet_r50_fpn_1x_coco.py",
24
  "faster_rcnn": "configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py",
25
  "fcos": "configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py",
 
 
 
 
 
26
  }
27
  SPLIT_RATIOS = {"train": 0.70, "val": 0.15, "test": 0.15}
28
  SCENE_RE = re.compile(r"^(.*)_(-?\d+)_(-?\d+)$")
@@ -391,7 +396,8 @@ def parse_args() -> argparse.Namespace:
391
  parser.add_argument(
392
  "--models",
393
  default="atss,retinanet,faster_rcnn,fcos",
394
- help="Comma-separated: atss, retinanet, faster_rcnn, fcos.",
 
395
  )
396
  parser.add_argument("--epochs", type=int, default=12)
397
  parser.add_argument("--batch-size", type=int, default=4)
 
23
  "retinanet": "configs/retinanet/retinanet_r50_fpn_1x_coco.py",
24
  "faster_rcnn": "configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py",
25
  "fcos": "configs/fcos/fcos_r50-caffe_fpn_gn-head_1x_coco.py",
26
+ "cascade_rcnn": "configs/cascade_rcnn/cascade-rcnn_r50_fpn_1x_coco.py",
27
+ "dala_retinanet": "configs/dala/retinanet_r50_fpn_dala_1x_coco.py",
28
+ "dala_faster_rcnn": "configs/dala/faster-rcnn_r50_fpn_dala_1x_coco.py",
29
+ "dala_fcos": "configs/dala/fcos_r50-caffe_fpn_dala_1x_coco.py",
30
+ "dala_cascade_rcnn": "configs/dala/cascade-rcnn_r50_fpn_dala_1x_coco.py",
31
  }
32
  SPLIT_RATIOS = {"train": 0.70, "val": 0.15, "test": 0.15}
33
  SCENE_RE = re.compile(r"^(.*)_(-?\d+)_(-?\d+)$")
 
396
  parser.add_argument(
397
  "--models",
398
  default="atss,retinanet,faster_rcnn,fcos",
399
+ help=("Comma-separated model keys. DALA keys: dala_faster_rcnn, "
400
+ "dala_retinanet, dala_fcos, dala_cascade_rcnn."),
401
  )
402
  parser.add_argument("--epochs", type=int, default=12)
403
  parser.add_argument("--batch-size", type=int, default=4)